<template>
  <div class="select-box" v-loading="selectedLoad[dimension]">
    <el-cascader v-model="form.schema[dimension].field" :options="options[dimension]" :props="props" @change="onChange(true, true)" :show-all-levels="false" clearable style="width: 100%"></el-cascader>
    <el-select v-if="expandField[dimension].length" v-model="form.schema[dimension].expand" @change="onChange3(dimension)" placeholder="请选择拓展字段" style="width: 100%;margin-top: 15px;">
      <el-option v-for="item in expandField[dimension]" :value="item.id" :label="item.name"></el-option>
    </el-select>
    <div>
      <div style="text-align: right;height: 40px;">
        <template v-if="form.schema[dimension].type !== 6">
          <el-button v-if="form.schema[dimension].ptype === 3 || form.schema[dimension].ptype === 4" type="text" @click="handleEdit">编辑</el-button>
          <template v-else-if="form.schema[dimension].ptype === 1 || form.schema[dimension].ptype === 2">
            <el-dropdown size="medium" @command="handleCommand">
              <el-button type="text" class="el-dropdown-link">
                <span v-if="form.schema[dimension].num !== allData">{{ form.schema[dimension].ptype === 1 ? `Top` : `最近` }} {{ form.schema[dimension].num }}</span>
                <span v-else>全部数据</span>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="i in 5" :command="i * 10"><span>{{ form.schema[dimension].ptype === 1 ? `Top` : `最近` }}</span> {{ i * 10 }}</el-dropdown-item>
                <el-dropdown-item :command="allData">全部数据</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </template>
        <template v-else>
          <el-button type="text" @click="handleSelectAll">全选</el-button>
          <el-button type="text" @click="handleCancelAll">取消</el-button>
        </template>
      </div>
      <el-container class="selected-list">
        <template v-if="form.schema[dimension].ptype !== 0">
          <el-main :style="{ padding: form.schema[dimension].type === 6 ? '15px 0' : '15px' }">
            <template v-if="form.schema[dimension].type !== 6">
              <el-checkbox-group v-model="selected[dimension]">
                <el-row v-for="item in form.source[dimension]">
                  <el-checkbox :label="item.name">{{ item.name }}</el-checkbox>
                </el-row>
              </el-checkbox-group>
            </template>
            <template v-else>
              <el-tree ref="tree" :data="form.source[dimension]" check-strictly :default-checked-keys="treeKey[dimension]" @check-change="checkChange" show-checkbox node-key="id" :props="defaultProps"></el-tree>
            </template>
          </el-main>
        </template>
      </el-container>
    </div>
    <el-dialog title="编辑" :visible.sync="dialogVisible" width="700px" append-to-body>
      <div class="sc-form-table">
        <el-table :data="copyData" border>
          <el-table-column type="index" width="50" fixed="left">
            <template slot="header">
              <el-button type="primary" icon="el-icon-plus" size="mini" circle @click="rowAdd()"></el-button>
            </template>
            <template slot-scope="scope">
              <div class="sc-form-table-handle">
                <span>{{scope.$index + 1}}</span>
                <el-button type="danger" icon="el-icon-delete" size="mini" plain circle @click="rowDel(scope.row, scope.$index)"></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="名称" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="开始" align="center" width="200">
            <template slot-scope="scope">
              <div v-if="form.schema[dimension].ptype === 3">
                <el-select v-model="scope.row.min.operator" size="small" placeholder="" style="width: 60px;">
                  <el-option :value="0" label=">"></el-option>
                  <el-option :value="1" label="≥"></el-option>
                </el-select>
                <el-input v-model="scope.row.min.value" size="small" style="width: 100px;padding-left: 10px;"></el-input>
              </div>
              <div v-else-if="form.schema[dimension].ptype === 4">
                <el-date-picker v-model="scope.row.startTime" value-format="yyyy-MM-dd" size="small" type="date" placeholder="选择开始日期" style="width: 100%;"></el-date-picker>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="结束" align="center" width="200">
            <template slot-scope="scope">
              <div v-if="form.schema[dimension].ptype === 3">
                <el-select v-model="scope.row.max.operator" size="small" placeholder="" style="width: 60px;">
                  <el-option :value="2" label="<"></el-option>
                  <el-option :value="3" label="≤"></el-option>
                </el-select>
                <el-input v-model="scope.row.max.value" size="small" style="width: 100px;padding-left: 10px;"></el-input>
              </div>
              <div v-else-if="form.schema[dimension].ptype === 4">
                <el-date-picker v-model="scope.row.endTime" value-format="yyyy-MM-dd" size="small" type="date" placeholder="选择结束日期" style="width: 100%;"></el-date-picker>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loadingBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { customPage } from "@/views/analyse/custom/mixins";
