<template>
  <div class="new-filter" :style="countChartStyle">
    <div
      v-for="(filter, index) of ext.filterList"
      :key="index"
      class="item"
      :style="countItemStyle"
    >
      <template v-if="filter.filterType == 'normal'">
        <div class="name">{{ filter.name }}</div>
        <div
          v-for="(condition, i) of filter.conditions"
          :key="i"
          class="condition"
        >
          <div class="value">
            <!-- 日期类型 -->
            <template v-if="filter.viewDataType == 'DATETIME'">
              <template v-if="filter.dateType == 'time'">
                <el-date-picker
                  size="mini"
                  v-model="condition.values"
                  type="datetimerange"
                  placeholder="选择日期时间"
                  :value-format="filter.dateFormat"
                >
                </el-date-picker>
              </template>
              <template v-else-if="['month', 'date'].includes(filter.dateType)">
                <el-date-picker
                  size="mini"
                  v-model="condition.values"
                  :type="filter.dateType + 'range'"
                  placeholder="选择日期"
                  :value-format="filter.dateFormat"
                >
                </el-date-picker>
              </template>
              <template v-else-if="filter.dateType == 'year'">
                <el-date-picker
                  size="mini"
                  v-model="condition.values[0]"
                  type="year"
                  placeholder="选择日期"
                  :value-format="filter.dateFormat"
                >
                </el-date-picker>
                <span>~</span>
                <el-date-picker
                  size="mini"
                  v-model="condition.values[1]"
                  type="year"
                  placeholder="选择日期"
                  :value-format="filter.dateFormat"
                >
                </el-date-picker>
              </template>
              <template v-else>
                <el-time-picker
                  is-range
                  size="mini"
                  v-model="condition.values"
                  placeholder="选择时间"
                  :value-format="filter.dateFormat"
                >
                </el-time-picker>
              </template>
              <el-popover
                placement="bottom-start"
                trigger="hover"
                popper-class="special-time-popover"
              >
                <el-button
                  size="mini"
                  slot="reference"
                  type="primary"
                  style="margin-left: 5px"
                >
                  快捷选择
                </el-button>
                <el-tag
                  size="mini"
                  type="primary"
                  @click="setQuickOption('hour', 23, index)"
                >
                  近24小时
                </el-tag>
                <el-tag
                  size="mini"
                  type="primary"
                  @click="setQuickOption('date', 6, index)"
                >
                  近7天
                </el-tag>
                <el-tag
                  size="mini"
                  type="primary"
                  @click="setQuickOption('date', 13, index)"
                >
                  近14天
                </el-tag>
                <el-tag
                  size="mini"
                  type="primary"
                  @click="setQuickOption('date', 30, index)"
                >
                  近1月
                </el-tag>
                <el-tag
                  size="mini"
                  type="primary"
                  @click="setQuickOption('month', 5, index)"
                >
                  近6月
                </el-tag>
                <el-tag
                  size="mini"
                  type="primary"
                  @click="setQuickOption('month', 11, index)"
                >
                  近一年
                </el-tag>
              </el-popover>
            </template>
            <template v-else>
              <template v-if="condition.function == 'in'">
                <el-cascader
                  size="mini"
                  v-model="condition.values"
                  :options="filter.options"
                  :props="{
                    expandTrigger: 'hover',
                    emitPath: false,
                    multiple: true,
                    label: 'VALUE',
                    value: 'VALUE',
                  }"
                  filterable
                  :show-all-levels="false"
                  collapse-tags
                  v-loading="OptionLoading"
                  clearable
                ></el-cascader>
                <el-button
                  size="mini"
                  @click="onEnumSelectAll(filter)"
                  type="primary"
                >
                  全选
                </el-button>
              </template>
              <template v-else>
                <el-input
                  size="mini"
                  v-model="condition.values[0]"
                  placeholder="输入值"
                ></el-input>
                <span v-if="condition.function == 'between'">~</span>
                <el-input
                  v-if="condition.function == 'between'"
                  size="mini"
                  v-model="condition.values[1]"
                  placeholder="输入值"
                ></el-input>
              </template>
            </template>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="name">日期</div>
        <el-form class="condition" size="mini" inline>
          <el-form-item>
            <el-button-group v-show="!filter.hidden">
              <el-button
                size="mini"
                :type="filter.dateType == 'QUARTER' ? 'primary' : ''"
                @click="filter.dateType = 'QUARTER'"
              >
                季度
              </el-button>
              <el-button
                size="mini"
                :type="filter.dateType == 'MONTH' ? 'primary' : ''"
                @click="filter.dateType = 'MONTH'"
              >
                月份
              </el-button>
              <el-button
                size="mini"
                :type="filter.dateType == 'DAY' ? 'primary' : ''"
                @click="filter.dateType = 'DAY'"
              >
                日
              </el-button>
            </el-button-group>
          </el-form-item>
          <el-form-item>
            <div class="abs">
              <template v-if="filter.dateType == 'QUARTER'">
                <vxe-input
                  v-model="filter.time[0]"
                  placeholder="季度选择"
                  type="quarter"
                  clearable
                  value-format="yyyyMM"
                  size="mini"
                ></vxe-input>
                <vxe-input
                  v-model="filter.time[1]"
                  placeholder="季度选择"
                  type="quarter"
                  clearable
                  value-format="yyyyMM"
                  size="mini"
                ></vxe-input>
              </template>
              <template v-if="filter.dateType == 'MONTH'">
                <el-date-picker
                  style="width: 290px"
                  v-model="filter.time"
                  type="monthrange"
                  placeholder="选择月份"
                  clearable
                  value-format="yyyyMM"
                >
                </el-date-picker>
              </template>
              <template v-if="filter.dateType == 'DAY'">
                <el-date-picker
                  style="width: 290px"
                  v-model="filter.time"
                  type="daterange"
                  placeholder="选择日期"
                  clearable
                  value-format="yyyyMMdd"
                >
                </el-date-picker>
              </template>
            </div>
          </el-form-item>
        </el-form>
        <el-popover
          placement="bottom-start"
          trigger="hover"
          popper-class="special-time-popover"
        >
          <el-button size="mini" slot="reference" type="primary">
            快捷选择
          </el-button>
          <el-tag
            v-show="filter.dateType == 'DAY'"
            size="mini"
            type="primary"
            @click="setSpecialQuickOption(7, index)"
          >
            近7天
          </el-tag>
          <el-tag
            v-show="filter.dateType == 'DAY'"
            size="mini"
            type="primary"
            @click="setSpecialQuickOption(15, index)"
          >
            近15天
          </el-tag>
          <el-tag
            v-show="['DAY', 'MONTH'].includes(filter.dateType)"
            size="mini"
            type="primary"
            @click="setSpecialQuickOption(30, index)"
          >
            近1月
          </el-tag>
          <el-tag
            v-show="['DAY', 'MONTH'].includes(filter.dateType)"
            size="mini"
            type="primary"
            @click="setSpecialQuickOption(182, index)"
          >
            近6月
          </el-tag>
          <el-tag
            v-show="['DAY', 'MONTH'].includes(filter.dateType)"
            size="mini"
            type="primary"
            @click="setSpecialQuickOption(365, index)"
          >
            近12月
          </el-tag>
          <el-tag
            size="mini"
            type="primary"
            @click="setSpecialQuickOption(90, index)"
          >
            近1季
          </el-tag>
          <el-tag
            size="mini"
            type="primary"
            @click="setSpecialQuickOption(365, index)"
          >
            近4季
          </el-tag>
        </el-popover>
      </template>
      <div class="icons" v-show="isEdit">
        <i class="el-icon el-icon-edit" @click="onFilterEdit(index)"></i>
        <i class="el-icon el-icon-delete" @click="onFilterDel(index)"></i>
      </div>
    </div>
    <div class="filter-btns">
      <el-dropdown @command="onAddFilter">
        <el-button size="mini" type="success" class="add-btn" v-show="isEdit">
          <i class="el-icon-plus"></i>
        </el-button>
        <template #dropdown>
            <el-dropdown-menu>
                <el-dropdown-item command="normal">标准过滤器</el-dropdown-item>
                <el-dropdown-item command="special">
                    联通时间过滤器
                </el-dropdown-item>
            </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button
        size="mini"
        type="primary"
        @click="previewAll"
        class="refresh-btn"
      >
        <i class="el-icon-search"></i>
      </el-button>
    </div>
    <el-dialog
      append-to-body
      :visible.sync="show"
      title="编辑筛选"
      custom-class="newbi-global-filter"
      v-if="filterForm"
    >
      <template v-if="filterForm.filterType == 'normal'">
        <el-form size="mini" label-width="100px">
          <el-form-item label="筛选器名称">
            <el-input v-model="filterForm.name"></el-input>
          </el-form-item>
          <el-form-item label="关联图表">
            <div
              v-for="chart of filterForm.chartList"
              :key="chart.chartKey"
              style="margin: 5px"
            >
              <el-checkbox
                v-model="chart.select"
                class="checkbox-item"
                @change="countTypeDisable"
              >
                {{ chart.chartTitle }}
              </el-checkbox>
              <el-select
                v-model="chart.fieldId"
                @change="onFieldChange(chart, $event)"
                placeholder="选择适用字段"
                filterable
                v-loading="chart.loading"
              >
                <el-option
                  v-for="field of chart.fields"
                  :key="field.id"
                  :label="field.columnTitle"
                  :value="field.id"
                ></el-option>
              </el-select>
            </div>
            <div
              class="tips"
              style="color: #e6a23c"
              v-show="filterForm.disable"
            >
              <i class="el-icon-info" style="margin-right: 5px"></i>
              {{ filterForm.disableMsg }}
            </div>
          </el-form-item>
          <template v-if="!filterForm.disable">
            <el-form-item label="枚举来源" v-show="countEnumShow()">
              <el-radio-group v-model="filterForm.enumSource">
                <el-radio label="1">原始数据聚合</el-radio>
                <el-radio label="2">api</el-radio>
              </el-radio-group>
              <el-button
                size="mini"
                icon="el-icon-share"
                plain
                type="success"
                @click="getEnumData(filterForm, true)"
                style="margin-left: 20px"
              >
                获取
              </el-button>
            </el-form-item>
            <el-form-item
              label="选择api"
              v-if="countEnumShow() && filterForm.enumSource == '2'"
            >
              <el-cascader
                v-model="filterForm.enumId"
                :options="apiList"
                :props="{ expandTrigger: 'hover', emitPath: false }"
                filterable
                popper-class="bigdata-data-selector"
                :show-all-levels="false"
              ></el-cascader>
            </el-form-item>
            <template v-if="filterForm.viewDataType == 'DATETIME'">
              <el-form-item label="计算方式">
                <el-radio-group
                  v-model="filterForm.timeType"
                  @change="countAbsoluteTime(filterForm)"
                >
                  <el-radio label="relative">相对时间</el-radio>
                  <el-radio label="absolute">绝对时间</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="相对单位选择"
                v-show="filterForm.timeType == 'relative'"
              >
                <el-select
                  v-model="filterForm.timeUnit"
                  @change="countAbsoluteTime(filterForm)"
                >
                  <el-option label="年" value="year"></el-option>
                  <el-option label="月" value="month"></el-option>
                  <el-option label="日" value="date"></el-option>
                  <el-option label="时" value="hour"></el-option>
                  <el-option label="分" value="minute"></el-option>
                  <el-option label="秒" value="second"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                v-show="filterForm.timeType == 'relative'"
                label="日期基准调整"
              >
                <el-select
                  v-model="filterForm.relativeCount"
                  style="width: 80px"
                  @change="countAbsoluteTime(filterForm)"
                >
                  <el-option label="往前" value="left"></el-option>
                  <el-option label="往后" value="right"></el-option>
                </el-select>
                <el-input
                  v-model="filterForm.relativeSize"
                  style="width: 80px"
                  @input="countAbsoluteTime(filterForm)"
                >
                  <template slot="append">
                    {{ timeAppendMap[filterForm.timeUnit] }}
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item
                label="相对时间设置"
                v-if="filterForm.timeType == 'relative'"
              >
                <el-input
                  v-model="filterForm.value1"
                  style="width: 110px"
                  @input="countAbsoluteTime(filterForm)"
                >
                  <template slot="append">
                    {{ timeAppendMap[filterForm.timeUnit] }}
                  </template>
                </el-input>
                <el-select
                  v-model="filterForm.count1"
                  style="width: 60px"
                  @change="countAbsoluteTime(filterForm)"
                >
                  <el-option label="前" value="left"> </el-option>
                  <el-option label="后" value="right"> </el-option>
                </el-select>
                <span style="margin: 0 10px">~</span>
                <el-input
                  v-model="filterForm.value2"
                  style="width: 110px"
                  @input="countAbsoluteTime(filterForm)"
                >
                  <template slot="append">
                    {{ timeAppendMap[filterForm.timeUnit] }}
                  </template>
                </el-input>
                <el-select
                  v-model="filterForm.count2"
                  style="width: 60px"
                  @change="countAbsoluteTime(filterForm)"
                >
                  <el-option label="前" value="left"> </el-option>
                  <el-option label="后" value="right"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="日期值">
                <template v-if="filterForm.dateType == 'time'">
                  <el-date-picker
                    style="width: 320px"
                    v-model="filterForm.conditions[0].values"
                    type="datetimerange"
                    placeholder="选择日期时间"
                    :value-format="filterForm.dateFormat"
                    :disabled="filterForm.timeType == 'relative'"
                  >
                  </el-date-picker>
                </template>
                <template
                  v-else-if="['month', 'date'].includes(filterForm.dateType)"
                >
                  <el-date-picker
                    style="width: 320px"
                    v-model="filterForm.conditions[0].values"
                    :type="filterForm.dateType + 'range'"
                    placeholder="选择日期"
                    :value-format="filterForm.dateFormat"
                    :disabled="filterForm.timeType == 'relative'"
                  >
                  </el-date-picker>
                </template>
                <template v-else-if="filterForm.dateType == 'year'">
                  <el-date-picker
                    style="width: 150px"
                    v-model="filterForm.conditions[0].values[0]"
                    type="year"
                    placeholder="选择日期"
                    :value-format="filterForm.dateFormat"
                    :disabled="filterForm.timeType == 'relative'"
                  >
                  </el-date-picker>
                  <span>~</span>
                  <el-date-picker
                    style="width: 150px"
                    v-model="filterForm.conditions[0].values[1]"
                    type="year"
                    placeholder="选择日期"
                    :value-format="filterForm.dateFormat"
                    :disabled="filterForm.timeType == 'relative'"
                  >
                  </el-date-picker>
                </template>
                <template v-else>
                  <el-time-picker
                    is-range
                    style="width: 320px"
                    v-model="filterForm.conditions[0].values"
                    placeholder="选择时间"
                    :value-format="filterForm.dateFormat"
                    :disabled="filterForm.timeType == 'relative'"
                  >
                  </el-time-picker>
                </template>
              </el-form-item>
            </template>
            <el-form-item label="过滤条件" v-else>
              <div
                class="filter-item"
                v-for="(condition, i) of filterForm.conditions"
                :key="i"
              >
                <el-select
                  size="mini"
                  v-model="condition.function"
                  style="width: 100px; margin-right: 10px"
                  placeholder="选择条件"
                  @change="onFunctionChange($event, i)"
                >
                  <el-option
                    v-for="func of globalFunctions[filterForm.viewDataType]"
                    :key="func.function"
                    :value="func.function"
                    :label="func.label"
                  ></el-option>
                </el-select>
                <template v-if="condition.function == 'in'">
                  <el-cascader
                    size="mini"
                    v-model="condition.values"
                    :options="filterForm.options"
                    :props="{
                      expandTrigger: 'hover',
                      emitPath: false,
                      multiple: true,
                      label: 'VALUE',
                      value: 'VALUE',
                    }"
                    filterable
                    :show-all-levels="false"
                    collapse-tags
                    clearable
                  ></el-cascader>
                  <el-button
                    size="mini"
                    @click="onEnumSelectAll(filterForm)"
                    type="primary"
                  >
                    全选
                  </el-button>
                </template>
                <template v-else>
                  <el-input
                    style="width: 170px"
                    size="mini"
                    v-model="condition.values[0]"
                    placeholder="输入值"
                  ></el-input>
                  <span v-if="condition.function == 'between'">~</span>
                  <el-input
                    v-if="condition.function == 'between'"
                    style="width: 170px"
                    size="mini"
                    v-model="condition.values[1]"
                    placeholder="输入值"
                  ></el-input>
                </template>
              </div>
            </el-form-item>
          </template>
        </el-form>
      </template>
      <template v-else>
        <el-form size="mini" label-width="100px">
          <el-form-item label="时间格式">
            <el-radio-group
              v-model="filterForm.dateType"
              @change="countSpecialAbsoluteTime(filterForm)"
            >
              <el-radio label="QUARTER">季度</el-radio>
              <el-radio label="MONTH">月份</el-radio>
              <el-radio label="DAY">日</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="隐藏时间格式">
            <el-switch v-model="filterForm.hidden"></el-switch>
          </el-form-item>
          <el-form-item label="计算方式">
            <el-radio-group
              v-model="filterForm.timeType"
              @change="countSpecialAbsoluteTime(filterForm)"
            >
              <el-radio label="relative">相对时间</el-radio>
              <el-radio label="absolute">绝对时间</el-radio>
              <el-radio
                label="themonth"
                :disabled="filterForm.dateType != 'DAY'"
              >
                本月
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-show="filterForm.timeType == 'relative'"
            label="日期基准调整"
          >
            <el-select
              v-model="filterForm.relativeCount"
              style="width: 80px"
              @change="countSpecialAbsoluteTime(filterForm)"
            >
              <el-option label="往前" value="left"></el-option>
              <el-option label="往后" value="right"></el-option>
            </el-select>
            <el-input
              v-model="filterForm.relativeSize"
              style="width: 80px"
              @input="countSpecialAbsoluteTime(filterForm)"
            >
              <template slot="append">
                {{ specialDateTypeMap[filterForm.dateType] }}
              </template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="相对时间设置"
            v-if="filterForm.timeType == 'relative'"
          >
            <el-input
              v-model="filterForm.value1"
              style="width: 110px"
              @input="countSpecialAbsoluteTime(filterForm)"
            >
              <template slot="append">
                {{ specialDateTypeMap[filterForm.dateType] }}
              </template>
            </el-input>
            <el-select
              v-model="filterForm.count1"
              style="width: 60px"
              @change="countSpecialAbsoluteTime(filterForm)"
            >
              <el-option label="前" value="left"> </el-option>
              <el-option label="后" value="right"> </el-option>
            </el-select>
            <span style="margin: 0 10px">~</span>
            <el-input
              v-model="filterForm.value2"
              style="width: 110px"
              @input="countSpecialAbsoluteTime(filterForm)"
            >
              <template slot="append">
                {{ specialDateTypeMap[filterForm.dateType] }}
              </template>
            </el-input>
            <el-select
              v-model="filterForm.count2"
              style="width: 60px"
              @change="countSpecialAbsoluteTime(filterForm)"
            >
              <el-option label="前" value="left"> </el-option>
              <el-option label="后" value="right"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="filterForm.timeType == 'themonth'"
            label="前推一天"
          >
            <el-switch
              v-model="filterForm.forward"
              @change="countSpecialAbsoluteTime(filterForm)"
            ></el-switch>
          </el-form-item>
          <el-form-item label="日期值">
            <template v-if="filterForm.dateType == 'QUARTER'">
              <vxe-input
                v-model="filterForm.time[0]"
                placeholder="季度选择"
                type="quarter"
                clearable
                value-format="yyyyMM"
                :disabled="filterForm.timeType != 'absolute'"
              ></vxe-input>
              <vxe-input
                v-model="filterForm.time[1]"
                placeholder="季度选择"
                type="quarter"
                clearable
                value-format="yyyyMM"
                :disabled="filterForm.timeType != 'absolute'"
              ></vxe-input>
            </template>
            <template v-if="filterForm.dateType == 'MONTH'">
              <el-date-picker
                v-model="filterForm.time"
                type="monthrange"
                placeholder="选择月份"
                clearable
                value-format="yyyyMM"
                :disabled="filterForm.timeType != 'absolute'"
              >
              </el-date-picker>
            </template>
            <template v-if="filterForm.dateType == 'DAY'">
              <el-date-picker
                v-model="filterForm.time"
                type="daterange"
                placeholder="选择日期"
                clearable
                value-format="yyyyMMdd"
                :disabled="filterForm.timeType != 'absolute'"
              >
              </el-date-picker>
            </template>
          </el-form-item>
          <el-form-item label="图表设置">
            <el-table size="mini" :data="filterForm.chartList">
              <el-table-column label="图表选择">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.select"></el-checkbox>
                  {{ scope.row.chartTitle }}
                </template>
              </el-table-column>
              <el-table-column label="时间维度类型" width="200px">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.tid"
                    @change="onTidChange($event, scope.row)"
                    filterable
                  >
                    <el-option label="不选择" value=""></el-option>
                    <el-option
                      v-for="i of scope.row.fields"
                      :key="i.id"
                      :label="i.columnTitle + '【' + i.columnName + '】'"
                      :value="i.id"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="时间维度值" width="200px">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.vid"
                    @change="onVidChange($event, scope.row)"
                    filterable
                  >
                    <el-option label="不选择" value=""></el-option>
                    <el-option
                      v-for="i of scope.row.fields"
                      :key="i.id"
                      :label="i.columnTitle + '【' + i.columnName + '】'"
                      :value="i.id"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </template>
      <div class="btns">
        <el-button size="small" @click="show = false">取消</el-button>
        <el-button size="small" type="primary" @click="onAddFilterConfirm">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { cubeFieldList } from "../../api/newbi/dataset";
