<template>
  <div class="newbi-dataset-filter">
    <div class="wrapper">
      <div class="left">
        <el-tabs tab-position="left" v-model="nowName" @tab-click="onSelectItem">
          <el-tab-pane v-for="(item, i) of list" :name="item.cubePermName" :key="item.id" :label="item.cubePermName"> </el-tab-pane>
        </el-tabs>
        <div class="add-tab">
          <el-button size="small" plain icon="el-icon-plus" @click="onAddItem">添加过滤器</el-button>
        </div>
      </div>
      <div class="right" v-if="nowFilter">
        <el-form size="mini" label-width="60px" style="height: 93%">
          <el-form-item label="名称">
            <el-input :disabled="nowFilter.isDefault === 1" v-model="nowFilter.cubePermName"></el-input>
          </el-form-item>
          <el-form-item label="权限组" v-if="nowFilter.isDefault !== 1">
            <auth-group-selector v-model="nowFilter.dataPermId"></auth-group-selector>
          </el-form-item>
          <template v-if="showFalgTemp === 'Btns'">
            <div style="margin-bottom: 20px" class="flex flex-between flex-center">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
              <div class="flex gap-10">
                <el-button size="small" style="width: 100%" :type="nowFilter.id ? 'primary' : ''" @click="onSave" plain>
                  {{ nowFilter.id ? '更新' : '添加' }}
                </el-button>
                <el-button size="small" style="width: 100%" v-if="nowFilter.isDefault !== 1" @click="onDel(nowFilter.id)" plain type="danger">删除</el-button>
              </div>
            </div>
            <div class="flex flex-between gap-10" style="height: 90%; overflow: auto">
              <el-checkbox-group v-if="btns.length" v-model="nowFilter.btnsList" class="btnsList" @change="handleCheckedCitiesChange">
                <el-tabs>
                  <el-tab-pane label="系统按钮">
                    <div v-for="item in customSystemBtns.filter((v) => !v.buttonType || v.buttonType === 2)" class="flex gap-10 flex-center" style="margin-bottom: 10px">
                      <el-checkbox :label="item.value" :key="item.value">
                        <span class="">{{ item.label || btnText(item.value) }}</span>
                      </el-checkbox>
                      <!--                      <el-cascader-->
                      <!--                        :disabled="['journal', 'recycle', 'uploadRevoke', 'comDelete'].includes(item.value)"-->
                      <!--                        v-model="item.flowId"-->
                      <!--                        :options="flowSelectList"-->
                      <!--                        placeholder="请选择需要关联的流程"-->
                      <!--                        :props="{ value: 'id', label: 'name', children: 'children', emitPath: false }"-->
                      <!--                        clearable-->
                      <!--                      ></el-cascader>-->
                    </div>
                  </el-tab-pane>
                  <!--                  <el-tab-pane label="自定义按钮">-->
                  <!--                    <div v-for="item in customSystemBtns.filter((v) => v.buttonType === 1)" class="flex gap-10 flex-center" style="margin-bottom: 10px">-->
                  <!--                      <el-checkbox :label="item.value" :key="item.value">-->
                  <!--                        <span class="">{{ item.label || btnText(item.value) }}</span>-->
                  <!--                      </el-checkbox>-->
                  <!--                      <el-cascader-->
                  <!--                        :disabled="['journal', 'recycle', 'uploadRevoke', 'comDelete'].includes(item.value)"-->
                  <!--                        v-model="item.flowId"-->
                  <!--                        :options="flowSelectList"-->
                  <!--                        placeholder="请选择需要关联的流程"-->
                  <!--                        :props="{ value: 'id', label: 'name', children: 'children', emitPath: false }"-->
                  <!--                        clearable-->
                  <!--                      ></el-cascader>-->
                  <!--                    </div>-->
                  <!--                  </el-tab-pane>-->
                </el-tabs>
              </el-checkbox-group>
              <el-checkbox-group v-if="columnBtns.length" v-model="nowFilter.columnBtnsList" class="btnsList columnBtnList">
                <el-tabs>
                  <el-tab-pane label="系统按钮">
                    <div v-for="item in customTableData.filter((v) => !v.buttonType || v.buttonType === 2)" class="flex gap-10 flex-center" style="margin-bottom: 10px">
                      <div>
                        <el-checkbox :label="item.value" :key="item.value">
                          <div class="">{{ item.label || btnText(item.value) }}</div>
                        </el-checkbox>
                      </div>
                      <div>
                        <!--                        <el-cascader-->
                        <!--                          :disabled="['detail', 'rowJournal'].includes(item.value)"-->
                        <!--                          v-model="item.flowId"-->
                        <!--                          :options="flowSelectList"-->
                        <!--                          placeholder="请选择需要关联的流程"-->
                        <!--                          :props="{ value: 'id', label: 'name', children: 'children', emitPath: false }"-->
                        <!--                          clearable-->
                        <!--                        ></el-cascader>-->
                      </div>
                    </div>
                  </el-tab-pane>
                  <!--                  <el-tab-pane label="自定义按钮">-->
                  <!--                    <div v-for="item in customTableData.filter((v) => v.buttonType === 1)" class="flex gap-10 flex-center" style="margin-bottom: 10px">-->
                  <!--                      <div>-->
                  <!--                        <el-checkbox :label="item.value" :key="item.value">-->
                  <!--                          <div class="">{{ item.label || btnText(item.value) }}</div>-->
                  <!--                        </el-checkbox>-->
                  <!--                      </div>-->
                  <!--                      <div>-->
                  <!--                        <el-cascader-->
                  <!--                          :disabled="['detail', 'rowJournal'].includes(item.value)"-->
                  <!--                          v-model="item.flowId"-->
                  <!--                          :options="flowSelectList"-->
                  <!--                          placeholder="请选择需要关联的流程"-->
                  <!--                          :props="{ value: 'id', label: 'name', children: 'children', emitPath: false }"-->
                  <!--                          clearable-->
                  <!--                        ></el-cascader>-->
                  <!--                      </div>-->
                  <!--                    </div>-->
                  <!--                  </el-tab-pane>-->
                </el-tabs>
              </el-checkbox-group>
            </div>
          </template>
          <el-tabs v-if="showFalgTemp === 'data'" v-model="activeType">
            <el-tab-pane label="行过滤" name="row">
              <el-dropdown @command="onAddFilter" trigger="click">
                <el-button type="success" size="mini" plain icon="el-icon-plus" style="margin: 0 10px">添加</el-button>
                <el-dropdown-menu slot="dropdown" class="newbi-dataset-filter-drop">
                  <el-input v-model="searchKey" placeholder="筛选" clearable></el-input>
                  <div class="fields">
                    <el-dropdown-item v-for="(field, i) of searchedFields" :key="i" :command="field" :class="[field.dimensionType]">
                      {{ field.columnTitle }}
                    </el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </el-dropdown>
              <cube-filter-node :node="nowFilter.filterRelation.where" :level="1"></cube-filter-node>
            </el-tab-pane>
            <el-tab-pane label="列过滤" name="column">
              <el-dropdown @command="onAddColumn" trigger="click">
                <el-button type="success" size="mini" plain icon="el-icon-plus" style="margin: 0 10px">添加</el-button>
                <el-dropdown-menu slot="dropdown" class="newbi-dataset-filter-drop">
                  <el-input v-model="searchKey" placeholder="筛选" clearable></el-input>
                  <div class="fields">
                    <el-dropdown-item v-for="(field, i) of availableFields" :key="i" :command="field" :class="[field.dimensionType, field.select ? 'select' : '']">
                      {{ field.columnTitle }}
                    </el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </el-dropdown>
              <div v-for="(column, i) of nowFilter.excludeColumn" :key="i" :class="['column', column.dimensionType]">
                <span class="one-line">{{ column.columnTitle }}</span>
                <i class="el-icon-close close" @click="nowFilter.excludeColumn.splice(i, 1)"></i>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form>
        <div class="flex gap-10" v-if="showFalgTemp === 'data'">
          <el-button size="small" style="width: 100%" :type="nowFilter.id ? 'primary' : 'success'" @click="onSave" plain>
            {{ nowFilter.id ? '更新' : '添加' }}
          </el-button>
          <el-button size="small" style="width: 100%" v-if="nowFilter.isDefault !== 1" @click="onDel(nowFilter.id)" plain type="danger">删除</el-button>
        </div>
      </div>
    </div>
    <!-- 过滤器编辑框 -->
    <el-dialog append-to-body :visible.sync="showCondition" title="编辑过滤器" custom-class="bigdata-filter" width="560px">
      <div v-if="nowCondition">
        <el-form size="mini" label-width="80px">
          <el-form-item label="当前字段">
            <div :class="['now-filter', nowCondition.column.dimensionType]">
              <div class="name">{{ nowCondition.column.columnTitle + ' ' + nowCondition.column.columnName }}</div>
              <div style="color: #999">{{ datatypeMap[nowCondition.column.viewDataType] }}</div>
            </div>
          </el-form-item>
          <el-form-item label="连接方式">
            <el-radio-group v-model="nowCondition.connectType">
              <el-radio label="and">且</el-radio>
              <el-radio label="or">或</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="枚举来源" v-show="countEnumShow()">
            <el-radio-group v-model="nowCondition.enumSource">
              <el-radio label="1">原始数据聚合</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="onGetEnumData" style="margin-left: 20px"> 获取 </el-button>
          </el-form-item>
          <el-form-item label="选择api" v-if="countEnumShow() && nowCondition.enumSource === '2'">
            <el-cascader
              v-model="nowCondition.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="选择字典" v-if="countEnumShow() && nowCondition.enumSource === '3'">
            <el-select v-model="nowCondition.enumId">
              <el-option v-for="(item, i) of dictList" :key="i" :value="item.id" :label="item.keyCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="过滤条件">
            <div class="filter-item" v-for="(condition, i) of nowCondition.conditions" :key="i">
              <el-select size="mini" v-model="condition.function" style="width: 100px; margin-right: 10px" placeholder="选择条件" @change="onFunctionChange">
                <el-option v-for="func of functions[nowCondition.column.viewDataType]" :key="func.function" :value="func.function" :label="func.label"></el-option>
              </el-select>
              <el-select v-model="condition.useParam" style="width: 95px; margin-right: 5px" @change="onUseParamChange(condition)">
                <el-option label="普通参数" :value="false"></el-option>
                <el-option label="全局参数" :value="true"></el-option>
              </el-select>
              <template v-if="condition.useParam">
                <el-cascader
                  size="small"
                  v-model="condition.paramKey"
                  :options="paramList"
                  :show-all-levels="false"
                  filterable
                  :props="{ expandTrigger: 'click', emitPath: false, value: 'paramKey' }"
                  clearable
                ></el-cascader>
              </template>
              <!-- 日期类型 -->
              <template v-else>
                <template v-if="nowCondition.column.viewDataType === 'DATETIME'">
                  <el-select v-model="condition.timeType" style="width: 95px; margin-right: 5px" @change="onTimeTypeChange(condition)">
                    <el-option label="绝对时间" value="absolute"></el-option>
                    <el-option label="相对时间" value="relative"></el-option>
                  </el-select>
                  <template v-if="condition.timeType === 'relative'">
                    <el-input style="width: 120px; margin-right: 5px" v-model="condition.values[0]">
                      <template slot="append"> {{ timeTypeMap[nowCondition.column.timeDataFormat] }}</template>
                    </el-input>
                    <el-select v-model="condition.countType" style="width: 60px">
                      <el-option label="前" value="left"></el-option>
                      <el-option label="后" value="right"></el-option>
                    </el-select>
                  </template>
                  <template v-else>
                    <template v-if="nowCondition.dateType === 'time'">
                      <el-date-picker style="width: 200px" v-model="condition.values[0]" type="datetime" placeholder="选择日期时间" :value-format="nowCondition.dateFormat"></el-date-picker>
                      <el-date-picker
                        v-if="condition.function === 'between'"
                        style="width: 200px"
                        v-model="condition.values[1]"
                        type="datetime"
                        placeholder="选择日期时间"
                        :value-format="nowCondition.dateFormat"
                      ></el-date-picker>
                    </template>
                    <template v-else-if="['year', 'month', 'date'].includes(nowCondition.dateType)">
                      <el-date-picker style="width: 200px" v-model="condition.values[0]" :type="nowCondition.dateType" placeholder="选择日期" :value-format="nowCondition.dateFormat"></el-date-picker>
                      <el-date-picker
                        v-if="condition.function === 'between'"
                        style="width: 200px"
                        v-model="condition.values[1]"
                        :type="nowCondition.dateType"
                        placeholder="选择日期"
                        :value-format="nowCondition.dateFormat"
                      ></el-date-picker>
                    </template>
                    <template v-else>
                      <el-time-select style="width: 200px" v-model="condition.values[0]" placeholder="选择时间" :value-format="nowCondition.dateFormat"></el-time-select>
                      <el-time-select
                        v-if="condition.function === 'between'"
                        style="width: 200px"
                        v-model="condition.values[1]"
                        placeholder="选择时间"
                        :value-format="nowCondition.dateFormat"
                      ></el-time-select>
                    </template>
                  </template>
                </template>
                <template v-if="['in', 'notIn'].includes(condition.function)">
                  <el-cascader
                    v-model="condition.values"
                    :options="nowCondition.options"
                    :props="{ expandTrigger: 'hover', emitPath: false, multiple: true, label: 'VALUE', value: 'KEY' }"
                    filterable
                    :show-all-levels="false"
                    collapse-tags
                    clearable
                  ></el-cascader>
                  <el-button size="mini" @click="onEnumSelectAll(nowCondition)" type="primary"> 全选</el-button>
                </template>
                <template v-else-if="['indexIn'].includes(condition.function)">
                  <el-input style="width: 200px" size="mini" v-model="condition.values[0]" placeholder="默认使用第几条"> </el-input>
                </template>
                <span v-else-if="['isnull', 'notnull'].includes(condition.function)"></span>
                <el-input v-else style="width: 200px" size="mini" v-model="condition.values[0]" placeholder="输入值"> </el-input>
              </template>
              <i class="el-icon-delete" v-show="nowCondition.conditions.length > 1" @click="onConditionDel(i)"></i>
            </div>
            <el-button size="mini" type="success" plain @click="onConditionAdd" v-show="canAddCondition"> 添加条件 </el-button>
          </el-form-item>
          <div class="btns" style="display: flex; justify-content: end; margin-top: 30px">
            <el-button type="primary" size="small" @click="showCondition = false" style="width: 100px"> 确定</el-button>
            <el-button size="small" @click="showCondition = false" style="width: 100px"> 取消</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { dateTypeMap, fieldDateFormats, functions, timeTypeMap, columnKeys } from './dict'