import { mapGetters } from "vuex";
import { findChildren, getTreeDataList } from "@/utils";
import { getSourceName, getTreeNameByIds } from "@/utils/chart";

export default {
  mixins: [customPage],
  props: ['dimension'],
  data() {
    return {
      allData: 9999999,
      dialogVisible: false,
      loadingBtn: false,
      copyData: [],
      parentId: -1,
      props: {
        expandTrigger: 'click',
        value: 'id',
        label: 'name',
        emitPath: false
      },
      expandField: {
        x: [],
        y: [],
      },
      options: {
        x: [],
        y: [],
      },
      typeList: {
        '90': '分类号',
        '91': '公司/人',
        '92': '日期',
        '93': '区域',
        '94': '引用/同族',
        '95': '其他',
        '96': '自定义字段',
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    ...mapGetters(['projectId', 'userinfo', 'customField', 'patentField'])
  },
  watch: {
    selected: {
      deep: true,
      handler(n, o) {
        if (this.form.schema[this.dimension].type !== 6) {
          this.form.source[this.dimension].map(item => {
            item.selected = this.selected[this.dimension].indexOf(item.name) !== -1
          })
          this.$store.dispatch('getItemSettingColor', [])
        }
      }
    }
  },
  mounted() {
    this.onChange(false, false)
    if (this.form.schema[this.dimension].type === 6) {
      let tree = getTreeDataList(this.form.source[this.dimension], [])
      if (this.treeKey[this.dimension].length) {
        let data = tree.find(item => item.id === this.treeKey[this.dimension][0])
        this.parentId = data ? data.parentId : -1
        this.setChildren(this.form.source[this.dimension])
      }
    }
    this.initOptions()
  },
  methods: {
    getSourceName() {
      switch (this.dimension) {
        case 'x':
          this.form.setting.title1 = getSourceName(this.form.schema.x.field, this.form.schema.x.expand, this.form.schema.x.num)
          break
        case 'y':
          this.form.setting.title2 = getSourceName(this.form.schema.y.field, this.form.schema.y.expand, this.form.schema.y.num)
          break
      }
    },
    initOptions() {
      for (let key in this.options) {
        let data = []
        for (let type in this.typeList) {
          let children = {
            id: type,
            name: this.typeList[type],
            children: []
          }
          if (type === '96') {
            children.children = this.patentField.filter(item => item.type < 90 || item.type === 96)
          } else {
            children.children = this.patentField.filter(item => String(item.type) === type)
          }
          data.push(children)
        }
        this.$set(this.options, key, data)
      }
    },
    updateSelected() {
      this.selected[this.dimension] = this.form.source[this.dimension].slice(0, this.form.schema[this.dimension].num).map(item => item.name)
      this.getSourceName()
    },
    async handleCommand(command) {
      this.form.schema[this.dimension].num = command
      await this.$store.dispatch('getSourceDataList', this.dimension)
      this.updateSelected()
    },
    async onChange(option, reset) {
      const field = this.patentField.find(item => item.id === this.form.schema[this.dimension].field)
      if (field) {
        this.$set(this.expandField, this.dimension, field.expand || [])
      } else {
        this.$set(this.form.schema[this.dimension], 'field', null)
        this.$set(this.expandField, this.dimension, [])
      }
      if (option && !field) {
        this.$store.commit('SET_RELOAD_DATA', true)
      }
      if (reset) {
        this.$set(this.form.schema[this.dimension], 'expand', null)
        await this.onChange3(this.dimension)
      }
    },
    getSchemaType() {
      let ptype = 0, type = 0
      const field = this.patentField.find(item => item.id === this.form.schema[this.dimension].field)
      if (field) {
        type = field.type
        if (field.ptype === 0 && this.form.schema[this.dimension].expand) {
          const expand = field.expand.find(item => item.id === this.form.schema[this.dimension].expand)
          ptype = expand.ptype
        } else {
          ptype = field.ptype
        }
      } else {
        ptype = 0
      }
      this.$set(this.form.schema[this.dimension], 'type', type)
      this.$set(this.form.schema[this.dimension], 'ptype', ptype)
    },
    async onChange3(dimension) {
      this.copyData = []
      this.getSchemaType()
      this.$store.commit('SET_CHANGE_NUM')
      if (this.form.schema[dimension].field) {
        await this.$store.dispatch('getSourceDataList', dimension)
      } else {
        this.form.source[dimension] = []
      }
      if (this.form.source[dimension].length === 0) {
        switch (this.form.schema[dimension].field) {
          case 32:
            this.form.source[dimension] = [{
              name: '0',
              min: {
                operator: 1,
                value: '0'
              },
              max: {
                operator: 3,
                value: '0'
              },
              selected: true
            }, {
              name: '1-5',
              min: {
                operator: 1,
                value: '1'
              },
              max: {
                operator: 3,
                value: '5'
              },
              selected: true
            }, {
              name: '6-10',
              min: {
                operator: 1,
                value: '6'
              },
              max: {
                operator: 3,
                value: '10'
              },
              selected: true
            }, {
              name: '11-20',
              min: {
                operator: 1,
                value: '11'
              },
              max: {
                operator: 3,
                value: '20'
              },
              selected: true
            }, {
              name: '21-30',
              min: {
                operator: 1,
                value: '21'
              },
              max: {
                operator: 3,
                value: '30'
              },
              selected: true
            }, {
              name: '30以上',
              min: {
                operator: 1,
                value: '30'
              },
              max: {
                operator: 3,
                value: '99999'
              },
              selected: true
            }]
            break
          case 33:
            this.form.source[dimension] = [{
              name: '0',
              min: {
                operator: 1,
                value: '0'
              },
              max: {
                operator: 3,
                value: '0'
              },
              selected: true
            }, {
              name: '1-5',
              min: {
                operator: 1,
                value: '1'
              },
              max: {
                operator: 3,
                value: '5'
              },
              selected: true
            }, {
              name: '6-10',
              min: {
                operator: 1,
                value: '6'
              },
              max: {
                operator: 3,
                value: '10'
              },
              selected: true
            }, {
              name: '11-30',
              min: {
                operator: 1,
                value: '11'
              },
              max: {
                operator: 3,
                value: '30'
              },
              selected: true
            }, {
              name: '30以上',
              min: {
                operator: 1,
                value: '30'
              },
              max: {
                operator: 3,
                value: '99999'
              },
              selected: true
            }]
            break
          case 34:
          case 35:
          case 55:
            this.form.source[dimension] = [{
              name: '1',
              min: {
                operator: 1,
                value: '1'
              },
              max: {
                operator: 3,
                value: '1'
              },
              selected: true
            }, {
              name: '2-5',
              min: {
                operator: 1,
                value: '2'
              },
              max: {
                operator: 3,
                value: '5'
              },
              selected: true
            }, {
              name: '6-10',
              min: {
                operator: 1,
                value: '6'
              },
              max: {
                operator: 3,
                value: '10'
              },
              selected: true
            }, {
              name: '11-20',
              min: {
                operator: 1,
                value: '11'
              },
              max: {
                operator: 3,
                value: '20'
              },
              selected: true
            }, {
              name: '20-50',
              min: {
                operator: 1,
                value: '20'
              },
              max: {
                operator: 3,
                value: '50'
              },
              selected: true
            }, {
              name: '50以上',
              min: {
                operator: 1,
                value: '50'
              },
              max: {
                operator: 3,
                value: '99999'
              },
              selected: true
            }]
            break
        }
      }
      this.updateSelected()
    },
    handleEdit() {
      this.copyData = JSON.parse(JSON.stringify(this.form.source[this.dimension]))
      this.dialogVisible = true
    },
    cancel() {
      this.dialogVisible = false
    },
    async handleConfirm() {
      this.validateForm().then(async (response) => {
        this.form.source[this.dimension] = JSON.parse(JSON.stringify(this.copyData))
        let selected = this.selected
        selected[this.dimension] = this.form.source[this.dimension].map(item => item.name)
        this.$store.commit('SET_CHART_SELECTED', selected)
        this.$store.commit('SET_RELOAD_DATA', true)
        this.dialogVisible = false
      }).catch(error => {
        this.$message.error(error)
      })
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        const name = this.copyData.map(item => item.name)
        if (name.indexOf("") !== -1) {
          reject('请输入名称')
        }
        if (new Set(name).size !== name.length) {
          reject('名称不能重复')
        }
        switch (this.form.schema[this.dimension].ptype) {
          case 3:
            if (this.copyData.map(item => item.min.value).indexOf("") !== -1 || this.copyData.map(item => item.min.operator).indexOf("") !== -1 || this.copyData.map(item => item.max.value).indexOf("") !== -1 || this.copyData.map(item => item.max.operator).indexOf("") !== -1) {
              reject('运算符或范围不能为空')
            }
            resolve()
            break;
          case 4:
            if (this.copyData.map(item => item.startTime).indexOf("") !== -1 || this.copyData.map(item => item.endTime).indexOf("") !== -1 || this.copyData.map(item => item.startTime).indexOf(null) !== -1 || this.copyData.map(item => item.endTime).indexOf(null) !== -1) {
              reject('开始或结束时间不能为空')
            }
            resolve()
            break;
        }
        reject('参数类型错误')
      })
    },
    rowAdd() {
      switch (this.form.schema[this.dimension].ptype) {
        case 3:
          this.copyData.push({
            name: '',
            min: {
              operator: '',
              value: ''
            },
            max: {
              operator: '',
              value: ''
            },
            selected: true
          })
          break
        case 4:
          this.copyData.push({
            name: '',
            startTime: '',
            endTime: '',
            selected: true
          })
          break
      }
    },
    rowDel(row, index) {
      this.copyData.splice(index, 1)
    },
    setChildren(arr) {
      arr.forEach(item => {
        this.$set(item, 'disabled', item.parentId !== this.parentId && this.parentId !== -1)
        if (item.children && item.children.length) {
          this.setChildren(item.children)
        } else {

        }
      })
    },
    checkChange(data, checked, indeterminate) {
      this.parentId = -1
      this.treeKey[this.dimension] = this.$refs.tree.getCheckedKeys()
      if (this.parentId === -1) {
        this.parentId = data.parentId
      }
      if (this.treeKey[this.dimension].length === 0) {
        this.parentId = -1
      }
      this.selected[this.dimension] = getTreeNameByIds(this.form.source[this.dimension], this.treeKey[this.dimension])
      this.$store.commit('SET_RELOAD_DATA', true)
      this.setChildren(this.form.source[this.dimension])
    },
    handleSelectAll() {
      if (this.parentId === -1) {
        return false
      }
      const tree = getTreeDataList(this.form.source[this.dimension], [])
      const data = tree.filter(item => item.parentId === this.parentId)
      this.treeKey[this.dimension] = data.map(item => item.id)
      this.selected[this.dimension] = getTreeNameByIds(this.form.source[this.dimension], this.treeKey[this.dimension])
      this.$store.commit('SET_RELOAD_DATA', true)
    },
    handleCancelAll() {
      this.parentId = -1
      this.treeKey[this.dimension] = []
      this.selected[this.dimension] = []
      this.$refs.tree.setCheckedKeys([])
      this.$store.commit('SET_RELOAD_DATA', true)
      this.setChildren(this.form.source[this.dimension])
    }
  }
}
</script>

<style lang="less">
.select-box {
  padding: 15px;
}
.selected-list {
  background: #f4f4f4;
  height: 250px !important;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  .el-main {
    .el-row {
      line-height: 20px;
    }
    .el-tree {
      background: none !important;
    }
  }
}
</style>
