<template>
  <div class="patent-articles-patent-field">
    <el-form label-position="top" class="custom-field-form" v-if="!lock">
      <template v-for="(item, index) in customField">
        <el-form-item>
          <template slot="label">
            <span :title="item.name" class="name">{{ item.name }}</span>
          </template>
          <div class="option">
            <el-dropdown size="small">
              <span class="el-dropdown-link">
                <i class="el-icon-more el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleOption(0, item.id, index)">上移</el-dropdown-item>
                <el-dropdown-item @click.native="handleOption(1, item.id, index)">下移</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <template v-if="item.type === 0 || item.type === 2 || item.type === 1">
            <div v-for="(val, i) in selected[item.id]" class="custom-input">
              <el-date-picker v-if="item.type === 1" :disabled="!($permission('/workspace/details/indexing') && $r(projectId,[1,2]))" v-model="val.label" value-format="yyyy-MM-dd" type="date" size="small" placeholder="选择日期" class="width_100" @change="onChange($event, item, val)"></el-date-picker>
              <el-input v-else type="textarea" :disabled="!($permission('/workspace/details/indexing') && $r(projectId,[1,2]))" v-model="val.label" placeholder="请输入内容" size="small" @blur="onChange($event, item, val)"></el-input>
            </div>
          </template>
          <template v-if="item.type === 4">
            <el-radio-group v-model="selected[item.id]" :disabled="!($permission('/workspace/details/indexing') && $r(projectId,[1,2]))" @change="onChange($event, item)">
              <div v-for="option in item.option">
                <el-radio class="custom-radio" :label="option.id" @click.native.prevent="getSelect(item,option.id)">{{ option.name }}</el-radio>
              </div>
            </el-radio-group>
          </template>
          <template v-if="item.type === 5">
            <el-checkbox-group v-model="selected[item.id]" :disabled="!($permission('/workspace/details/indexing') && $r(projectId,[1,2]))" @change="onChange($event, item)">
              <el-checkbox class="custom-checkbox" v-for="option in item.option" :label="option.id">{{ option.name }}</el-checkbox>
            </el-checkbox-group>
          </template>
          <template v-if="item.type === 6" >
          <div>
             <el-tree
                @check-change="onChange($event, item)"
                :ref="item.id"
                :data="item.option"
                check-strictly
                :default-checked-keys="selected[item.id]"
                show-checkbox
                node-key="id"
                default-expand-all
                :props="defaultProps"
            ></el-tree>
          </div>
           
          </template>
          
        </el-form-item>
      </template>
      
      <template v-if="product.isCategory == 1 && $permission('/workspace/product')">
        <el-form-item>
          <template slot="label">
            <span :title="product.productName" class="name">{{ product.productName }}</span>
          </template>
          <template>
            <div>
              <el-tree
                @check-change="changeCategory"
                ref="Category"
                :data="CategoryList"
                check-strictly
                :default-checked-keys="selectCategory"
                show-checkbox
                node-key="id"
                default-expand-all
                :props="{label:'structureName',value:'id'}"
            ></el-tree>
            </div>
          </template>
        </el-form-item>
          </template>
    </el-form>
  </div>
</template>