import cubeFilterNode from './cubeFilterNode'
import authGroupSelector from './auth-group-selector'
import util from '@/utils/wey'
import { getEnumData, onEnumSelectAll } from './util'
import { BtnDataPermSubmit, dataapicategoryList, dataapiList, getDataPermList } from './report'
import { dictList } from '@/api/newbi/dict'
import { cubePremSave, cubePremList, cubePremSDel, cubeBtnPremSDel, paramList, categoryList, globalCategoryList, flowList } from '@/api/newbi/dataset'
import { Base64 } from 'js-base64'
import { getCustomButton } from '@/api/onlineDev/visualDev'

export default {
  components: { cubeFilterNode, authGroupSelector },
  model: { prop: 'show', event: 'change' },
  // props: ['show', 'cubeId', 'fields', 'modelId','btns','columnBtns'],
  props: {
    showFalg: {
      type: String,
      required: true
    },
    show: {
      type: Boolean,
      default: false
    },
    cubeId: {
      type: Number,
      require: true
    },
    modelId: {
      type: String,
      require: true
    },
    fields: {
      type: Array,
      default: () => []
    },
    btns: {
      type: Array,
      default: () => []
    },
    columnBtns: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      columnKeys,
      timeTypeMap,
      functions,
      dateTypeMap,
      fieldDateFormats,
      apiList: [],
      dictList: [],
      list: [],
      draggingNode: null,
      draggingIndex: 0,
      showCondition: false,
      nowFilter: null,
      nowName: '',
      defaultFilterJson: '{"filterList":[],"filterRelation":{"where":{"conditions":[],"filters":[],"relation":"AND"}}}',
      datatypeMap: { NUMBER: '数字', STRING: '字符串', DATETIME: '时间' },
      nowCondition: null,
      searchKey: '',
      activeType: 'row',
      showFalgTemp: this.showFalg,
      flowSelectList: [],
      isIndeterminate: true,
      checkAll: false,
      customTableData: [],
      systemBtns: [],
      customSystemBtns: [],
      paramList: []
    }
  },
  watch: {
    showFalg(val, valOld) {
      if (val) {
        this.showFalgTemp = val
      }
    }
  },
  provide() {
    return {
      editFilterByUniqId: this.editFilterByUniqId,
      onNodeDrag: this.onNodeDrag,
      onNodeDrop: this.onNodeDrop,
      onDelFilter: this.onDelFilter
    }
  },
  computed: {
    // 能否添加过滤条件
    canAddCondition() {
      if (!this.nowCondition) return false
      let func = this.nowCondition.conditions[0].function
      return !(func === 'in' || func === 'notIn' || func === 'indexIn')
    },
    searchedFields() {
      return this.fields.filter((i) => i.columnTitle.includes(this.searchKey))
    },
    availableFields() {
      return this.searchedFields.map((i) => ({ ...i, select: !!this.nowFilter.excludeColumn.find((j) => j.id == i.id) }))
    },
    nowFilterIndex() {
      console.log(this.nowFilter.excludeColumn)
      return this.searchedFields.findIndex((i) => i.uniqId == this.nowFilter.uniqId)
    }
  },
  async created() {
    await this.init()
  },
  methods: {
    async init() {
      this.getInitData()
      const { data } = await getCustomButton(this.modelId)
      const { records } = data.data
      this.customButtions = records.map((item) => {
        item.buttonInfo = item.buttonInfo ? JSON.parse(item.buttonInfo || {}) : {}
        item.label = item.buttonName
        item.type = item.buttonType === 1 ? '自定义按钮' : '系统按钮'
        item.value = 'custom_button_' + item.id
        return item
      })
      this.customTableData = [...this.columnBtns, ...this.customButtions.filter((v) => v.buttonType === 1 && v.buttonLocation === 2)]
      this.customSystemBtns = [...this.btns, ...this.customButtions.filter((v) => v.buttonType === 1 && v.buttonLocation === 1)].filter((v) => {
        return ['add', 'download', 'recycle'].includes(v.value)
      })
      console.log(this.customSystemBtns)
    },
    btnText(key) {
      let text = ''
      switch (key) {
        case 'download':
          text = '导出'
          break
        case 'batchRemove':
          text = '批量删除'
          break
        // case 'batchUpdate':
        //   text = '批量编辑'
        //   break
        case 'edit':
          text = '编辑'
          break
        case 'remove':
          text = '删除'
          break
        case 'detail':
          text = '详情'
          break
        case 'batchUpload':
          text = '批量导入'
          break
        // case 'uploadRevoke':
        //   text = '导入撤销'
        //   break
        // case 'comDelete':
        //   text = '彻底删除'
        //   break
        case 'journal':
          text = '操作日志'
          break
        case 'recycle':
          text = '回收站'
          break
        // case 'rowJournal':
        //   text = '操作记录'
        //   break
        default:
          text = '新增'
          break
      }
      return text
    },
    onAddColumn(field) {
      if (this.nowFilter.excludeColumn.find((i) => i.id == field.id)) return
      this.nowFilter.excludeColumn.push(field)
    },
    onDel(id) {
      this.$confirm('确定删除?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          if (this.showFalgTemp === 'Btns') {
            //编辑按钮权限时
            cubeBtnPremSDel({ visualdevPermId: id }).then((res) => {
              this.$message({ type: 'success', message: '已删除' })
              this.getData()
            })
          } else {
            cubePremSDel({ cubePermId: id }).then((res) => {
              this.$message({ type: 'success', message: '已删除' })
              this.getData()
            })
          }
        })
        .catch(() => {})
    },
    getData() {
      if (this.showFalgTemp === 'data' && this.fields && this.fields.length) {
        this.getDataConfirm()
      }
      if (this.showFalgTemp === 'Btns' && this.modelId) {
        this.getBtnConfirm()
      }
    },
    async getBtnConfirm() {
      let res = await getDataPermList({ visualdevId: this.modelId })
      const { data } = await getCustomButton(this.modelId)
      const { records } = data.data
      this.customButtions = records.map((item) => {
        item.buttonInfo = item.buttonInfo ? JSON.parse(item.buttonInfo || {}) : {}
        item.label = item.buttonName
        item.type = item.buttonType === 1 ? '自定义按钮' : '系统按钮'
        item.value = 'custom_button_' + item.id
        return item
      })
      // this.customTableData = [...this.columnBtns, ...this.customButtions.filter((v) => v.buttonType === 1)]
      this.systemBtns = this.customButtions.filter((v) => v.buttonType === 2)
      this.list = res.data.data.map((i) => {
        let id = i.id // id
        let visualdevId = i.visualdevId // 过滤器id
        let cubePermName = i.visualdevPermName //过滤器名称
        let dataPermId = i.dataPermId // 权限组id
        let isDefault = i.isDefault //是否是默认
        let ParsePermJson = i ? JSON.parse(i.permJson) : []

        //过滤已选中的按钮
        let btnFilterList = ParsePermJson.length
          ? ParsePermJson.map((item) => {
              if (item.permValue === 1) {
                return item
              }
            }).filter((l) => l !== undefined)
          : []
        //与按钮list匹配
        let btnvalueList = btnFilterList.map((item) => this.customSystemBtns.find((j) => j.value === item.permKey)).filter((l) => l !== undefined)
        let columnvalueList = btnFilterList.map((item) => this.customTableData.find((j) => j.value === item.permKey)).filter((l) => l !== undefined)
        let btnsList = btnvalueList.map((i) => {
          return i.value
        })
        let columnBtnsList = columnvalueList.map((i) => {
          return i.value
        })
        return { id, visualdevId, isDefault, ParsePermJson, cubePermName, dataPermId, btnsList, columnBtnsList }
      })
      console.log(this.list)
      if (!this.list.length) {
        this.list.push({
          cubePermName: '默认权限组',
          dataPermId: '',
          cubeDataId: parseInt(this.cubeId),
          filterRelation: { where: { conditions: [], filters: [], relation: 'AND' } },
          filterList: [],
          excludeColumn: [],
          btnsList: ['add', 'download'],
          columnBtnsList: ['remove', 'edit'],
          isDefault: 1
        })
      }
      this.nowName = this.list[0].cubePermName
      this.onSelectItem({ name: this.nowName })
    },
    async getDataConfirm() {
      let res = await cubePremList({ cubeDataId: this.cubeId })
      this.list = res.data.data.map((i) => {
        let { filterList, filterRelation } = JSON.parse(i.filterJson || this.defaultFilterJson)
        let ids = i.excludeColumnIds ? i.excludeColumnIds.split(',') : []
        let excludeColumn = ids.map((id) => this.fields.find((j) => j.id == id))
        return { ...i, filterList, filterRelation, excludeColumn }
      })
      if (!this.list.length) {
        this.list.push({
          cubePermName: '一号过滤器',
          dataPermId: '',
          cubeDataId: parseInt(this.cubeId),
          filterRelation: { where: { conditions: [], filters: [], relation: 'AND' } },
          filterList: [],
          excludeColumn: [],
          btnsList: [],
          columnBtnsList: []
        })
      }
      this.nowName = this.list[0].cubePermName
      this.onSelectItem({ name: this.nowName })
    },
    onSave() {
      // 提交中
      const loading = this.$loading({
        lock: true,
        text: '提交中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (this.showFalgTemp === 'data') {
        let { cubeDataId, dataPermId, cubePermName, filterList, filterRelation, id, excludeColumn } = this.nowFilter
        let data = {
          cubeDataId,
          dataPermId,
          cubePermName,
          filterJson: JSON.stringify({ filterList, filterRelation }),
          excludeColumnIds: excludeColumn.map((i) => i.id).join(',')
        }
        id && (data.id = id)
        cubePremSave(Base64.encode(JSON.stringify(data))).then((res) => {
          loading.close()
          this.$message({ type: 'success', message: '已提交' })
          this.getData()
        })
      }
      if (this.showFalgTemp === 'Btns') {
        if (!this.nowFilter.dataPermId && this.nowFilter.isDefault === 0) {
          this.$message({ type: 'warning', message: '请选择权限组' })
          return false
        }
        let aaa = []
        let bbb = []
        this.customSystemBtns.forEach((i) => {
          const find = this.systemBtns.find((v) => v.buttonName === i.label)
          let data = { permKey: i.value, permName: i.label, permValue: 1, flowId: i.flowId ? i.flowId : '' }
          if (i.value.includes('custom')) {
            data = {
              buttonCondition: i.buttonCondition,
              buttonId: i.id,
              buttonLocation: i.buttonLocation,
              buttonStatus: i.buttonStatus,
              buttonType: i.buttonType,
              execType: i.execType,
              flowId: '',
              permKey: i.value,
              permName: i.buttonName,
              permValue: 0,
              redirectUrl: i.redirectUrl
            }
          }
          if (find) {
            data = {
              buttonCondition: find.buttonCondition,
              buttonId: find.id,
              buttonLocation: find.buttonLocation,
              buttonStatus: find.buttonStatus,
              buttonType: find.buttonType,
              execType: find.execType,
              flowId: i.flowId ? i.flowId : '',
              permKey: i.value,
              permName: find.buttonName,
              permValue: 0,
              redirectUrl: find.redirectUrl
            }
          }
          if (this.nowFilter.btnsList.includes(i.value)) {
            data.permValue = 1
            aaa.push(data)
          } else {
            data.permValue = 0
            aaa.push(data)
          }
        })
        this.customTableData.forEach((i) => {
          const find = this.customButtions.find((v) => v.buttonName === i.label)
          let data = { permKey: i.value, permName: i.label, permValue: 1, flowId: i.flowId ? i.flowId : '' }
          if (i.value.includes('custom')) {
            data = {
              buttonCondition: i.buttonCondition,
              buttonId: i.id,
              buttonLocation: i.buttonLocation,
              buttonStatus: i.buttonStatus,
              buttonType: i.buttonType,
              execType: i.execType,
              flowId: '',
              permKey: i.value,
              permName: i.buttonName,
              permValue: 0,
              redirectUrl: i.redirectUrl
            }
          }
          if (find) {
            data = {
              buttonCondition: find.buttonCondition,
              buttonId: find.id,
              buttonLocation: find.buttonLocation,
              buttonStatus: find.buttonStatus,
              buttonType: find.buttonType,
              execType: find.execType,
              flowId: i.flowId ? i.flowId : '',
              permKey: i.value,
              permName: find.buttonName,
              permValue: 0,
              redirectUrl: find.redirectUrl
            }
          }
          if (this.nowFilter.columnBtnsList.includes(i.value)) {
            data.permValue = 1
            bbb.push(data)
          } else {
            data.permValue = 0
            bbb.push(data)
          }
        })
        let permList = aaa.concat(bbb)
        let valueList = {
          id: this.nowFilter.id,
          visualdevId: this.modelId, //表单ID
          visualdevPermName: this.nowFilter.cubePermName, //表单操作权限名称
          dataPermId: this.nowFilter.dataPermId, //权限组ID
          isDefault: this.nowFilter.isDefault, //是否是默认权限
          permJson: JSON.stringify(permList)
        }
        BtnDataPermSubmit(Base64.encode(JSON.stringify(valueList))).then((res) => {
          loading.close()
          this.$message({ type: 'success', message: '已提交' })
          this.getData()
        })
      }
    },
    // 过滤器添加条件
    onConditionAdd() {
      this.nowCondition.conditions.push({
        function: 'eq',
        values: ['', ''],
        timeType: 'absolute',
        countType: 'left'
      })
    },
    // 过滤器删除条件
    onConditionDel(i) {
      this.nowCondition.conditions.splice(i, 1)
    },
    onEnumSelectAll(filter) {
      onEnumSelectAll(filter)
    },
    // 条件时间类型变化时
    onTimeTypeChange(condition) {
      if (condition.timeType === 'relative') {
        condition.values = [1]
      } else {
        condition.values = ['']
      }
    },
    // 计算函数变化时
    async onFunctionChange(func) {
      if (['in', 'notIn', 'indexIn'].includes(func)) {
        this.nowCondition.conditions = [
          {
            function: func,
            values: [],
            timeType: 'absolute',
            countType: 'left'
          }
        ]
      }
    },
    // 获取初始化工具数据
    getInitData() {
      //获取流程分类下拉列表
      // flowList().then((res) => {
      //   this.flowSelectList = res.data.data
      // })
      // 获取api列表
      dataapicategoryList().then((res) => {
        let category = res.data.data
        dataapiList({ apiFormal: 1, apiTypes: '1,2' }).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,
                    key: k.apiKey
                  }))
              }
            })
            .filter((i) => i.children.length)
        })
      })
      dictList({ current: 1, size: 10000 }).then((res) => {
        this.dictList = res.data.data.records
      })
      globalCategoryList({ size: 10000, current: 1 }).then((res) => {
        let list = res.data.data.records
        let parents = list.filter((i) => !i.parentId)
        let categoryList = []
        list.forEach((i) => {
          i.children = []
          if (i.parentId) {
            let parent = parents.find((j) => j.id == i.parentId)
            parent.hasChild = true
            i.label = parent.typeName + ' / ' + i.typeName
            categoryList.push(i)
          } else {
            i.label = i.typeName
          }
        })
        categoryList = categoryList.concat(parents.filter((i) => !i.hasChild))
        paramList({ size: 10000, current: 1 }).then((res) => {
          let params = res.data.data.records
          params.forEach((i) => {
            i.label = i.paramName
            let parent = categoryList.find((j) => j.id == i.typeId)
            parent.children.push(i)
          })
          this.paramList = categoryList
        })
      })
    },
    // 获取枚举值列表
    onGetEnumData() {
      if (!this.nowCondition.options.length) {
        getEnumData(this.nowCondition, this.cubeId, '', '', true)
      }
    },
    // 判断是否展示枚举选项
    countEnumShow() {
      let func = this.nowCondition.conditions[0].function
      return func === 'in' || func === 'notIn' || func === 'indexIn'
    },
    // 删除条件时
    onDelFilter(item, node, i) {
      node.conditions.splice(i, 1)
      let index = this.nowFilter.filterList.findIndex((i) => i.uniqId == item.uniqId)
      this.nowFilter.filterList.splice(index, 1)
      let rootNode = this.nowFilter.filterRelation.where
      rootNode.filters.forEach((node, index) => {
        this.clearNullNode(rootNode, node, index)
      })
    },
    // 清除空节点
    clearNullNode(parent, item, index) {
      item.filters.forEach((node, i) => {
        this.clearNullNode(item, node, i)
      })
      if (!item.filters.length && !item.conditions.length) {
        parent.filters.splice(index, 1)
      }
    },
    // 节点拖拽完成时
    onNodeDrop(node) {
      let item = this.draggingNode.conditions.splice(this.draggingIndex, 1)[0]
      node.conditions.push(item)
      let rootNode = this.nowFilter.filterRelation.where
      rootNode.filters.forEach((node, index) => {
        this.clearNullNode(rootNode, node, index)
      })
    },
    // 开始拖拽某节点
    onNodeDrag(node, index) {
      this.draggingNode = node
      this.draggingIndex = index
    },
    // 编辑某个条件
    editFilterByUniqId({ uniqId }) {
      this.nowCondition = this.nowFilter.filterList.find((i) => i.uniqId == uniqId)
      this.showCondition = true
      let func = this.nowCondition.conditions[0].function
      if (func === 'in' || func === 'notIn' || func === 'indexIn') {
        this.onGetEnumData()
      }
    },
    // 添加条件时
    onAddFilter(field) {
      let column = util.filterFields([field], this.columnKeys)[0]
      let nowField = { column }
      nowField.uniqId = util.getRandomStr(7)
      nowField.cubeColumnId = field.id
      nowField.connectType = 'and'
      nowField.conditions = [
        {
          function: 'eq',
          values: ['', ''],
          timeType: 'absolute',
          countType: 'left'
        }
      ]
      nowField.asFilter = true
      nowField.options = []
      nowField.enumSource = '1'
      nowField.enumId = ''
      if (nowField.viewDataType === 'DATETIME') {
        nowField.dateType = this.dateTypeMap[field.timeDataFormat]
        nowField.dateFormat = this.fieldDateFormats.find((i) => i.value === field.timeDataFormat).label
      }
      this.nowFilter.filterList.push(nowField)
      this.nowFilter.filterRelation.where.conditions.push({
        uniqId: nowField.uniqId,
        columnTitle: column.columnTitle
      })
    },
    // 选择过滤器时
    onSelectItem({ name }) {
      if (this.showFalgTemp === 'data') {
        let now = this.list.find((i) => i.cubePermName === name)
        this.nowName = now.cubePermName
        this.nowFilter = now
      }
      if (this.showFalgTemp === 'Btns') {
        this.checkAll = false
        let now = this.list.find((i) => i.cubePermName === name)
        this.nowName = now.cubePermName
        this.nowFilter = now
        //关联流程
        if (!now.ParsePermJson) return
        now.ParsePermJson.forEach((item) => {
          this.customSystemBtns.forEach((v) => {
            if (v.value === item.permKey) {
              v.flowId = item.flowId
            }
          })
          this.columnBtns.forEach((v) => {
            if (v.value === item.permKey) {
              v.flowId = item.flowId
            }
          })
        })
        this.handleCheckedCitiesChange()
      }
    },
    // 添加过滤器时
    onAddItem() {
      let name = this.showFalgTemp === 'Btns' ? '新增权限组' : '新增过滤器'
      let cubePermName = this.list.length + 1 + '-' + name
      let newFilter = {
        cubePermName,
        dataPermId: '',
        cubeDataId: parseInt(this.cubeId),
        filterRelation: { where: { conditions: [], filters: [], relation: 'AND' } },
        filterList: [],
        excludeColumn: [],
        btnsList: [],
        columnBtnsList: [],
        isDefault: 0
      }
      this.checkAll = false
      this.list.push(newFilter)
      this.nowName = cubePermName
      this.nowFilter = newFilter
    },
    //全选
    handleCheckAllChange(val) {
      console.log(val)
      let btnList = this.customSystemBtns.map((i) => {
        return i.value
      })
      let columnBtnsList = this.customTableData.map((i) => {
        return i.value
      })
      this.nowFilter.btnsList = val ? btnList : []
      this.nowFilter.columnBtnsList = val ? columnBtnsList : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(e) {
      let checkedCount = this.nowFilter.btnsList.length + this.nowFilter.columnBtnsList.length
      let boxcheckedCount = this.customSystemBtns.length + this.columnBtns.length
      this.checkAll = checkedCount === boxcheckedCount
      this.isIndeterminate = checkedCount > 0 && checkedCount < boxcheckedCount
    },

    onUseParamChange(condition) {
      if (condition.useParam) {
        condition.values = ['', '']
      } else {
        condition.paramKey = ''
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.btnsList {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
  .btn-label {
    width: 80px;
    display: inline-block;
    line-height: 32px;
  }

  >>> .el-checkbox {
    width: 100%;
    margin-bottom: 10px;
    margin-right: 0;

    .el-checkbox__input {
      line-height: 28px;
    }

    .el-checkbox__label {
      .el-cascader {
        width: 160px;
      }
    }
  }
}

.columnBtnList {
  >>> .el-checkbox {
    &:last-child {
      margin-bottom: 0;
    }
  }
}
::v-deep .btnsList.el-checkbox {
  width: 100%;
  margin-bottom: 10px;
  margin-right: 0;
}
.newbi-dataset-filter {
  height: 100%;
  .wrapper {
    display: flex;
    height: 100%;
    .left {
      .el-tabs {
        height: 90%;
        .el-tabs__content {
          display: none;
        }
      }
      .add-tab {
        text-align: center;
        margin-right: 9px;
        padding: 13px 0;
      }
    }
    .right {
      flex: 1;
      height: 100%;
      overflow-y: auto;
      .filter-item {
        width: 300px;
        display: flex;
        height: 30px;
        line-height: 30px;
        align-items: center;
        padding: 0 10px;
        margin: 10px;
        border: 1px solid #ccc;
        .title {
          flex: 1;
          &.WEIDU {
            color: #468cff;
          }
          &.ZHIBIAO {
            color: #00c13a;
          }
        }
        .type {
          color: #777;
        }
      }
      .column {
        padding: 0 8px;
        margin: 8px 4px;
        width: 200px;
        height: 26px;
        line-height: 26px;
        font-size: 14px;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;
        &.WEIDU {
          border: 1px solid #468cff;
        }
        &.ZHIBIAO {
          border: 1px solid #00c13a;
        }
        .close {
          color: #f56c6c;
          cursor: pointer;
          margin-left: 5px;
        }
      }
      .el-tabs {
        margin-left: 10px;
      }
      .el-tab-pane {
        height: 93%;
        //overflow-y: auto;
      }
    }
  }
  .btns {
    margin-top: 20px;
    text-align: center;
    .el-button {
      width: 80px;
    }
  }
}
.newbi-dataset-filter-drop {
  .el-input {
    margin: 0 5px;
    width: 160px;
  }
  .fields {
    margin: 5px 0;
    height: 400px;
    overflow-y: auto;
  }
  .el-dropdown-menu__item {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 160px;
    &.WEIDU {
      color: #468cff;
    }
    &.ZHIBIAO {
      color: #00c13a;
    }
    &.select {
      color: #777;
      &:hover {
        background-color: #fff;
      }
    }
  }
}
</style>
