<template>
    <div class="">
     
        <el-container class="project-field">
          <el-header>
            <el-form :inline="true" class="project-field-header-form">
              <el-form-item label="字段名称">
                <el-input v-model="queryParams.name" size="small" placeholder="请输入字段名称"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="" size="small" @click="getList">查询</el-button>
                <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
              </el-form-item>
            </el-form>
            <!-- <el-button class="margin-right_20" type="success" size="small" @click="handleImport" :disabled="!$permission('/workspace/common/customField/import')">导入</el-button> -->
          </el-header>
          <el-main class="project-field-main">
            <el-table v-loading="loading" :data="tableData" border header-row-class-name="custom-table-header">
              <el-table-column type="index" label="#" width="55" align="center"></el-table-column>
              <el-table-column prop="name" label="字段名称" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="类型" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ typeObj[scope.row.type] }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ statusObj[scope.row.status] }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="createName" label="创建人" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ (scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="操作" align="center" width="150">
                <template slot-scope="scope">
                  <el-dropdown  split-button type="primary" size="small">
                   <span @click="handleEdit(scope.row)">编辑</span>
                   <!-- <p v-else :disabled="true">编辑</p> -->
                    <el-dropdown-menu slot="dropdown" class="text-align_center">
                      <el-dropdown-item @click.native="handleEditOption(scope.row)" v-if="[3, 4, 5, 6].indexOf(scope.row.type) !== -1 ">选项管理</el-dropdown-item>
                      <!-- <el-dropdown-item v-else-if="[3, 4, 5, 6].indexOf(scope.row.type) !== -1" type="primary" size="small" @click.native="handleEditOption(scope.row)">选项查看</el-dropdown-item> -->
                      <!-- <el-dropdown-item :disabled="!$permission('/workspace/common/customField/copy')" @click.native="handleCopy(scope.row)">复制</el-dropdown-item> -->
                      <el-dropdown-item class="color-red" @click.native="handleDelete(scope.row)" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <!-- <el-button v-else-if="[3, 4, 5, 6].indexOf(scope.row.type) !== -1" type="primary" size="small" @click.native="handleEditOption(scope.row)">选项查看</el-button> -->
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination :current-page.sync="queryParams.current" :page-size="queryParams.size" :total="total" @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" background></el-pagination>
            </div>
          </el-main>
          <!-- <el-footer class="footer-common">
            <el-button @click="close">关 闭</el-button>
          </el-footer> -->
        </el-container>

      <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" append-to-body destroy-on-close :before-close="cancel" top="10vh">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" label-position="left">
          <el-form-item label="字段名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入字段名称"></el-input>
          </el-form-item>
          <el-form-item label="字段类型" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择字段类型" class="width_100">
              <el-option v-for="(item, key) in typeObj" :label="item" :value="parseInt(key)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="字段状态" prop="status">
            <el-select v-model="ruleForm.status" placeholder="请选择字段状态" style="width: 100%;">
              <el-option v-for="(item, key) in statusObj" :label="item" :value="parseInt(key)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" placeholder="请输入备注" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit" :loading="btnLoading">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 选项卡 -->
      <el-dialog :title="title" :visible.sync="dialogVisible2" :width="optionDialogWidth" append-to-body destroy-on-close :close-on-click-modal="false" :before-close="close2" top="10vh">
        <el-container class="project-field-option-box" v-loading="optionLoading">
          <el-main>
            <template v-if="ruleForm.type === 6">
              <el-tree
                  class="tree-option"
                  :data="ruleForm.option"
                  node-key="id"
                  default-expand-all
                  :expand-on-click-node="false"
                  draggable
                  @node-drop="handleDrop"
              >
                <div class="custom-tree-node" slot-scope="{ node, data }">
                  <el-input v-model="data.name" placeholder="请输入内容" size="small" class="r" @focus="lockOption = true" @input="valueChange = true" @blur="submitOption(data)"></el-input>
                  <div class="o">
                    <span class="el-icon-plus" @click="handleAddTreeNode(data)" title="添加"></span>
                    <span class="el-icon-delete" @click="handleDeleteTreeNode(node, data)" title="删除"></span>
                  </div>
                </div>
              </el-tree>
            </template>
            <template v-else>
              <div v-for="(item, index) in ruleForm.option" class="option">
                <el-input v-model="item.name" placeholder="请输入内容" size="small" class="t" @focus="lockOption = true" @input="valueChange = true" @blur="submitOption(item)"></el-input>
                <div class="o">
                  <span class="el-icon-delete" @click="handleDeleteOption(item, index)" title="删除"></span>
                </div>
              </div>
            </template>
          </el-main>
          <el-footer >
            <el-button type="primary" size="small" @click="handleAddOption()" :disabled="lockOption">添加</el-button>
          </el-footer>
        </el-container>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close2">关 闭</el-button>
        </div>
      </el-dialog>
  
      <!-- <import-field-dialog ref="importFieldDialog" @close="getList" />
      <copy-field-dialog ref="copyFieldDialog" @close="getList" /> -->
    </div>
</template>
  
<script>
  // import ImportFieldDialog from "./ImportField";
  // import CopyFieldDialog from "./CopyField";
  import { findTreeEq } from "@/utils";
  
export default {
    props:["handleSelectId","reportId"],
    components: {
      // ImportFieldDialog,
      // CopyFieldDialog
    },
    data() {
      return {
        optionDialogWidth: '500px',
        lockOption: false,
        valueChange: false,
        reportType:Number(this.handleSelectId),
        queryParams: {
          name: '',
          type: null,
          status: null,
          size: 10,
          current: 1,
          projectId: 0,
          order: 'desc',
          reportType: Number(this.handleSelectId),
          reportId: this.reportId,
          option:[],
        },
        projectId: 0,
        typeObj: {
          0: '数字',
          1: '日期',
          2: '文本',
          // 3: '下拉框',
          4: '单选',
          5: '多选',
          6: '树',
        },
        pTypeObj: {
          1: '标引',
          2: '分类'
        },
        statusObj: {
          0: '关闭',
          1: '正常',
        },
        drawer: false,
        dialogVisible: false,
        dialogVisible2: false,
        title: '',
        total: 0,
        ruleForm: {},
        rules: {
          name: [{ required: true, message: '请输入字段名称', trigger: 'blur' },],
          type: [{ required: true, message: '请选择类型', trigger: 'change' },],
          status: [{ required: true, message: '请选择状态', trigger: 'change' },],
        },
        btnLoading: false,
        loading: false,
        optionLoading: false,
        tableData: [],

      }
    },
    mounted() {
      this.getList()
    },
    watch: {
      handleSelectId(val) {
        this.reportType=val
        this.getList()
      },
      reportId(val) {
        this.queryParams.reportId=val
        this.getList()
      },
    },
    methods: {
      handleCurrentChange(val) {
        this.queryParams.current = val;
        this.getList();
      },
      cancel() {
        this.dialogVisible = false
      },
      open(id) {
        this.projectId = id
        this.drawer = true
        this.queryParams.projectId = this.projectId
        this.getList()
      },
      close() {
        this.$store.commit('SET_CLOSE_FIELD_DRAWER')
        this.drawer = false
        this.$emit('close')
      },
      close2() {
        this.lockOption = false
        this.dialogVisible2 = false
      },
      // 打开新增自定义字段弹窗
      handleAdd() {
        this.title = '新增字段'
        this.ruleForm = {
          projectId: this.projectId,
          name: '',
          type: 6,
          status: 1,
          remark: '',
          option: [],
          reportType: this.reportType,
          reportId:this.queryParams.reportId,
        }
        this.dialogVisible = true
        
      },
      handleImport() {
        this.$refs.importFieldDialog.open(this.projectId)
      },
      handleEdit(row) {
        this.title = '编辑字段'
        this.dialogVisible = true
        this.ruleForm = { ...row }
      },
      // 选项管理
      handleEditOption(row) {
        this.ruleForm = { ...row }
        
        this.title = '选项管理'
        this.dialogVisible2 = true
        let params = {
          reportId:this.queryParams.reportId,
          fieldId: this.ruleForm.id,
          type: this.ruleForm.type,
        }
        if (this.ruleForm.type === 6) {
          this.optionDialogWidth = '600px'
        } else {
          this.optionDialogWidth = '500px'
        }
        this.optionLoading = true
        this.$api.listPatentFieldOption(params).then(response => {
          this.$set(this.ruleForm, 'option', response.data)
          this.optionLoading = false
        }).catch(error => {
          this.optionLoading = false
        })
      },
      // 选项卡管理其他删除
      handleDeleteOption(item, index) {
        if (!item.id) {
          this.ruleForm.option.splice(index, 1)
          this.lockOption = false
          this.valueChange = false
          return false
        }
        this.optionLoading = true
        this.$api.deleteOptionPatentField({ id: item.id, type: this.ruleForm.type,reportId:this.queryParams.reportId, }).then(response => {
          this.ruleForm.option.splice(index, 1)
          this.$message.success('操作成功')
          this.optionLoading = false
          this.lockOption = false
          this.valueChange = false
        }).catch(error => {
          this.optionLoading = false
        })
      },
      // 选项卡管理拖动
      handleDrop(draggingNode, dropNode, dropType, ev) {
        let order = dropNode.data.order
        switch (dropType) {
          case "before":
            draggingNode.data.parentId = dropNode.data.parentId
            draggingNode.data.order = order - 1
            break
          case "after":
            draggingNode.data.parentId = dropNode.data.parentId
            draggingNode.data.order = order + 1
            break
          case "inner":
            draggingNode.data.parentId = dropNode.data.id
            draggingNode.data.order = order + 1
            break
        }
        this.valueChange = true
        this.submitOption(draggingNode.data)
      },
      // 选项卡管理树形删除
      handleDeleteTreeNode(node, data) {
        const parent = node.parent
        const children = parent.data.children || parent.data
        if (!data.id) {
          children.splice(children.findIndex(d => d.$treeNodeId === data.$treeNodeId), 1)
          this.lockOption = false
          return false
        }
        this.optionLoading = true
        this.$api.deleteOptionPatentField({ id: data.id,type: this.ruleForm.type,reportId:this.queryParams.reportId,}).then(response => {
          children.splice(children.findIndex(d => d.id === data.id), 1)
          this.$message.success('操作成功')
          this.optionLoading = false
          this.lockOption = false
        }).catch(error => {
          this.optionLoading = false
        })
      },
      // 选项卡管理树形添加
      handleAddTreeNode(data) {
        if (this.lockOption) {
          return false
        }
        if (!data.children) {
          this.$set(data, 'children', [])
        }
        const lastIndex = data.children.length - 1
        data.children.push({
          name: '',
          parentId: data.id,
          order: lastIndex < 0 ? 0 : data.children[lastIndex].order + 1,
          children: [],
        })
        this.lockOption = true
        this.$forceUpdate()
      },
      //选项卡输入
      submitOption(item) {
        // if (!this.$permission('/workspace/common/customField/managementOptions')) {
        //   return false
        // }
        if (!item.name) {
          this.$message.error('请输入内容')
          return false
        }
        if (!this.valueChange) {
          this.lockOption = false
          return false
        }
        let data = {
          id: item.id,
          name: item.name,
          fieldId: this.ruleForm.id,
          type: this.ruleForm.type,
          parentId: item.parentId,
          reportId:this.queryParams.reportId,
          order: item.order,
        }
        this.optionLoading = true
        this.$api.updatePatentField(data).then(response => {
          this.$set(item, 'id', response.data)
          this.$message.success('操作成功')
          this.optionLoading = false
          this.lockOption = false
          this.valueChange = false
        }).catch(error => {
          this.optionLoading = false
        })
      },
      // 选项卡管理添加
      handleAddOption() {
        if (this.ruleForm.type === 6) {
          const lastIndex = this.ruleForm.option.length - 1
          this.ruleForm.option.push({
            name: '',
            parentId: 0,
            order: lastIndex < 0 ? 0 : this.ruleForm.option[lastIndex].order + 1,
            children: [],
          })
        } else {
          this.ruleForm.option.push({
            name: ''
          })
        }
        this.lockOption = true
      },
      getList() {
        this.queryParams.reportType = this.reportType
        this.loading = true
        this.$api.listPatentField(this.queryParams).then(response => {
          if (response.code == 200) {
            // response.data.option=[]
            this.tableData = response.data
            // this.total = response.pageColumn.total
            this.total = response.data.length
            this.loading = false
          }
        }).catch(error => {
          this.loading = false
        })
      },
      validationForm() {
        return new Promise((resolve, reject) => {
          switch (this.ruleForm.type) {
            case 0:
            case 1:
            case 2:
              resolve()
              break
            case 5:
              const optionName = this.ruleForm.option.map(item => item.name)
              if (optionName.length === 0) {
                reject('请添加选项')
              }
              if (!optionName.every(item => !!item)) {
                reject('选项不能为空')
              }
              if (this.$_.uniq(optionName).length !== optionName.length) {
                reject('选项名称重复')
              }
              resolve()
              break
            case 6:
              const flag = findTreeEq(this.ruleForm.option, 'name')
              if (flag) {
                reject(`${flag}`)
              }
              resolve()
              break
          }
        })
      },
      // 确定添加自定义字段
      submit() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.btnLoading = true
            if (this.ruleForm.id) {
              this.$api.editPatentField(this.ruleForm).then(response => {
                this.$message.success('编辑成功')
                this.btnLoading = false
                this.getList()
                this.cancel()
              }).catch(error => {
                this.btnLoading = false
              })
            } else {
              this.$api.addPatentField(this.ruleForm).then(response => {
                this.$message.success('新增成功')
                this.btnLoading = false
                this.getList()
                this.cancel()
              }).catch(error => {
                this.btnLoading = false
              })
            }
          }
        })
      },
      // 复制
      handleCopy(row) {
        this.$refs.copyFieldDialog.open(row)
      },
      handleDelete(row) {
        this.$confirm('确认删除本条数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.$api.deletePatentField({ id: row.id ,reportId:this.queryParams.reportId,}).then(response => {
            this.$message.success('删除成功')
            this.loading = false
            this.getList()
          }).catch(error => {
            this.loading = false
          })
        })
      }
    }
  }
