<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" :key="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>
            <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 }}<span v-if="item.number == 0 || item.number">({{ item.number }})</span></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="true"  :close-on-click-modal="false">
      <el-container>
        <el-header v-if="form.schema[dimension].ptype === 4">
          <div class="head">
            <p>
              <span>最小年份：{{ minDate }}</span>
              <span>最大年份：{{ maxDate }}</span>
            </p>
            <div>
              <el-popover placement="bottom" title="" ref="popover" width="100" trigger="click">
                <el-main class="patent-fast-edit-popover">
                  <div class="btn" @click="quickAdd(0)">清空</div>
                  <div class="btn" @click="quickAdd(2)">2年</div>
                  <div class="btn" @click="quickAdd(3)">3年</div>
                  <div class="btn" @click="quickAdd(4)">5年</div>
                  <el-divider></el-divider>
                  <div class="select-number">
                    <el-input size="mini" type="number" v-model="num" @change="quickAdd(num)"></el-input>
                    <span>年</span>
                  </div>
                </el-main>
                <el-button type="text" size="small" class="margin-left_10" slot="reference"> 快速添加<i
                  class="el-icon-arrow-down el-icon--right"></i></el-button>
            </el-popover>

            </div>
          </div>
        </el-header>
        <el-main class="sc-form-table">
          <el-table :data="copyData" border>
            <el-table-column type="index" width="50" >
              <template slot="header">
                <el-button type="primary" icon="el-icon-plus" size="mini" circle @click="rowAdd()"></el-button>
              </template>
              <template slot-scope="scope">
                <div>
                  <!-- <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">
                <div v-if="quick">
                  {{ scope.row.name }}
                </div>
                <div v-else>
                  <el-input v-model="scope.row.name" size="small"></el-input>
                </div>
                
              </template>
            </el-table-column>
            <el-table-column label="开始" align="center" width="200">
              <template slot-scope="scope">
                <div v-if="quick">
                  {{ scope.row.startTime }}
                </div>
                <div v-else>
                  <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>
                </div>
                
              </template>
            </el-table-column>
            <el-table-column label="结束" align="center" width="200">
              <template slot-scope="scope">
                <div v-if="quick">
                  {{ scope.row.endTime }}
                </div>
                <div v-else>
                  <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>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <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: 'value',
        label: 'name',
        emitPath: false
      },
      expandField: {
        x: [],
        y: [],
      },
      options: {
        x: [],
        y: [],
      },
      typeList: {
        'classify': '分类号',
        'company': '公司/人',
        'dateType': '日期',
        'nation': '区域',
        'amount': '引用/同族',
        '95': '其他',
        '96': '自定义字段',
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      maxDate:'',
      minDate:'',
      quick:false,
      num:0,
    }
  },
  computed: {
    ...mapGetters([ 'userinfo',  '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.initData()
    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, this.form.schema.x.expand, this.form.schema.x.num)
          break
        case 'y':
          this.form.setting.title2 = getSourceName(this.form.schema.y, this.form.schema.y.expand, this.form.schema.y.num)
          break
      }
    },
    initData(){
      var data = this.patentField
      for (let i = 0; i < data.length; i++) {
        if(data[i].groupBy == 'dateType'){
          data[i].expand = [
                {
                    "id": '月',
                    "name": "月",
                    "ptype": 2
                },
                {
                    "id": "季",
                    "name": "季",
                    "ptype": 2
                },
                {
                    "id": "半年",
                    "name": "半年",
                    "ptype": 2
                },
                {
                    "id": "年",
                    "name": "年",
                    "ptype": 2
                },
                {
                    "id": "自定义",
                    "name": "自定义",
                    "ptype": 4
                }
            ]
        }
        // 给ipc、cpc、upc、loc添加大小类等
        if (data[i].groupBy == 'classify') {
            var special= {
              MC: [
                { id: 'IC', name: '部' },
                { id: 'IC2', name: '大类' },
                { id: 'IC3', name: '小类' },
                { id: 'IC4', name: '大组' },
                { id: 'IC5', name: '小组' },
              ],
              CPC: [
                { id: 'CPC', name: '部' },
                { id: 'CPC2', name: '大类' },
                { id: 'CPC3', name: '小类' },
                { id: 'CPC4', name: '大组' },
                { id: 'CPC5', name: '小组' },
              ],
              UPC: [
                // { value: '0', label: '分类号' },//老系统有
                { id: 'UPC', name: '大类' },
                { id: 'UPC2', name: '小类' },
              ],
              LOC: [
                // { value: '0', label: '分类号' },//老系统有
                { id: 'LOC', name: '大类' },
                { id: 'LOC2', name: '小类' },
              ],
            }
            data[i].expand = special[data[i].value]
          }
      }
      this.$store.commit('SET_SYSTEM_FIELD',data)
    },
    initOptions() {
      let obj = {
        text: '文本',
        number: '号码',
        typeStatus: '类型及状态',
        classify: '分类',
        dateType: '日期',
        company: '公司/人',
        typeStatus: '类型及状态',
        address: '地址',
        nation: '国家/地区',
        amount: '引用',
        customField: '自定义字段',
      }
      let filedObj = {}
      let data = this.patentField
      for (let i = 0; i < data.length; i++) {
        if (data[i].filedKind == -1) {//专利本身
          if(['text','number','address'].includes(data[i].groupBy)){
            continue
          }
          if(data[i].groupBy == 'nation'){
            if(data[i].name.indexOf('县')!=-1 ){
              continue
            }
          }
          if (filedObj[data[i].groupBy]) {
            filedObj[data[i].groupBy].children.push(data[i])
          } else {
            filedObj[data[i].groupBy] = {
              value: data[i].groupBy,
              name: obj[data[i].groupBy],
              children: [
                data[i]
              ],
            }
          }
          
        } else {//自定义字段
          if (filedObj.customField) {
            filedObj.customField.children.push(data[i])
          } else {
            filedObj[data[i].group] = {
              value: 'customField',
              name: obj.customField,
              children: [data[i]]
            }
          }
        }
      }
      var options = Object.values(filedObj)
      for (let key in this.options) {
        this.$set(this.options, key, options)
      }
    },
    updateSelected() {
      this.selected[this.dimension] = this.form.source[this.dimension].slice(0, this.form.schema[this.dimension].num).map(item => item.name)
      // this.$store.commit('SET_CHART_SELECTED', this.selected)
      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.value === 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) {
        if(field && field.groupBy == 'dateType'){
           this.$set(this.form.schema[this.dimension], 'expand', '年')
        }else{
          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.value === this.form.schema[this.dimension].field)
      if (field) {
        type = field.type
        if (!field.ptype && 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
          if (['classify'].includes(field.groupBy)) {
            ptype = 0
          }
          if(['amount'].includes(field.groupBy)){
            ptype = 3
          }
        }
        this.$set(this.form.schema[this.dimension], 'fieldKind', field.filedKind)
        this.$set(this.form.schema[this.dimension], 'name', field.name)
        this.$set(this.form.schema[this.dimension], 'groupBy', field.groupBy)
      } 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] = []
      }

      this.updateSelected()
    },
    //快速添加
    quickAdd(option1){
      if(option1 == 0){
        this.copyData = []
        this.quick = false
        return false
      }
      var min = Number(this.minDate)
      var max = Number(this.maxDate)
      var data = []
     
      var option = Number(option1)
      for(var i = max;i>min;i=i-option){
        var prev = (i-option)<min?min:i-option
        data.push(
          {
            name:`${prev}-${i}`,
            endTime:i,
            startTime:prev
          }
        )
      }
      this.quick = true
      this.copyData = data
      this.$refs.popover.doClose()
    },
    async handleEdit() {
      this.copyData = JSON.parse(JSON.stringify(this.form.source[this.dimension]))
      if(this.form.schema[this.dimension].type == 'DateTime'){
        const field = this.patentField.find(item => item.value === this.form.schema[this.dimension].field)
        if(field){
          if(!field.minDate && !field.maxDate){
            var param = {
              ...this.form.search,
              field:field.field
            }
            await this.$api.getFieldRange(param).then(response=>{
              if(response.code == 200){
                field.maxDate = response.data.maxDate
                field.minDate = response.data.minDate
              }
            })
          }
          this.maxDate = field.maxDate
          this.minDate = field.minDate
        }
      }
      this.quick  = false
      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
        if(this.form.schema[this.dimension].ptype == 4){
          selected[this.dimension] = this.form.source[this.dimension].map(item => `${item.startTime}-${item.endTime}`)
        }else if(this.form.schema[this.dimension].ptype == 3){
          selected[this.dimension] = this.form.source[this.dimension].map(item => `${item.min.value}-${item.max.value}`)
        }
        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>
<style lang="scss" scoped>
  .head{
    width: 100%;
    display:flex;
    justify-content:space-between;
    align-items: center;
  }
</style>
<style lang="scss" scoped>
.patent-fast-edit-popover {
  padding: 0 !important;

  .btn {
    color: #000;
    line-height: 30px;
    border-radius: 5px;
    padding-left: 10px;
    text-align: left;
    font-size: 14px;
    cursor: pointer;

    &:hover {
      background: #adadad;
      color: #fff;
    }
  }

  .disabled {
    cursor: not-allowed !important;
  }

  .bottom {
    text-align: right;
    color: #1e9fff;
    line-height: 40px;
    padding-left: 10px;
    font-size: 18px;
  }

  .el-divider--horizontal {
    margin: 10px 0 !important;
  }

  .select-number {
    .el-input {
      width: 70px;
    }

    span {
      padding: 0 3px;
    }
  }
}
</style>
