<template>
  <div class="new-filter-box">
    <el-dialog append-to-body :visible.sync="show" title="编辑筛选" custom-class="newbi-global-filter" v-if="filterForm">
      <template v-if="filterForm.__config__.layout === 'colFormItem'">
        <el-form size="mini" label-width="100px">
          <div class="tips" style="color: #e6a23c; padding: 0 20px 10px" v-show="filterForm.disable"><i class="el-icon-info" style="margin-right: 5px"></i> {{ filterForm.disableMsg }}</div>
          <el-form-item label="筛选器名称">
            <el-input v-model="filterForm.__config__.label"></el-input>
          </el-form-item>
          <template v-if="!filterForm.disable">
            <el-form-item label="枚举来源" v-show="countEnumShow()">
              <el-radio-group @change="wallpaperInput" v-model="filterForm.enumSource">
                <!--                <el-radio label="1" v-show="filterForm.__config__.viewDataType === 'STRING'">原始数据聚合</el-radio>-->
                <el-radio label="2">api</el-radio>
                <el-radio label="3">自定义字典</el-radio>
              </el-radio-group>
              <el-button size="mini" type="primary" @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
                @change="selectApiChange"
                ref="selectApi"
                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>
            <el-form-item label="key值:" v-if="countEnumShow() && filterForm.enumSource === '2'">
              <el-select v-if="filterForm.apiProps" @change="wallpaperInput" v-model="filterForm.apiProps.value">
                <el-option v-for="(item, i) of showFields" :key="i" :value="item.columnComments" :label="item.columnName"></el-option>
              </el-select>
              value值：<el-select v-if="filterForm.apiProps" @change="wallpaperInput" v-model="filterForm.apiProps.label">
                <el-option v-for="(item, i) of showFields" :key="i" :value="item.columnComments" :label="item.columnName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数据级联" v-if="countEnumShow() && filterForm.enumSource === '2'">
              <el-switch v-model="filterForm.cascadeSwitch" @change="wallpaperInput"></el-switch>
            </el-form-item>
            <template v-if="countEnumShow() && filterForm.enumSource === '2' && filterForm.cascadeSwitch">
              <el-divider>级联节点设置</el-divider>
              <el-form-item label="子节点值:">
                <el-select v-if="filterForm.cascadeSet" placeholder="请选择子节点值" @change="wallpaperInput" v-model="filterForm.cascadeSet.idKey">
                  <el-option v-for="(item, i) of showFields" :key="i" :value="item.columnComments" :label="item.columnName"></el-option>
                </el-select>
                父节点值：<el-select v-if="filterForm.cascadeSet" placeholder="请选择父节点值" @change="wallpaperInput" v-model="filterForm.cascadeSet.pidKey">
                  <el-option v-for="(item, i) of showFields" :key="i" :value="item.columnComments" :label="item.columnName"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="子级键名">
                <el-input style="width: 200px" v-if="filterForm.cascadeSet" v-model="filterForm.cascadeSet.childrenName" placeholder="请输入子级键名" />
              </el-form-item>
            </template>
            <el-form-item label="选择字典" v-if="countEnumShow() && filterForm.enumSource === '3'">
              <el-select @change="wallpaperInput" v-model="filterForm.enumId">
                <el-option v-for="(item, i) of dictList" :key="i" :value="item.id" :label="item.keyCode"></el-option>
              </el-select>
            </el-form-item>
            <template v-if="filterForm.__config__.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
                    @input="countAbsoluteTime(filterForm)"
                    style="width: 321px"
                    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-button size="mini" style="margin-left: 10px" v-show="filterForm.timeType === 'absolute'" @click="onClearTime(filterForm)"> 清空 </el-button>
              </el-form-item>
            </template>
            <el-form-item label="过滤条件" v-else-if="filterForm.__config__.viewDataType === 'STRING' || filterForm.__config__.viewDataType === 'APIS'">
              <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.__config__.viewDataType]" :key="func.function" :value="func.function" :label="func.label"></el-option>
                </el-select>
                <el-input v-if="condition.function === 'like'" style="width: 170px" size="mini" v-model="condition.values[0]" placeholder="输入值" @input="wallpaperInput"></el-input>
                <template v-else>
                  <el-cascader
                    v-if="condition.function === 'in'"
                    size="mini"
                    v-model="condition.values"
                    @change="wallpaperInput"
                    :props="{
                      expandTrigger: 'hover',
                      emitPath: false,
                      multiple: true,
                      label: 'VALUE',
                      value: 'KEY',
                      children: filterForm.cascadeSet && filterForm.cascadeSet.childrenName ? filterForm.cascadeSet.childrenName : ''
                    }"
                    filterable
                    :show-all-levels="false"
                    collapse-tags
                    clearable
                    :options="filterForm.options"
                    :ref="index + '--'"
                  ></el-cascader>
                  <el-cascader
                    v-if="condition.function === 'eq'"
                    size="mini"
                    v-model="condition.values[0]"
                    @change="wallpaperInput"
                    :props="{
                      expandTrigger: 'hover',
                      emitPath: false,
                      multiple: false,
                      label: 'VALUE',
                      value: 'KEY',
                      children: filterForm.cascadeSet && filterForm.cascadeSet.childrenName ? filterForm.cascadeSet.childrenName : ''
                    }"
                    filterable
                    :show-all-levels="false"
                    collapse-tags
                    clearable
                    :options="filterForm.options"
                  ></el-cascader>
                  <el-button size="mini" @click="onEnumSelectAll(filterForm, index + '--')" v-if="condition.function === 'in'"> 全选 </el-button>
                </template>
              </div>
            </el-form-item>
            <el-form-item v-else label="过滤条件">
              <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.__config__.viewDataType]" :key="func.function" :value="func.function" :label="func.label"></el-option>
                </el-select>
                <el-cascader
                  :style="customStyle"
                  v-if="condition.function === 'single'"
                  size="mini"
                  v-model="condition.values[0]"
                  :options="filterForm.options"
                  filterable
                  :show-all-levels="false"
                  collapse-tags
                  :props="{ expandTrigger: 'hover', emitPath: false, multiple: false, label: 'VALUE', value: 'KEY' }"
                  v-loading="OptionLoading"
                  clearable
                ></el-cascader>
                <template v-else>
                  <el-input style="width: 170px" size="mini" v-model="condition.values[0]" @input="wallpaperInput" 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]" @input="wallpaperInput" 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-input v-model="filterForm.name"></el-input>
          </el-form-item>
          <el-form-item label="时间格式">
            <el-radio-group v-model="filterForm.dateType" @change="countSpecialAbsoluteTime(filterForm, $event)">
              <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 label="theyear">自然年</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-select v-model="filterForm.monthType" style="width: 60px" @change="countSpecialAbsoluteTime(filterForm)">
              <el-option label="前" value="left"></el-option>
              <el-option label="后" value="right"></el-option>
            </el-select>
            <el-input type="number" style="width: 110px" v-model="filterForm.monthNum" @input="countSpecialAbsoluteTime(filterForm)">
              <template slot="append">月</template>
            </el-input>
            <el-checkbox v-model="filterForm.monthEnd" :true-label="1" :false-label="0" style="margin-left: 30px" @change="countSpecialAbsoluteTime(filterForm)"> 截止到当前 </el-checkbox>
          </el-form-item>
          <el-form-item v-if="filterForm.timeType === 'theyear'" label="自然年设置">
            <el-select v-model="filterForm.monthType" style="width: 60px" @change="countSpecialAbsoluteTime(filterForm)">
              <el-option label="前" value="left"></el-option>
              <el-option label="后" value="right"></el-option>
            </el-select>
            <el-input type="number" style="width: 110px" v-model="filterForm.monthNum" @input="countSpecialAbsoluteTime(filterForm)">
              <template slot="append">年</template>
            </el-input>
            <el-checkbox v-model="filterForm.monthEnd" :true-label="1" :false-label="0" style="margin-left: 30px" @change="countSpecialAbsoluteTime(filterForm)"> 截止到当前 </el-checkbox>
          </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-button size="mini" style="margin-left: 10px" v-show="filterForm.timeType === 'absolute'" @click="onClearTime(filterForm)"> 清空 </el-button>
          </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" v-show="i.dimensionType === 'WEIDU'" :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" v-show="i.dimensionType === 'WEIDU'" :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>
        <!--        <el-button size="small" @click="onTest"> 测试</el-button>-->
      </div>
    </el-dialog>
    <!--    <el-dialog append-to-body title="筛选器编辑&排序" :visible.sync="showSort" custom-class="newbi-filters-sort">-->
    <!--      <draggable v-model="ext.filterList" class="sort-box" animation="300">-->
    <!--        <div class="sort-item" v-for="(item, i) of ext.filterList" :key="i">-->
    <!--          <div class="name">{{ item.name }}</div>-->
    <!--          <el-switch v-model="item.hiddenBtn" :active-value="false" :inactive-value="true"></el-switch>-->
    <!--          <el-button type="text" @click="onFilterEdit(i)">编辑</el-button>-->
    <!--        </div>-->
    <!--      </draggable>-->
    <!--    </el-dialog>-->
  </div>