<script>
export default {
  props: ['projectId', 'patentId','patentNo'],
  data() {
    return {
      customField: [],
      loading: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      selected: {},
      lock: true,
      CategoryList:[],
      selectCategory:[],
      product:{},
      radioValue:null,
    }
  },
  watch: {
    patentId() {
      this.getPatentIndexSetting()
    },
    patentNo(val){}
  },
  activated() {
    this.getPatentIndexSetting()
  },
  mounted() {
    this.getCustomField()
    if(this.$permission('/workspace/product')){
      this.getProject()
    }
    
  },
  methods: {
    //获取专题库详情
    async getProject(){
      await  this.$api.getProject({id:this.projectId}).then(response=>{
                if(response.code == 200){
                  if(response.data[0].isCategory){
                    this.product={
                      productId:response.data[0].productId,
                      productName:response.data[0].productName,
                      structureId:response.data[0].structureId,
                      isCategory:response.data[0].isCategory
                    }
                    if(this.product.isCategory == 1){
                      this.getCategoryList()
                    }
                  }
                  
                }
              })
    },
    //获取架构详情
    getCategoryList(){
      var params = {
        productId: this.product.productId,
        structureId: this.product.structureId? this.product.structureId:0
      }
      this.$api.queryStructures(params).then(res => {
        if(res.code == 200){
          if(this.product.structureId){
            this.CategoryList = [res.data]
          }else{
            this.CategoryList = res.data.children
          }
        }
      })
    },
    //标引架构
    changeCategory(row,isSign){
      var params = {
        projectId:this.projectId,
        patentNo:this.patentNo,
        productId:row.productId,
        structureId:row.id,
        updateType:isSign
      }
      this.loading = true
      this.$api.updateProductStructurePatentIndex(params).then(response=>{
        if(response.code == 200){
          this.$message.success('操作成功')
          this.loading = false
        }else{
          this.$message.err('操作失败')
          this.loading = false
        }
      }).catch(error => {
        this.$message.err('操作失败')
        this.loading = false
      })
    },
    //获取专利标引的信息
    getCategorySetIndex(){
      var params={
        projectId:this.projectId,
        patentNo:this.patentNo
      }
      this.$api.queryProductStructurePatentIndex(params).then(response=>{
        if(response.code == 200){
          this.selectCategory = response.data.map(item=>{
            return item.structureId
          })
        }
      })
    },

    handleOption(type, id, index) {
      if ((type === 0 && index === 0) || (type === 1 && index === this.customField.length - 1)) {
        return false
      }
      let data = this.customField.map(item => {
        return {
          id: item.id,
          order: 0
        }
      })
      switch (type) {
        case 0:
          [data[index - 1], data[index]] = [data[index], data[index - 1]]
          break
        case 1:
          [data[index + 1], data[index]] = [data[index], data[index + 1]]
          break
      }
      for (let i = 0; i < data.length; i++) {
        data[i].order = i
      }
      this.$api.setProjectFieldOrder({ projectId: this.projectId, data: data }).then(response => {
        this.$message.success('操作成功')
        this.getCustomField()
      })
    },
    getSelect(val,option){
      this.radioValue = option
      this.onChange('',val)
    },
    onChange(e, val, val1) {
      if (!this.$permission('/workspace/details/indexing')) {
        return false
      }
      if (this.lock) {
        return false
      }
      let data = {
        id: this.patentId,
        fieldId: val.id,
        projectId: this.projectId,
        type: val.type,
        selected: []
      }
      switch (val.type) {
        case 0:
        case 1:
        case 2:
          data.selected = this.selected[val.id].map(item => {
            return {
              label: item.label
            }
          })
          break
        case 3:
        case 4:
          if(this.selected[val.id] == this.radioValue){
            this.selected[val.id] = 0
          }else{
            this.selected[val.id]= this.radioValue
          }
          data.selected = [{
            value: this.selected[val.id]
          }]
          this.radioValue = null
          break
        case 5:
          data.selected = this.selected[val.id].map(item => {
            return {
              value: item
            }
          })
          break
        case 6:
          const keys = this.$refs[val.id][0].getCheckedNodes();
          data.selected = keys.map(item => {
            return {
              value: item.id
            }
          })
          break
      }
      this.updatePatentIndexSetting(data)
    },
    updatePatentIndexSetting(data) {
      this.loading = true
      this.$api.updatePatentIndexSetting(data).then(response => {
        this.$message.success('操作成功')
        this.loading = false
      }).catch(error => {
        this.loading = false
      })
    },
    async getCustomField() {
      this.loading = true
      const order = await this.$api.getProjectFieldOrder({ projectId: this.projectId })
      this.$api.getProjectCustomField({ projectId: this.projectId }).then(response => {
        response.data.map(item => {
          const t = order.data.find(o => o.id === item.id)
          item.order = t ? t.order : 0
        })
        this.customField = response.data.sort((a, b) => { return a.order - b.order })
        if(this.$permission('/workspace/details/indexing') && this.$r(this.projectId,[1,2])){
        }else{
          for(var i =0;i<this.customField.length;i++){
            if(this.customField[i].type == 6){
              this.customField[i].option.forEach(item => {
            item.disabled = true;
            if (item.children) {
              this.deepEach(item.children);
            }
          });
            }
          }
          
        }
        this.loading = false
      })
    },
    deepEach(arr) {
      arr.forEach(item => {
        item.disabled = true;
        if (item.children) {
          this.deepEach(item.children); // 递归
        }
      });
},
    getPatentIndexSetting() {
      this.selected = {}
      this.lock = true
      this.getCategorySetIndex()
      this.$api.getPatentIndexSetting2({ projectId: this.projectId, patentId: this.patentId }).then(response => {
        for(let value of response.data) {
          switch (value.type) {
            case 0:
            case 1:
            case 2:
              let selected = []
              if (value.selected.length) {
                selected.push(...value.selected)
              } else {
                selected.push({
                  label: '',
                  value: -1,
                })
              }
              this.$set(this.selected, value.id, selected)
              break
            case 3:
            case 4:
              this.$set(this.selected, value.id, value.selected.length === 0 ? null : value.selected[0].value)
              break
            case 5:
            case 6:
              this.$set(this.selected, value.id, value.selected.map(item => item.value))
              break
          }
        }
        this.$nextTick(() => {
          this.lock = false
        })
      })
    },
    handleDeleteInput(item, index, field) {
      this.selected[field.id].splice(index, 1)
      this.onChange(field, item)
    },
    handleAddInput(item, field) {
      if (!item.label) {
        this.$message.error('请录入内容')
        return false
      }
      item.value = 0
      this.onChange(field, item)
      this.selected[field.id].push({
        value: -1,
        label: ''
      })
    },
  }
}
</script>

<style lang="scss">
  .jinzhi{
    cursor: not-allowed;
    pointer-events:none
  }
.patent-articles-patent-field {
  .custom-field-form {
    .name {
      display: block;
      width: 170px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .option {
      position: absolute;
      right: 0;
      top: -50px;
      color: #1e9fff;
      i {
        cursor: pointer;
      }
    }
    .el-form-item {
      margin-bottom: 0 !important;
      .el-form-item__label {
        font-size: 16px;
        border-bottom: 1px solid #d2d2d2;
        margin-bottom: 10px;
        color: #EE6666;
      }
    }
    .custom-input {
      margin-bottom: 10px;
      .el-input {
      }
      .el-button {
        float: right;
        margin-top: 5px;
      }
    }
    .custom-checkbox, .custom-radio {
      width: 100%;
      margin-right: 0 !important;
      line-height: 30px;
    }
    .el-form-item__label {
      width: 100%;
      padding: 0 !important;
    }
  }
}
</style>