<template>
  <div class="">
    <el-drawer class="custom-drawer-form" title="自定义栏位管理" size="1000px" :visible.sync="drawer" direction="rtl" :before-close="close" destroy-on-close append-to-body>
      <el-container class="project-field">
        <el-header>
          <el-form :inline="true" class="project-field-header-form">
            <el-form-item label="字段名称">
              <el-input v-model="searchOption.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">导入</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.find(item=>item.value == scope.row.status).label }}</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="description" 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>
                  <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 @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>
          
        </el-main>
        <el-footer class="pagination">
          <!-- <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-footer>
      </el-container>
    </el-drawer>

    <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" :append-to-body="true"  :close-on-click-modal="false" 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" :key="key" :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" :key="key" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="ruleForm.description" 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="false"
                :props='treeProps'
                @node-drop="handleDrop"
            >
              <div class="custom-tree-node" slot-scope="{ node, data }">
                <el-input v-model="data.name" :style="{'--backgroundColor':getBackground(node,data)}" placeholder="请输入内容" size="small" class="r" @focus="lockOption = true" @input="valueChange = true" @blur="submitOption(data)"></el-input>
                <div class="o">
                  <span class="el-icon-circle-plus" @click="handleAddTreeNode(data)" title="添加"></span>
                  <span class="el-icon-delete" style="color: black;font-weight: bold;" @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 "../dialog/ImportField";
// import CopyFieldDialog from "../dialog/CopyField";
import { findTreeEq } from "@/utils";

export default {
  components: {
    // ImportFieldDialog,
    // CopyFieldDialog
  },
  data() {
    return {
      treeProps:{
        children:'child'
      },
      optionDialogWidth: '500px',
      lockOption: false,
      valueChange: false,
      queryParams: {
        size: 10,
        current: 1,
      },
      //检索条件
      searchOption: {
        projectId: 0,
        name:'',
      },
      sort:[
        {
          "orderBy": "createTime",
          "orderType": 1
        }
      ],
      projectId: 0,
      typeObj: {
        0: '数字',
        1: '日期',
        2: '文本',
        // 3: '下拉框',
        4: '单选',
        5: '多选',
        6: '树',
      },
      pTypeObj: {
        1: '标引',
        2: '分类'
      },
      statusObj: [
        {
          label:'关闭',
          value:false
        },
        {
          label:"正常",
          value:true
        }
      ],
      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() {
  },
  methods: {
    //不同层级不同背景色
    getBackground(node,data){
      let color = {
        '1':'rgb(49,97,146)',
        '2':'rgb(64,158,255)',
        '3':'#67C23A',
      }
      if(color[node.level]){
        return color[node.level]
      }
      return '#E6A23C'
      
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
    cancel() {
      this.dialogVisible = false
    },
    open(id) {
      this.projectId = id
      this.drawer = true
      this.searchOption.projectId = this.projectId
      this.getList()
    },
    close() {
      this.drawer = false
      this.$emit('close',this.projectId)
    },
    close2() {
      this.lockOption = false
      this.dialogVisible2 = false
    },
    handleAdd() {
      this.title = '新增字段'
      this.ruleForm = {
        projectId: this.projectId,
        name: '',
        type: 6,
        status: true,
        description: '',
        option: []
      }
      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 = {
        customFieldId: this.ruleForm.id,
        // type: this.ruleForm.type
      }
      if (this.ruleForm.type === 6) {
        this.optionDialogWidth = '600px'
      } else {
        this.optionDialogWidth = '500px'
      }
      this.optionLoading = true
      this.$api.queryCustomOption(params).then(response => {
        this.$set(this.ruleForm, 'option', response.data.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.deleteCustomOption([{ id: item.id, customFieldId: this.ruleForm.id }]).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 child = parent.data.child || parent.data
      if (!data.id) {
        child.splice(child.findIndex(d => d.$treeNodeId === data.$treeNodeId), 1)
        this.lockOption = false
        return false
      }
      this.optionLoading = true
      this.$api.deleteCustomOption([{ id: data.id, customFieldId: this.ruleForm.id }]).then(response => {
        child.splice(child.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.child) {
        this.$set(data, 'child', [])
      }
      const lastIndex = data.child.length - 1
      data.child.push({
        name: '',
        parentId: data.id,
        order: lastIndex < 0 ? 0 : data.child[lastIndex].order + 1,
        child: [],
      })
      this.lockOption = true
      this.$forceUpdate()
    },
    submitOption(item) {
      if (!item.name) {
        this.$message.error('请输入内容')
        return false
      }
      if (!this.valueChange) {
        this.lockOption = false
        return false
      }
      let data = {
        id: item.id,
        name: item.name,
        customFieldId: this.ruleForm.id,
        type: this.ruleForm.type,
        parentId: item.parentId,
        order: item.order,
      }
      this.optionLoading = true
      if(!item.id){
        this.$api.addCustomOption(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
        })
      }else{
        this.$api.updateCustomOption(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,
          child: [],
        })
      } else {
        this.ruleForm.option.push({
          name: ''
        })
      }
      this.lockOption = true
    },
    getList() {
      this.loading = true
      var params = {
        ...this.queryParams,
        searchQuery:this.$commonJS.objectToString(this.searchOption),
        orderDTOList: this.sort,
      }
      this.$api.queryCustomField(params).then(response => {
        this.tableData = response.data.data
        this.total = response.data.total
        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.updateCustomField(this.ruleForm).then(response => {
              this.$message.success('编辑成功')
              this.btnLoading = false
              this.getList()
              this.cancel()
            }).catch(error => {
              this.btnLoading = false
            })
          } else {
            this.$api.addCustomField(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.handleDeletes([row.id])
    },
    handleDeletes(ids) {
      this.$confirm('确认删除该数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$api.deleteCustomField(ids).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;
        }
      }
      .el-input__inner{
        border-radius: 50px;
        background: var(--backgroundColor);
        color: white !important;
      }
    }
  }
}
</style>
