<template>
  <el-card>
    <el-radio-group v-model="PartType" style="margin: 30px 20px;">
      <el-radio label="产品结构维护">产品结构维护</el-radio>
      <el-radio label="产品材料维护">产品材料维护</el-radio>
      <el-radio label="工艺参数维护">工艺参数维护</el-radio>
    </el-radio-group>
    <el-col>
      <el-button
        type="distribution"
        icon="el-icon-circle-plus-outline"
        size="small"
        @click="handleAdd('department_Form')">新增</el-button>
      <el-button type="warning" icon="el-icon-edit" size="small" plain @click="handleEdit()">编辑</el-button>
      <el-button type="danger" icon="el-icon-delete" size="small" plain @click="deleteTable()">删除</el-button>
    </el-col>
    <el-card class="box-card" style="width: 600px;height: 720px">
      <div slot="header" class="clearfix" style="position: relative;">
        <span v-if="PartType == '产品结构维护'" style="color: black;line-height: 30px;">产品结构维护</span>
        <span v-if="PartType == '产品材料维护'" style="color: darkgreen;line-height: 30px;">产品材料维护</span>
        <span v-if="PartType == '工艺参数维护'" style="color: cornflowerblue;line-height: 30px;">工艺参数维护</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="expandALL()">展开</el-button>
        <div class="tList">
          <div class="tItem">
            <div :style="{ backgroundColor: getTypeColor('产品结构') }"/>
            结构
          </div>
          <div class="tItem">
            <div :style="{ backgroundColor: getTypeColor('产品材料') }"/>
            材料
          </div>
          <div class="tItem">
            <div :style="{ backgroundColor: getTypeColor('工艺参数') }"/>
            工艺参数
          </div>
        </div>
      </div>
      <div style="height: 650px;overflow:auto;">
        <el-tree
          ref="treeForm"
          :data="productTreeData"
          :props="defaultProps"
          :default-expanded-keys="expandedList"
          :allow-drop="allowDrop"
          draggable
          show-checkbox
          node-key="id"
          check-strictly
          @node-drag-end="sortDrag"
          @node-expand="nodeExpand"
          @node-collapse="nodeCollapse"
          @check-change="handleClick">
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span :style="{ color: getTypeColor(data.type) }">{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
    </el-card>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      PartType: '产品结构维护',
      productTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      expandedList: [],
      productId: 0,
      productType: '',
      productName: '',
      expandAll: true,
      nodeName: ''
    }
  },
  computed: {

  },
  created() {
    this.getTreeData()
  },
  methods: {
    handleAdd() {
      this.$prompt('请输入分支名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: ''
      }).then(({ value }) => {
        var param = []
        param.push(['父节点', this.productId])
        param.push(['节点名称', value])
        param.push(['节点类型', this.PartType.substring(0, 4)])
        var Data = this.CreateData('11', 'WEB_基本表_产品结构_新增', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result == 1) {
            this.$message.success('新增成功!')
            this.getTreeData()
          } else {
            this.$message.error('信息增加失败')
          }
        })
      })
    },
    getTreeData() {
      var param = []
      var Data = this.CreateData('11', 'WEB_基本表_产品结构_查询', param)
      this.ExecDatabase(Data).then(response => {
        const data = response.data
        this.productTreeData = this.tree(data, 0)
      })
    },
    deleteTable() {
      if (this.productId) {
        if (this.productType + '维护' != this.PartType) {
          this.$message.warning(`请选择${this.productType + '维护'}`)
          return
        }
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var param = []
          param[0] = ['子节点', this.productId]
          var Data = this.CreateData('11', 'WEB_基本表_产品结构_删除', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result == 1) {
              this.getTreeData()
              this.productId = 0
              this.$message.success('删除成功')
            } else {
              this.$message.warning(response.data[0].msg)
            }
          })
        })
      } else {
        this.$message.warning(`请选择产品`)
      }
    },
    handleEdit() {
      if (!this.productId) {
        this.$message.warning('请先勾选产品!')
        return
      }
      if (this.productType + '维护' != this.PartType) {
        this.$message.warning(`请选择${this.productType + '维护'}`)
        return
      }
      this.$prompt('请输入产品名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: this.productName
      }).then(({ value }) => {
        var param = []
        param.push(['子节点', this.productId])
        param.push(['节点名称', value])
        var Data = this.CreateData('11', 'WEB_基本表_产品结构_修改', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result == 1) {
            this.$message.success('修改成功!')
            this.getTreeData()
          } else {
            this.$message.warning(response.data[0].msg)
          }
        })
      })
    },
    expandALL() {
      this.expandAll = !this.expandAll
      for (let i = 0; i < this.$refs.treeForm.store._getAllNodes().length; i++) {
        this.$refs.treeForm.store._getAllNodes()[i].expanded = this.expandAll
      }
    },
    getTypeColor(type) {
      switch (type) {
        case '产品结构':
          return 'black'
        case '产品材料':
          return 'darkgreen'
        case '工艺参数':
          return 'cornflowerblue'
        default:
          return 'black'
      }
    },
    getBigTypeColor(type) {
      switch (type) {
        case '产品结构维护':
          return 'black'
        case '产品材料维护':
          return 'darkgreen'
        case '工艺参数维护':
          return 'cornflowerblue'
        default:
          return 'black'
      }
    },
    tree(data, pid) {
      const result = []
      let temp
      for (let i = 0; i < data.length; i++) {
        if (data[i].父节点 === pid) {
          const obj = { label: data[i].节点名称, id: data[i].子节点, type: data[i].节点类型 }
          temp = this.tree(data, data[i].子节点)
          if (temp.length > 0) {
            obj.children = temp
          }
          result.push(obj)
        }
      }
      return result
    },
    allowDrop(draggingNode, dropNode, type) {
      if (type === 'inner') {
        return false
      } else {
        if (draggingNode.parent.id !== dropNode.parent.id) {
          return false
        } else {
          return true
        }
      }
    },
    // 节点拖拽排序
    sortDrag(Node, targetNode, type, event) {
      // let PId = 0
      // if (targetNode.parent.key) {
      //   PId = targetNode.parent.key
      // }
      // var param = []
      // param[0] = ['原始位置', Node.data.id]
      // param[1] = ['最终位置', targetNode.data.id]
      // param[2] = ['父节点', PId]
      // var Data = this.CreateData('12', '产品关系_变更节点排序', param)
      // this.ExecDatabase(Data).then(response => {
      //   if (response.data[0].result === '1') {
      //     this.$message.success('更新成功')
      //     this.getTreeData()
      //   } else {
      //     this.$message.error('更新失败')
      //   }
      // })
    },
    nodeExpand(data) {
      // console.log(this.departmentData, 55555)
      this.expandedList.push(data.id) // 在节点展开是添加到默认展开数组
    },
    nodeCollapse(data) {
      this.expandedList.splice(this.expandedList.indexOf(data.id), 1) // 收起时删除数组里对应选项
    },
    handleClick(data, checked) {
      if (!this.$refs.treeForm) return

      if (checked) {
        this.$refs.treeForm.setCheckedKeys([data.id])
        setTimeout(() => {
          this.productId = data.id
          this.productName = data.label || '' // 防止undefined
          this.productType = data.type || ''
          console.log('当前选中：', this.productId, this.productName)
        }, 50)
      } else {
        // this.$refs.treeForm.setCheckedKeys()
        this.productId = 0
        this.productName = ''
        this.productType = ''
        console.log('当前选中：', this.productId, this.productName)
      }
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-card__body {
  padding: 0px !important;
}

.tList {
  text-align: right;
  display: flex;
  position: absolute;
  right: 0px;

  .tItem {
    display: flex;
    margin-left: 10px;
    line-height: 15px;
    font-size: 13px;

    div {
      width: 15px;
      height: 15px;
      margin-right: 5px;
    }
  }
}
</style>