</script>
  
<style lang="scss">
  .project-field {
    .pagination {
      text-align: center;
      margin: 20px 0;
    }
    .project-field-header-form {
      margin-left: 20px;
    }
    .project-field-main {
      background: #fff;
      padding: 5px 20px;
      margin-top: 20px;
    }
  }
  .project-field-option-box {
    height: 500px !important;
    background: #f5f5f5;
    border-radius: 5px;
    border: 1px solid #cecece;
    overflow: hidden;
    .option {
      margin-bottom: 10px;
      .t {
        cursor: pointer;
        width: 390px;
      }
      .o {
        cursor: pointer;
        width: 20px;
        float: right;
        text-align: right;
        margin-top: 5px;
      }
    }
    .el-footer {
      line-height: 50px;
      height: 50px !important;
      padding: 0 10px !important;
    }
    .tree-option {
      background: #f5f5f5 !important;
      .is-expanded, .is-focusable, {
        .el-tree-node__content:hover, .el-tree-node__content {
          background: #f5f5f5 !important;
        }
      }
      .el-tree-node__content {
        height: 40px !important;
      }
      .custom-tree-node {
        width: 100%;
        .r {
          width: 300px;
        }
        .o {
          cursor: pointer;
          width: 40px;
          float: right;
          text-align: right;
          margin-top: 5px;
          span:nth-child(1) {
            margin-right: 10px;
          }
        }
      }
    }
  }
</style>
  