</template>
<script>
import { cubeFieldList } from '@/api/newbi/dataset'
import { enumCheck, optionList } from '@/api/newbi/bigdata'
import { dataapicategoryList, dataapiDetail, dataapiList, openurl } from './../Dataset-filter/report'
import { dictDetail, dictList } from '@/api/newbi/dict'
import { param } from './../Dataset-filter/config'
import { apiTypeMap, dateTypeMap, fieldDateFormats, globalFunctions, timeAppendMap } from './../Dataset-filter/dict'
import moment from 'moment'
// import draggable from "vuedraggable";

export default {
  // components: {draggable},
  props: ['option', 'charts', 'chartId', 'ext', 'isEdit', 'index', 'isReport', 'reportMonth', 'mini', 'title'],
  data() {
    return {
      apiTypeMap,
      fieldDateFormats,
      dateTypeMap,
      globalFunctions,
      timeAppendMap,
      show: false,
      filterForm: null,
      OptionLoading: false,
      itemIndex: -1,
      apiList: [],
      specialDateTypeMap: { DAY: '天', MONTH: '月', QUARTER: '季' },
      dictList: [],
      showSort: false,
      oldOpt: {},
      showDrawer: false,
      showFields: []
    }
  },
  computed: {
    customStyle() {
      return { fontSize: 12 + 'px' }
    },
    // chartList() {
    //   return this.charts
    //     .filter((i) => i.dataconfig && i.dataconfig.dataType === "CUBE")
    //     .map((i) => {
    //       let chart = {
    //         chartTitle: i.title,
    //         chartKey: i.key,
    //         cubeDataId: i.dataconfig.dataId,
    //         fields: [],
    //         loading: false,
    //       };
    //       this.setChartField(chart);
    //       return chart;
    //     });
    // },
    apisList() {
      return this.charts
        .filter((i) => i.dataconfig && i.dataconfig.dataType === 'API')
        .map((i) => ({
          chartTitle: i.title,
          chartKey: i.key,
          dataId: i.dataconfig.dataId,
          params: i.dataconfig.params
        }))
    },
    countChartStyle() {
      let { outBorderStyle, outBorderColor, fold, foldType, foldSwitch } = this.option
      if (this.mini) {
        return {}
      } else {
        return {
          border: `1px ${outBorderStyle} ${outBorderColor}`,
          width: fold ? '0' : 'auto',
          overflow: fold ? 'hidden' : 'unset',
          marginLeft: foldSwitch && foldType === 'left' ? '25px' : '0',
          marginRight: foldSwitch && foldType === 'right' ? '140px' : '115px'
        }
      }
    },
    countItemStyle() {
      let { inBorderStyle, inBorderColor, filterFontSize } = this.option
      return { border: `1px ${inBorderStyle} ${inBorderColor}`, fontSize: (filterFontSize || 12) + 'px' }
    },
    visualId() {
      let { query, params, fullPath } = this.$route
      return fullPath.includes('/preview/') ? params.id : query.id
    }
  },
  created() {
    // if (!this.chartId && !this.ext.filterList) {
    //   this.$set(this.ext, "filterList", []);
    // } else {
    //   this.ext.filterList.forEach((f) => {
    //     if (f.filterType === "special") {
    //       f.time = f.time || ['', ''];
    //       this.countSpecialAbsoluteTime(f);
    //     } else {
    //       if (!f.conditions) return;
    //       if (!f.conditions.length) return;
    //       if (f.viewDataType === "DATETIME") {
    //         this.countAbsoluteTime(f);
    //       } else if (f.viewDataType === "STRING" || f.viewDataType === "APIS") {
    //         let func = f.conditions[0].function;
    //         if (func === "in" || func === "eq") {
    //           this.getEnumData(f, false);
    //         }
    //       } else if (f.viewDataType == 'NUMBER') {
    //         if (f.conditions[0].function == 'single') {
    //           this.getEnumData(f, false);
    //         }
    //       }
    //     }
    //   });
    // }
    // 获取字典列表
    dictList({ current: 1, size: 10000 }).then((res) => (this.dictList = res.data.data.records))
    // 获取api列表
    dataapicategoryList().then((res) => {
      let category = res.data.data
      dataapiList({ apiFormal: 1, apiTypes: '1' }).then((res) => {
        let list = res.data.data
        this.apiList = category
          .map((i) => ({
            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: {
    wallpaperInput() {
      this.$forceUpdate()
    },
    selectApiChange(val) {
      if (!val) return
      dataapiList({ apiFormal: 1, apiTypes: '1' }).then((res) => {
        let list = res.data.data
        let obj = list.find((i) => i.id === val)
        let resJson = JSON.parse(obj.note || '{}')
        this.showFields = resJson.showFields || []
      })
    },
    // onTest() {
    //   logjson(this.filterForm);
    // },
    handleInputClick(e) {
      e.target.focus()
    },
    onClearTime(filter) {
      if (filter.filterType === 'special') {
        filter.time = ['', '']
      } else {
        filter.conditions[0].values = ['', '']
      }
    },
    onClear() {
      this.ext.filterList.forEach((item) => {
        if (item.filterType === 'special') return
        let func = item.conditions[0].function
        if (func === 'in') {
          item.conditions[0].values = []
        } else if (func === 'between') {
          item.conditions[0].values = ['', '']
        } else {
          item.conditions[0].values = ['']
        }
      })
      this.previewAll()
    },
    onToggleFold() {
      this.option.fold = !this.option.fold
    },
    // 数字时间改变日期类型时
    changeSpecialDateType(filter, dateType) {
      filter.dateType = dateType
      this.countSpecialAbsoluteTime(filter)
      document.getElementById(this.index).focus()
    },
    // 整理可选项树状结构
    countTreeOptions(originData) {
      originData.forEach((i) => {
        i.children = []
        i.KEY = i.KEY || i.VALUE
      })
      let parents = [...originData]
      let res = [],
        childrens = []
      originData.forEach((i) => (i.PID === '0' ? res.push(i) : childrens.push(i)))
      childrens.forEach((i) => {
        let parent = parents.find((j) => j.ID === i.PID)
        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.KEY)
      }
    },
    onEnumSelectAll(filter, refKey) {
      let options = filter.options
      let arr = []
      options.forEach((i) => this.getOptionValue(arr, i))
      let key = this.$refs[refKey][0].inputValue
      if (key && key.trim()) {
        arr = arr.filter((i) => i.includes(key))
      }
      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, nowType) {
      if (nowType == 'DAY') filter.value1 = 29
      if (nowType == 'MONTH') filter.value1 = 12
      if (nowType == 'QUARTER') filter.value1 = 4
      let { count1, count2, value1, value2, dateType, relativeSize, relativeCount, timeType, monthEnd } = filter
      if (timeType === 'relative') {
        let v1, v2
        let date1 = new Date()
        let date2 = new Date()
        if (this.isReport) {
          let datestr = this.reportMonth + '-01 00:00:00'
          date1 = new Date(datestr)
          date2 = new Date(datestr)
        }
        value1 = parseInt(value1)
        value2 = parseInt(value2)
        let count = relativeCount === 'left' ? -parseInt(relativeSize) : parseInt(relativeSize)
        if (dateType === 'QUARTER') {
          date1.setDate(1)
          date2.setDate(1)
          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 = moment(date1).format('yyyyMM')
          v2 = moment(date2).format('yyyyMM')
        } else if (dateType === 'MONTH') {
          date1.setDate(1)
          date2.setDate(1)
          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()
        if (this.isReport) {
          let datestr = this.reportMonth + '-01 00:00:00'
          date1 = new Date(datestr)
          date2 = new Date(datestr)
        }
        date1.setDate(1)
        date2.setDate(1)
        let isLeft = filter.monthType === 'left'
        let monthNum = parseInt(filter.monthNum || 0)
        let count = isLeft ? -monthNum : monthNum
        date1.setMonth(date1.getMonth() + count)
        date2.setMonth(date2.getMonth() + 1 + count)
        date2.setDate(0)
        if (monthEnd && new Date().getMonth() == date2.getMonth()) {
          date2.setDate(new Date().getDate())
        }
        let v1 = moment(date1).format('yyyyMMDD')
        let v2 = moment(date2).format('yyyyMMDD')
        filter.time = [v1, v2]
      } else if (timeType === 'theyear') {
        let date1 = new Date()
        let date2 = new Date()
        let v1, v2
        if (this.isReport) {
          let datestr = this.reportMonth + '-01 00:00:00'
          date1 = new Date(datestr)
          date2 = new Date(datestr)
        }
        date1.setMonth(0)
        date1.setDate(1)
        let isLeft = filter.monthType === 'left'
        let monthNum = parseInt(filter.monthNum || 0)
        let count = isLeft ? -monthNum : monthNum
        date1.setFullYear(date1.getFullYear() + count)
        date2.setFullYear(date2.getFullYear() + count)
        if (!(monthEnd && new Date().getFullYear() == date2.getFullYear())) {
          date2.setMonth(11)
          date2.setDate(31)
        }
        if (dateType == 'DAY') {
          v1 = moment(date1).format('yyyyMMDD')
          v2 = moment(date2).format('yyyyMMDD')
        } else {
          v1 = moment(date1).format('yyyyMM')
          v2 = moment(date2).format('yyyyMM')
        }
        filter.time = [v1, v2]
      }
    },
    // 根据相对时间计算绝对时间
    countAbsoluteTime(filter) {
      let { count1, count2, value1, value2, relativeSize, relativeCount, timeType, dateFormat } = filter
      this.$forceUpdate()
      if (timeType === 'absolute') return
      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)
      date1.setDate(date1.getDate() + count)
      date2.setDate(date2.getDate() + count)
      let origin = date1.getDate()
      date1.setDate(origin + value1)
      date2.setDate(origin + value2)
      let v1 = moment(date1).format('yyyy-MM-DD')
      let v2 = moment(date2).format('yyyy-MM-DD')
      filter.dateType = 'date'
      filter.conditions[0].values = [v1, v2]
      this.$forceUpdate()
    },
    // 保存前去掉可选值列表
    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) => {
      //     if (isEdit) {
      //       return new Promise((r, j) => {
      //         let {tableName, columnName} = i.field;
      //         enumCheck({tableName, columnName, cubeDataId: i.cubeDataId,}).then(() => {
      //           optionList({
      //             tableName,
      //             columnName,
      //             cubeDataId: i.cubeDataId,
      //             visualId: this.visualId || "",
      //             componentId: this.chartId || "",
      //           }).then((res) => {
      //             opts = opts.concat(res.data.data.map((i) => i[columnName]));
      //             r();
      //           });
      //         }).catch(() => {
      //           this.$message({'message': '此数据集不支持原始聚合', type: 'warning'});
      //           j();
      //         });
      //       });
      //     } else {
      //       return new Promise((r, j) => {
      //         let {tableName, columnName} = i.field;
      //         optionList({
      //           tableName,
      //           columnName,
      //           cubeDataId: i.cubeDataId,
      //           visualId: this.visualId || "",
      //           componentId: this.chartId || "",
      //         }).then((res) => {
      //           opts = opts.concat(res.data.data.map((i) => i[columnName]));
      //           r();
      //         });
      //       });
      //     }
      //   });
      //   Promise.all(tasks)
      //     .then(() => filter.options = XEUtils.uniq(opts).map((i) => ({KEY: i, VALUE: i,})))
      //     .finally((_) => (this.OptionLoading = false));
      // } else
      if (enumSource === '2') {
        if (!enumId) {
          return this.$message({ message: '请选择api', type: 'warning' })
        }
        this.OptionLoading = true
        dataapiDetail(enumId).then((res) => {
          let { apiKey } = res.data.data
          openurl(apiKey, param).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 {
              let list = data.map((i) => ({ KEY: i[filter.apiProps.value] || i.KEY || i.VALUE, VALUE: i[filter.apiProps.label] || i.VALUE }))
              list.forEach((i, k) => {
                let obnj = data.find((o) => i.KEY === o[filter.apiProps.value])
                Object.assign(i, obnj)
              })
              filter.options = list
              if (filter.cascadeSwitch) this.getCascadeSet(filter)
            }
            this.$forceUpdate()
          })
        })
      } else {
        if (!enumId) {
          return this.$message({ message: '请选择字典', type: 'warning' })
        }
        dictDetail({ id: enumId }).then((res) => {
          let content = JSON.parse(res.data.data.content || '[]')
          filter.options = content.map((i) => ({ KEY: i.key, VALUE: i.value }))
          this.$forceUpdate()
        })
      }
    },
    getCascadeSet(scheme) {
      try {
        let data = scheme.options.filter((i) => i[scheme.cascadeSet.idKey] || i[scheme.cascadeSet.pidKey])
        let treeData = g.T.toTree(data, scheme.cascadeSet.childrenName, scheme.cascadeSet.idKey, scheme.cascadeSet.pidKey)
        this.$set(scheme, 'options', treeData)
      } catch {}
    },
    // 去掉为空的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
      let { viewDataType } = this.filterForm.__config__
      if ((viewDataType === 'STRING' || viewDataType === 'APIS') && func !== 'like') return true
      return viewDataType === 'NUMBER' && func === 'single'
    },
    // 获取图表字段配置
    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)
      if (this.mini) {
        this.showDrawer = false
      }
    },
    // 设置快捷选项时|数字时间
    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 = 0
      filter.timeUnit = type
      filter.count1 = 'left'
      filter.count2 = 'left'
      filter.value1 = size
      filter.value2 = 0
      this.countAbsoluteTime(filter)
    },
    // 编辑某项筛选
    onFilterEdit(row) {
      if (row.__config__.viewDataType === 'DATETIME') {
        row.timeUnit = 'date'
        row.dateFormat = 'yyyy-MM-dd'
        row.conditions = row.conditions && row.conditions.length ? row.conditions : [{ function: 'between', values: ['', ''] }]
        this.countAbsoluteTime(row)
      }
      this.filterForm = row
      if (this.filterForm.enumSource === '2' && this.filterForm.enumId) {
        this.selectApiChange(this.filterForm.enumId)
      }
      let oldCondition = this.filterForm.conditions ? JSON.parse(JSON.stringify(this.filterForm.conditions)) : []
      this.filterForm.conditions = oldCondition.length ? oldCondition : [{ function: 'like', values: [''] }]
      if (this.filterForm.__config__.viewDataType === 'STRING') {
        this.oldOpt = {
          viewDataType: this.filterForm.__config__.viewDataType
          // dateType: this.filterForm.dateType,
          // condition: this.filterForm.conditions[0]
        }
      }
      this.show = true
      // this.$nextTick(this.countTypeDisable);
      this.$forceUpdate()
    },
    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 = ['', '']
      }
      this.$forceUpdate()
    },
    // 计算是否可添加过滤条件
    countTypeDisable() {
      // let charts = this.filterForm.chartList.filter((i) => i.select);
      // let apis = this.filterForm.apisList.filter((i) => i.select);
      // if (!charts.length && !apis.length) {
      //   this.filterForm.disableMsg = "请选择至少一个图表";
      //   this.filterForm.disable = true;
      //   this.filterForm.conditions = [];
      //   return;
      // }
      // if (charts.length) {
      //   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";
      //   if (viewDataType === this.oldOpt.viewDataType) {
      //     this.filterForm.conditions = [JSON.parse(JSON.stringify(this.oldOpt.condition))];
      //   } else {
      //     this.filterForm.conditions = [{function: func, values: ["", ""],},];
      //   }
      //   if (viewDataType === "DATETIME") {
      //     this.countAbsoluteTime(this.filterForm);
      //   }
      // } else {
      //   if (apis.find(i => !i.param)) {
      //     this.filterForm.disableMsg = "请选择图表参数";
      //     this.filterForm.disable = true;
      //     return;
      //   }
      //   this.filterForm.viewDataType = 'APIS';
      //   this.filterForm.disableMsg = "";
      this.filterForm.disable = false
      let oldCondition = this.filterForm.conditions ? JSON.parse(JSON.stringify(this.filterForm.conditions)) : []
      this.filterForm.conditions = oldCondition.length ? oldCondition : [{ function: 'like', values: [] }]
      // }
    },
    // 某图表选择过滤字段时
    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
          }),
          apisList: this.apisList.map((i) => ({ ...i, select: false, param: '' })),
          disable: false,
          disableMsg: '',
          viewDataType: '',
          dateType: '',
          dateFormat: '',
          connectType: 'and',
          conditions: [],
          options: [],
          enumSource: '1',
          enumId: '',
          apiProps: {
            label: '',
            value: ''
          },
          value1: 29,
          value2: 0,
          count1: 'left',
          count2: 'left',
          timeType: 'relative',
          relativeCount: 'left',
          relativeSize: 1,
          timeUnit: 'date',
          hiddenBtn: false
        }
      } else {
        this.filterForm = {
          name: '日期',
          filterType: 'special',
          dateType: 'DAY', // quarter month day
          value1: 29,
          value2: 0,
          count1: 'left',
          count2: 'left',
          timeType: 'relative',
          relativeCount: 'left',
          relativeSize: 1,
          hidden: false,
          monthNum: 0,
          monthType: 'left',
          monthEnd: 0,
          chartList: this.chartList.map((i) => {
            let chart = { ...i, select: false, tid: '', tfield: null, vid: '', vfield: null }
            this.setChartField(chart)
            return chart
          }),
          time: ['', ''],
          hiddenBtn: false
        }
        this.countSpecialAbsoluteTime(this.filterForm)
      }
      this.itemIndex = -1
      this.show = true
    },
    // 筛选器编辑完成时
    onAddFilterConfirm() {
      let data = JSON.parse(JSON.stringify(this.filterForm))
      if (this.filterForm.disable) {
        return this.$message({ message: this.filterForm.disableMsg, type: 'warning' })
      }
      if (!this.filterForm.conditions.length) {
        return this.$message({ message: '请添加过滤条件', type: 'warning' })
      }
      this.$emit('onAddSearchChange', data)
      this.show = false
    }
  }
}
</script>
<style lang="scss">
.new-filter-box {
  position: relative;
  .fold-btn {
    width: 20px;
    height: 30px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: #409eff;
    color: white;
    border-radius: 3px;
    line-height: 30px;
    text-align: center;
    transition: 0.1s;
    cursor: pointer;
    &.left {
      left: 0;
    }
    &.right {
      right: 0;
    }
  }
  .filter-btns {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    .el-button {
      margin: 0;
    }
  }
}
.new-filter {
  height: 100%;
  align-items: center;
  display: flex;
  flex-wrap: wrap;
  .item {
    border: 1px dashed #ccc;
    font-size: 14px;
    float: left;
    display: flex;
    align-items: center;
    margin-left: 5px;
    .el-range-input {
      font-size: unset;
    }
    .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 {
        font-size: 12px;
        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;
      transform: unset;
      top: 2px;
      bottom: 2px;
    }
  }
  .condition {
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .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;
    }
  }
}
.newbi-filters-sort {
  width: 500px;
  .el-dialog__body {
    min-height: 400px;
    max-height: 600px;
    overflow-y: auto;
  }
  .sort-box {
    width: 300px;
    margin: 0 auto;
  }
  .sort-item {
    width: 260px;
    display: flex;
    align-items: center;
    margin: 5px auto;
    padding: 0 15px;
    border: 1px solid #ccc;
    border-radius: 3px;
    height: 30px;
    .name {
      flex: 1;
    }
    .el-switch {
      margin: 0 10px;
    }
  }
}
.filter-mini-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 18px;
}
.filter-mini {
  height: 50% !important;
  #el-drawer__title {
    margin-bottom: 10px;
    padding: 10px 20px 0;
  }
  .el-drawer__body {
    overflow-y: auto;
    .new-filter {
      height: unset;
      display: block;
      .item {
        float: unset;
        margin: 10px 5px;
        display: block;
        .el-date-editor {
          width: 240px;
        }
      }
    }
    .filter-mini-btns {
      margin: 20px 5px;
      text-align: center;
      .el-button {
        margin: 0 20px;
      }
    }
  }
}
</style>