import { optionList } from "../../api/newbi/bigdata";
import {
  dataapicategoryList,
  dataapiList,
  dataapiDetail,
  openurl,
} from "../../api/report/report";
import {
  fieldDateFormats,
  dateTypeMap,
  globalFunctions,
  timeAppendMap,
} from "../../pages/newbi/dict";
import moment from "moment";
export default {
  props: ["option", "charts", "chartId", "ext", "isEdit"],
  data() {
    return {
      fieldDateFormats,
      dateTypeMap,
      globalFunctions,
      timeAppendMap,
      show: false,
      filterForm: null,
      OptionLoading: false,
      itemIndex: -1,
      apiList: [],
      specialDateTypeMap: {
        DAY: "天",
        MONTH: "月",
        QUARTER: "季",
      },
    };
  },
  computed: {
    chartList() {
      let arr = this.charts
        .filter((i) => {
          if (!i.dataconfig) return false;
          if (i.dataconfig.dataType != "CUBE") return false;
          return true;
        })
        .map((i) => {
          let chart = {
            chartTitle: i.title,
            chartKey: i.key,
            cubeDataId: i.dataconfig.dataId,
            fields: [],
            loading: false,
          };
          this.setChartField(chart);
          return chart;
        });
      return arr;
    },
    countChartStyle() {
      let { outBorderStyle, outBorderColor } = this.option;
      return {
        border: `1px ${outBorderStyle} ${outBorderColor}`,
      };
    },
    countItemStyle() {
      let { inBorderStyle, inBorderColor } = this.option;
      return {
        border: `1px ${inBorderStyle} ${inBorderColor}`,
      };
    },
  },
  created() {
    if (!this.chartId) {
      this.$set(this.ext, "filterList", []);
    } else {
      this.ext.filterList.forEach((f) => {
        if (f.filterType == "special") {
          this.countSpecialAbsoluteTime(f);
        } else {
          if (!f.conditions) return;
          if (!f.conditions.length) return;
          if (f.viewDataType == "DATETIME") {
            this.countAbsoluteTime(f);
          } else {
            let func = f.conditions[0].function;
            if (func != "in" && func != "notIn") return;
            this.getEnumData(f, false);
          }
        }
      });
    }
    // 获取api列表
    dataapicategoryList().then((res) => {
      let category = res.data.data;
      dataapiList({ apiFormal: 1, apiType: 1 }).then((res) => {
        let list = res.data.data;
        this.apiList = category
          .map((i) => {
            return {
              label: i.categoryName,
              value: i.id,
              children: list
                .filter((j) => j.categoryId == i.id)
                .map((k) => ({ label: k.apiName, value: k.id })),
            };
          })
          .filter((i) => i.children.length);
      });
    });
  },
  methods: {
    some() {
      console.log(this.ext.filterList);
    },
    // 整理可选项树状结构
    countTreeOptions(originData) {
      originData.forEach((i) => (i.children = []));
      let parents = [...originData];
      let res = [],
        childrens = [];
      originData.forEach((i) => {
        if (i.PID == "0") {
          res.push(i);
        } else {
          childrens.push(i);
        }
      });
      childrens.forEach((i) => {
        let parent = parents.find((j) => j.ID == i.PID);
        if (parent) {
          parent.children.push(i);
        }
      });
      return res;
    },
    getOptionValue(arr, item) {
      if (item.children) {
        item.children.forEach((i) => {
          this.getOptionValue(arr, i);
        });
      } else {
        arr.push(item.VALUE);
      }
    },
    onEnumSelectAll(filter) {
      let options = filter.options;
      let arr = [];
      options.forEach((i) => this.getOptionValue(arr, i));
      filter.conditions[0].values = arr;
    },
    // 根据月份计算季度
    countQuarter(month) {
      if (month < 4) return 1;
      if (month < 7) return 2;
      if (month < 10) return 3;
      return 4;
    },
    // 根据相对时间计算绝对时间|联通时间
    countSpecialAbsoluteTime(filter) {
      let {
        count1,
        count2,
        value1,
        value2,
        dateType,
        relativeSize,
        relativeCount,
        timeType,
      } = filter;
      if (timeType == "relative") {
        let v1, v2;
        let date1 = new Date();
        let date2 = new Date();
        value1 = parseInt(value1);
        value2 = parseInt(value2);
        let count =
          relativeCount == "left"
            ? -parseInt(relativeSize)
            : parseInt(relativeSize);
        if (dateType == "QUARTER") {
          date1.setMonth(date1.getMonth() + count * 3);
          date2.setMonth(date2.getMonth() + count * 3);
          let month = date1.getMonth() + 1;
          date1.setMonth(month + (count1 == "left" ? -value1 * 3 : value1 * 3));
          date2.setMonth(month + (count2 == "left" ? -value2 * 3 : value2 * 3));
          v1 =
            date1.getFullYear() + "" + this.countQuarter(date1.getMonth() + 1);
          v2 =
            date2.getFullYear() + "" + this.countQuarter(date2.getMonth() + 1);
        } else if (dateType == "MONTH") {
          date1.setMonth(date1.getMonth() + count);
          date2.setMonth(date2.getMonth() + count);
          let month = date1.getMonth();
          date1.setMonth(month + (count1 == "left" ? -value1 : value1));
          date2.setMonth(month + (count2 == "left" ? -value2 : value2));
          v1 = moment(date1).format("yyyyMM");
          v2 = moment(date2).format("yyyyMM");
        } else {
          date1.setDate(date1.getDate() + count);
          date2.setDate(date2.getDate() + count);
          let day = date1.getDate();
          date1.setDate(day + (count1 == "left" ? -value1 : value1));
          date2.setDate(day + (count2 == "left" ? -value2 : value2));
          v1 = moment(date1).format("yyyyMMDD");
          v2 = moment(date2).format("yyyyMMDD");
        }
        filter.time = [v1, v2];
      } else if (timeType == "themonth") {
        let date1 = new Date();
        let date2 = new Date();
        date1.setDate(1);
        if (filter.forward) {
          if (date2.getDate() == 1) {
            date1.setMonth(date1.getMonth() - 1);
          }
          date2.setDate(date2.getDate() - 1);
        }
        let v1 = moment(date1).format("yyyyMMDD");
        let v2 = moment(date2).format("yyyyMMDD");
        filter.time = [v1, v2];
      }
    },
    // 根据相对时间计算绝对时间
    countAbsoluteTime(filter) {
      let {
        count1,
        count2,
        value1,
        value2,
        relativeSize,
        relativeCount,
        timeType,
        timeUnit,
        dateFormat,
      } = filter;
      if (timeType == "absolute") return;
      dateFormat = dateFormat.replaceAll("d", "D");
      let date1 = new Date();
      let date2 = new Date();
      value1 = count1 == "left" ? -parseInt(value1) : parseInt(value1);
      value2 = count2 == "left" ? -parseInt(value2) : parseInt(value2);
      let count =
        relativeCount == "left"
          ? -parseInt(relativeSize)
          : parseInt(relativeSize);
      if (timeUnit == "year") {
        date1.setFullYear(date1.getFullYear() + count);
        date2.setFullYear(date2.getFullYear() + count);
        let origin = date1.getFullYear();
        date1.setFullYear(origin + value1);
        date2.setFullYear(origin + value2);
      } else if (timeUnit == "month") {
        date1.setMonth(date1.getMonth() + count);
        date2.setMonth(date2.getMonth() + count);
        let origin = date1.getMonth();
        date1.setMonth(origin + value1);
        date2.setMonth(origin + value2);
      } else if (timeUnit == "date") {
        date1.setDate(date1.getDate() + count);
        date2.setDate(date2.getDate() + count);
        let origin = date1.getDate();
        date1.setDate(origin + value1);
        date2.setDate(origin + value2);
      } else if (timeUnit == "hour") {
        date1.setHours(date1.getHours() + count);
        date2.setHours(date2.getHours() + count);
        let origin = date1.getHours();
        date1.setHours(origin + value1);
        date2.setHours(origin + value2);
      } else if (timeUnit == "minute") {
        date1.setMinutes(date1.getMinutes() + count);
        date2.setMinutes(date2.getMinutes() + count);
        let origin = date1.getMinutes();
        date1.setMinutes(origin + value1);
        date2.setMinutes(origin + value2);
      } else if (timeUnit == "second") {
        date1.setSeconds(date1.getSeconds() + count);
        date2.setSeconds(date2.getSeconds() + count);
        let origin = date1.getSeconds();
        date1.setSeconds(origin + value1);
        date2.setSeconds(origin + value2);
      }
      let v1 = moment(date1).format(dateFormat);
      let v2 = moment(date2).format(dateFormat);
      filter.conditions[0].values = [v1, v2];
    },
    // 保存前去掉可选值列表
    beforeSave() {
      this.ext.filterList.forEach((i) => (i.options = []));
    },
    // 获取枚举可选值
    getEnumData(filter, isEdit) {
      let { enumSource, enumId } = filter;
      if (enumSource == "1") {
        this.OptionLoading = true;
        let opts = [];
        let charts = filter.chartList;
        if (isEdit) {
          charts = charts.filter((i) => i.select);
        }
        let tasks = charts.map((i) => {
          return new Promise((r, j) => {
            let { tableName, columnName } = i.field;
            optionList({
              tableName,
              columnName,
              cubeDataId: i.cubeDataId,
            }).then((res) => {
              opts = opts.concat(res.data.data.map((i) => i[columnName]));
              r();
            });
          });
        });
        Promise.all(tasks)
          .then(() => {
            filter.options = XEUtils.uniq(opts).map((i) => ({
              VALUE: i,
            }));
          })
          .finally((_) => (this.OptionLoading = false));
      } else {
        if (!enumId) {
          return this.$message({ message: "请选择api", type: "warning" });
        }
        this.OptionLoading = true;
        dataapiDetail(enumId).then((res) => {
          let { apiKey } = res.data.data;
          openurl(apiKey).then((res) => {
            this.OptionLoading = false;
            let data = res.data.data;
            if (!data.length) {
              filter.options = data;
              return;
            }
            if (data[0].ID) {
              let tree = this.countTreeOptions(data);
              tree.forEach(this.clearChildren);
              filter.options = tree;
            } else {
              filter.options = data;
            }
          });
        });
      }
    },
    // 去掉为空的children
    clearChildren(node) {
      if (!node.children) return;
      if (!node.children.length) {
        delete node.children;
      } else {
        node.children.forEach(this.clearChildren);
      }
    },
    // 判断是否展示枚举选项
    countEnumShow() {
      if (!this.filterForm.conditions.length) return false;
      let func = this.filterForm.conditions[0].function;
      if (func == "in") return true;
      return false;
    },
    // 获取图表字段配置
    setChartField(chart) {
      return new Promise((resolve) => {
        if (chart.fields.length) {
          resolve();
        }
        chart.loading = true;
        cubeFieldList({ cubeDataId: chart.cubeDataId }).then((res) => {
          chart.fields = res.data.data.map((f) => {
            if (f.viewDataType == "DATETIME") {
              let { timeDataFormat } = f;
              f.dateType = this.dateTypeMap[timeDataFormat];
              f.dateFormat = this.fieldDateFormats.find(
                (k) => k.value == timeDataFormat
              ).label;
            }
            return f;
          });
          chart.loading = false;
          resolve();
        });
      });
    },
    previewAll() {
      this.$bus.$emit("previewAll", this.ext.filterList);
    },
    // 设置快捷选项时|联通时间
    setSpecialQuickOption(size, index) {
      let filter = this.ext.filterList[index];
      if (filter.dateType == "MONTH") {
        size = Math.floor(size / 30);
      } else if (filter.dateType == "QUARTER") {
        size = Math.floor(size / 90);
      }
      filter.timeType = "relative";
      filter.relativeCount = "left";
      filter.relativeSize = 0;
      filter.count1 = "left";
      filter.count2 = "left";
      filter.value1 = size;
      filter.value2 = 1;
      this.countSpecialAbsoluteTime(filter);
    },
    // 设置快捷选项时
    setQuickOption(type, size, index) {
      let filter = this.ext.filterList[index];
      filter.timeType = "relative";
      filter.relativeCount = "left";
      filter.relativeSize = 1;
      filter.timeUnit = type;
      filter.count1 = "left";
      filter.count2 = "left";
      filter.value1 = size;
      filter.value2 = 0;
      this.countAbsoluteTime(filter);
    },
    // 编辑某项筛选
    onFilterEdit(index) {
      this.itemIndex = index;
      let data = {
        ...this.ext.filterList[index],
      };
      if (data.filterType == "normal") {
        data.chartList = this.chartList.map((i) => {
          let chart = {
            ...i,
            select: false,
            fieldId: "",
            field: null,
          };
          let past = this.ext.filterList[index].chartList.find(
            (j) => j.chartKey == i.chartKey
          );
          if (past) {
            chart.select = true;
            chart.fieldId = past.fieldId;
            this.setChartField(chart).then((_) => {
              chart.field = i.fields.find((j) => j.id == past.fieldId);
            });
          }
          this.setChartField(chart);
          return chart;
        });
      } else {
        data.chartList = this.chartList.map((i) => {
          let chart = {
            ...i,
            select: false,
            tid: "",
            tfield: null,
            vid: "",
            vfield: null,
          };
          let past = data.chartList.find((j) => j.chartKey == i.chartKey);
          if (past) {
            chart.select = true;
            chart.tid = past.tid;
            chart.tfield = i.fields.find((j) => j.id == past.tid);
            chart.vid = past.vid;
            chart.vfield = i.fields.find((j) => j.id == past.vid);
          }
          this.setChartField(chart);
          return chart;
        });
      }
      this.filterForm = data;
      this.show = true;
    },
    onTidChange(id, chart) {
      chart.tfield = chart.fields.find((i) => i.id == id);
    },
    onVidChange(id, chart) {
      chart.vfield = chart.fields.find((i) => i.id == id);
    },
    // 删除某项筛选
    onFilterDel(index) {
      this.ext.filterList.splice(index, 1);
    },
    // 计算函数变化时
    onFunctionChange(func, index) {
      if (func == "in") {
        this.filterForm.conditions = [{ function: func, values: [] }];
      } else {
        this.filterForm.conditions[index].values = ["", ""];
      }
    },
    // 计算是否可添加过滤条件
    countTypeDisable() {
      let charts = this.filterForm.chartList.filter((i) => i.select);
      if (!charts.length) {
        this.filterForm.disableMsg = "请选择至少一个图表";
        this.filterForm.disable = true;
        this.filterForm.conditions = [];
        return;
      }
      if (charts.find((i) => !i.fieldId)) {
        this.filterForm.disableMsg = "请选择图表适用字段";
        this.filterForm.disable = true;
        this.filterForm.conditions = [];
        return;
      }
      let { viewDataType, dateType } = charts[0].field;
      for (let i = 1; i < charts.length; i++) {
        if (viewDataType != charts[i].field.viewDataType) {
          this.filterForm.disableMsg = "所选图表字段的数据类型不一致";
          this.filterForm.disable = true;
          this.filterForm.conditions = [];
          return;
        }
      }
      if (viewDataType == "DATETIME") {
        for (let i = 1; i < charts.length; i++) {
          if (dateType != charts[i].field.dateType) {
            this.filterForm.disableMsg = "所选图表字段的日期格式类型不一致";
            this.filterForm.disable = true;
            this.filterForm.conditions = [];
            return;
          }
        }
      }
      let { dateFormat } = charts[0].field;
      this.filterForm.viewDataType = viewDataType;
      this.filterForm.dateType = dateType;
      this.filterForm.dateFormat = dateFormat;
      this.filterForm.disableMsg = "";
      this.filterForm.disable = false;
      let func = "eq";
      if (viewDataType == "STRING") func = "like";
      if (viewDataType == "DATETIME") func = "between";
      this.filterForm.conditions = [
        {
          function: func,
          values: ["", ""],
        },
      ];
      if (viewDataType == "DATETIME") {
        this.countAbsoluteTime(this.filterForm);
      }
    },
    // 某图表选择过滤字段时
    onFieldChange(chart, fieldId) {
      chart.field = chart.fields.find((i) => i.id == fieldId);
      this.countTypeDisable();
    },
    // 添加一个筛选器
    onAddFilter(command) {
      this.filterType = command;
      if (this.filterType == "normal") {
        this.filterForm = {
          filterType: "normal",
          name: "未命名",
          chartList: this.chartList.map((i) => {
            let chart = {
              ...i,
              select: false,
              fieldId: "",
              field: null,
            };
            this.setChartField(chart);
            return chart;
          }),
          disable: false,
          disableMsg: "",
          viewDataType: "",
          dateType: "",
          dateFormat: "",
          connectType: "and",
          conditions: [],
          options: [],
          enumSource: "1",
          enumId: "",
          value1: 29,
          value2: 0,
          count1: "left",
          count2: "left",
          timeType: "relative",
          relativeCount: "left",
          relativeSize: 1,
          timeUnit: "date",
        };
      } else {
        this.filterForm = {
          filterType: "special",
          dateType: "DAY", // quarter month day
          value1: 29,
          value2: 0,
          count1: "left",
          count2: "left",
          timeType: "relative",
          relativeCount: "left",
          relativeSize: 1,
          hidden: false,
          forward: true,
          chartList: this.chartList.map((i) => {
            let chart = {
              ...i,
              select: false,
              tid: "",
              tfield: null,
              vid: "",
              vfield: null,
            };
            this.setChartField(chart);
            return chart;
          }),
          time: ["", ""],
        };
        this.countSpecialAbsoluteTime(this.filterForm);
      }
      this.itemIndex = -1;
      this.show = true;
    },
    // 筛选器编辑完成时
    onAddFilterConfirm() {
      let data = JSON.parse(JSON.stringify(this.filterForm));
      if (this.filterForm.filterType == "normal") {
        if (this.filterForm.disable) {
          return this.$message({
            message: this.filterForm.disableMsg,
            type: "warning",
          });
        }
        if (!this.filterForm.conditions.length) {
          return this.$message({
            message: "请添加过滤条件",
            type: "warning",
          });
        }
        data.chartList = data.chartList
          .filter((i) => i.select)
          .map((i) => {
            return {
              chartKey: i.chartKey,
              chartTitle: i.chartTitle,
              cubeDataId: i.cubeDataId,
              fieldId: i.fieldId,
              tableName: i.field.tableName,
              columnName: i.field.columnName,
              field: i.field,
            };
          });
      } else {
        data.chartList = data.chartList
          .filter((i) => i.select)
          .map((i) => {
            return {
              chartKey: i.chartKey,
              chartTitle: i.chartTitle,
              cubeDataId: i.cubeDataId,
              tid: i.tid,
              tfield: i.fields.find((j) => j.id == i.tid),
              vid: i.vid,
              vfield: i.fields.find((j) => j.id == i.vid),
            };
          });
      }
      if (this.itemIndex == -1) {
        this.ext.filterList.push(data);
      } else {
        this.ext.filterList.splice(this.itemIndex, 1, data);
      }
      this.show = false;
    },
  },
};
</script>
<style lang="scss">
.new-filter {
  align-items: center;
  display: flex;
  padding-right: 10px;
  flex-wrap: wrap;
  .filter-btns {
    position: absolute;
    right: 0;
    display: flex;
    .el-button {
      display: block;
      & + .el-button {
        margin-left: 5px;
      }
    }
  }
  .item {
    border: 1px dashed #ccc;
    font-size: 14px;
    float: left;
    display: flex;
    align-items: center;
    margin-left: 5px;
    .name {
      font-weight: 600;
      padding: 0 5px;
    }
    .condition {
      display: flex;
      align-items: center;
      margin: 5px;
      .func {
        margin-right: 5px;
        flex: 0 0 56px;
        text-align: center;
      }
      .el-input {
        width: 170px;
      }
    }
    .icons {
      display: flex;
      flex-direction: column;
      padding: 0 5px;
      .el-icon {
        cursor: pointer;
        & + .el-icon {
          margin-top: 5px;
        }
      }
    }
  }
  .el-cascader {
    height: 28px;
    width: 240px;
    .el-input {
      width: 100% !important;
      height: 100% !important;
      .el-input__inner {
        height: 100% !important;
      }
    }
    .el-cascader__tags {
      flex-wrap: nowrap;
      overflow: hidden;
    }
  }
  .condition {
    .el-form-item {
      margin-bottom: 0px;
    }
  }
  .abs {
    .el-input,
    .vxe-input {
      margin-top: 2px;
      width: 140px;
      & + * {
        margin-left: 10px;
      }
    }
  }
  .rel {
    .el-input-group__append {
      padding: 0 12px;
    }
    .el-input__inner {
      text-align: center;
    }
  }
}
.newbi-global-filter {
  width: 700px;
  .btns {
    display: flex;
    justify-content: space-evenly;
    margin-top: 20px;
    .el-button {
      width: 120px;
    }
  }
  .checkbox-item .el-checkbox__label {
    line-height: 14px;
    width: 230px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .filter-item {
    margin-bottom: 5px;
  }
  .el-input-group__append {
    padding: 0 12px;
  }
}
.newbi-select-filter {
  width: 300px;
  .btns {
    display: flex;
    justify-content: space-evenly;
    margin-top: 20px;
    .el-button {
      width: 120px;
    }
  }
}
</style>
