<template>
  <div class="patent-articles-patent-field">
    <el-form label-position="top" class="custom-field-form">
      <template v-for="(item, index) in customField">
        <el-form-item :key="item.id">
          <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, index)">上移</el-dropdown-item>
                <el-dropdown-item @click.native="handleOption(1, index)">下移</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <template v-if="(item.type === 0 || item.type === 2 || item.type === 1) && !item.showField">
            <el-date-picker v-if="item.type === 1" v-model="item.selectedValue" value-format="yyyy-MM-dd" type="date"
              size="small" placeholder="选择日期" class="width_100" @blur="onChange($event, item)"></el-date-picker>
            <el-input v-else type="textarea" v-model="item.selectedValue" placeholder="请输入内容" size="small"
              @blur="onChange($event, item)"></el-input>
          </template>
          <template v-if="item.type === 4 && !item.showField">
            <div class="showValue">
              <div>
                <!-- <div v-for="fieldValue in item.selected" :key="fieldValue.value" class="value">{{ fieldValue.value }}
                </div> -->
                <el-tag
                  v-for="tag in item.selected"
                  :key="tag.value"
                  closable
                  type=""
                  @close="handleCloseValue(item,tag)">
                  {{tag.value}}
                </el-tag>
              </div>
              <el-button size="small" @click="changeShow(item)">{{ item.show ? '收起' : '修改' }}</el-button>
            </div>
            <el-radio-group v-model="item.selectedValue" v-show="item.show">
              <div v-for="option in item.option" :key="option.id">
                <el-radio class="custom-radio" :label="option.id" @change="onChange($event, item)"
                  @click.native.prevent="clickItem(option, item)">{{
                    option.name }}</el-radio>
              </div>
            </el-radio-group>
          </template>
          <template v-if="item.type === 5 && !item.showField">
            <div class="showValue">
              <div>
                <!-- <div v-for="fieldValue in item.selected" :key="fieldValue.valueId" class="value">{{ fieldValue.value }}
                </div> -->
                <el-tag
                  v-for="tag in item.selected"
                  :key="tag.value"
                  closable
                  type=""
                  @close="handleCloseValue(item,tag)">
                  {{tag.value}}
                </el-tag>
              </div>
              <el-button size="small" @click="changeShow(item)">{{ item.show ? '收起' : '修改' }}</el-button>
            </div>
            <el-checkbox-group :value="item.selectedValue" v-show="item.show">
              <el-checkbox class="custom-checkbox" v-for="option in item.option" :label="option.id" :key="option.id"
                @change="(val) => onChange(option, item, val)">{{ option.name }}</el-checkbox>
            </el-checkbox-group>
          </template>
          <template v-if="[6,7,8,9].includes(item.type) && !item.showField">
            <div class="showValue">
              <div>
                <!-- <div v-for="fieldValue in item.selected" :key="fieldValue.valueId" class="value">{{ fieldValue.value }}
                </div> -->
                <el-tag
                  v-for="tag in item.selected"
                  :key="tag.value"
                  closable
                  type=""
                  @close="handleCloseValue(item,tag)">
                  {{tag.value}}
                </el-tag>
              </div>
              <el-button size="small" @click="changeShow(item)">{{ item.show ? '收起' : '修改' }}</el-button>
            </div>
            <div v-show="item.show">
              <el-tree :data="item.option" node-key="id" default-expand-all :props="defaultProps">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <el-checkbox-group :value="item.selectedValue">
                    <el-checkbox :label="data.id" @change="(val) => onChange(data, item, val)">{{ data.name
                    }}</el-checkbox>
                  </el-checkbox-group>
                </span>
              </el-tree>
            </div>

          </template>

        </el-form-item>
      </template>

    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    projectId: {
      default: 0
    },
    taskId: {
      default: null,
    },
    patentNo: ''
  },
  data() {
    return {
      customField: [],
      defaultProps: {
        children: 'child',
        label: 'name'
      },
    }
  },
  watch: {
    patentNo() {
      this.getOptionsAndSelected()
    }
  },
  mounted() {
    this.getCustomField()
  },
  methods: {
    //上移下移
    handleOption(type, index) {
      if (index == 0) {
        this.$message.warning('已是最顶层')
        return false
      }
      if (index == this.customField.length - 1) {
        this.$message.warning('已是最后一层')
        return false
      }
      if (type == 0) {
        var current = index - 1
        var next = index
      } else {
        var current = index
        var next = index + 1
      }
      var order = this.customField[current].sysOrder
      this.customField[current].sysOrder = this.customField[next].sysOrder
      this.customField[next].sysOrder = order
      var temp = JSON.parse(JSON.stringify(this.customField[current]))
      this.customField[current] = JSON.parse(JSON.stringify(this.customField[next]))
      this.customField[next] = temp
      let params = {
        taskId: this.taskId,
        projectId: this.projectId,
        allCustomFieldVOs: this.customField
      }

      this.$api.addAllPatentCustomFieldOrder(params).then(res => {
        if (res.code == 200) {
          this.$message('移动成功')
          // this.getCustomField()
          this.$forceUpdate()
        }
      })
    },
    // 
    clickItem(data, item) {
      this.gong(data, item)
    },
    handleCloseValue(item,tag){
      var params = {
        projectId: this.projectId,
        taskId: this.taskId,
        fieldType: item.type,
        fieldId: item.id,
        fieldValue: [tag.valueId],
        patentNo: this.patentNo,
        optionType: 0,
      }
      this.$api.addCustomFieldValue(params).then(response => {
        if (response.code == 200) {
          this.$message.success('修改成功')
          var index = item.selected.findIndex(i=>{
            return i.valueId == tag.valueId
          })
          item.selected.splice(index,1)
          item.selectedValue.splice(index,1)
          this.refresh(item)
        }
      }).catch(error => {

      })
    },
    //切换选择
    onChange(data, item, checked) {
      this.gong(data, item, checked)
    },
    // change与clickItem公用
    gong(data, item, checked) {
      var params = {
        projectId: this.projectId,
        taskId: this.taskId,
        fieldType: item.type,
        fieldId: item.id,
        fieldValue: [data.id || data],
        patentNo: this.patentNo,
        optionType: '',
      }
      if (item.type == 0 || item.type == 1 || item.type == 2 || item.type == 4) {
        if (item.type != 4) {
          params.fieldValue[0] = item.selectedValue
        } else {
          if (item && item.selectedValue) {//单选的id
            this.$set(item, 'selectedValue', '')
            this.$set(item, 'selected', [])
          } else {
            this.$set(item, 'selectedValue', data.id)
            item.selected.push(
              {
                value: data.name,
                valueId: data.id
              }
            )
          }
        }
        params.optionType = 2
      }
      // 判断optionType  0取消1添加2覆盖
      if (item.type == 6 || item.type == 5) {
        if (checked) {
          item.selectedValue.push(data.id)
          var name = ''
          if (data.pathName == '/') {
            name = data.pathName + data.name
          } else if (data.pathName) {
            name = data.pathName + '/' + data.name
          } else {
            name = data.name
          }
          item.selected.push(
            {
              value: name,
              valueId: data.id
            }
          )
          params.optionType = 1
        } else {
          let index = item.selectedValue.findIndex(valIndex => {
            return valIndex == data.id
          })
          if (index != -1) {
            item.selectedValue.splice(index, 1)
            item.selected.splice(index, 1)
          }
          params.optionType = 0
        }
      }
      this.$api.addCustomFieldValue(params).then(response => {
        if (response.code == 200) {
          this.$message.success('修改成功')
          // this.getSelected(item)
          this.refresh(item)
        }
      }).catch(error => {

      })
    },
    //刷新
    refresh(item) {
      this.$set(item, 'showField', true)
      this.$nextTick(() => {
        this.$set(item, 'showField', false)
      })
    },
    // 获取栏位
    getCustomField() {
      var params = {
        projectId: this.projectId,
        taskId: this.taskId
      }
      this.$api.getAllPatentCustomField(params).then(response => {
        if (response.code == 200) {
          this.customField = response.data.data
          this.getOptionsAndSelected()
        }
      }).catch(error => {
        this.customField = []
      })
    },
    //获取栏位的选项和选项值（0数字，1日期，2文本，4单选，5多选，6树，7产品8产品类别9技术分类）
    getOptionsAndSelected() {
      this.customField.forEach(item => {
        this.getSelected(item)
      });
    },
    //切换是否修改
    changeShow(item) {
      this.$set(item, 'show', !item.show)
      if (item.option && item.option.length > 0) {
        return;
      }
      this.getOption(item)
    },
    getOption(item) {
      switch (item.type) {
        case 4:
        case 5:
          this.getCustomOption(item)
          break;
        case 6:
          this.queryProductCategory(item, 4)
          break;
        case 7://接口传值类型：1产品类别，2产品，3技术分类，4自定义树
          this.queryProductCategory(item, 2)
          break;
        case 8:
          this.queryProductCategory(item, 1)
          break;
        case 9:
          this.queryProductCategory(item, 3)
          break;
      }
    },
    //获取已选中选项值、已添加的值
    getSelected(item) {
      let params = {
        projectId: this.projectId,
        taskId: this.taskId,
        fieldType: item.type,
        fieldId: item.id,
        patentNo: this.patentNo,
      }
      this.$api.getCustomFieldValues(params).then(response => {
        if (response.code == 200) {
          // item.selected = response.data.data
          this.$set(item,'selected',response.data.data)
          switch (item.type) {
            case 0://数字，日期，文字
            case 1:
            case 2:
              this.$set(item, 'selectedValue', (item.selected && item.selected.length > 0) ? item.selected[0].value : '')
              break;
            case 4://单选
              this.$set(item, 'selectedValue', (item.selected && item.selected.length > 0) ? item.selected[0].valueId : '')
              break;
            case 6://多选和树
            case 5:
              var a = []
              // item.selectedValue = []
              a = (item.selected && item.selected.length > 0) ? item.selected.map(item => item.valueId) : []
              this.$set(item, 'selectedValue', a)
              break;

            default:
              break;
          }

        }
      }).catch(error => {
        item.selected = []
      })
    },
    //查询自定义栏位选项
    getCustomOption(item) {
      var params = {
        customFieldId: item.id
      }
      this.$api.queryCustomOption(params).then(response => {
        if (response.code == 200) {
          this.$set(item, 'option', response.data.data)
        }
      }).catch(error => {
        this.$set(item, 'option', [])
      })
    },
    //获取产品或产品类别架构以及技术分类
    queryProductCategory(item, type) {
      let params = {
        projectId: this.projectId,
        taskId: this.taskId,
        type: type,//类型：1产品类别，2产品，3技术分类，4自定义树
        typeId: item.id,//产品或类别id
      }
      this.$api.queryTreeNodeTree(params).then(res => {
        if (res.code == 200) {
          this.$set(item, 'option', res.data.data)
        }
      }).catch(err => {
        this.$set(item, 'option', [])
      })
    },
  }
}
</script>

<style lang="scss">
.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>
<style lang="scss" scoped>
.showValue {
  width: 100%;
  display: flex;
  align-items: center;

  &>div {
    width: 100%;
    min-height: 30px;
    border: 1px solid var(--color1);
  }

  .value {

    padding: 5px;
    line-height: 20px;
  }
}
</style>