<!--
 * @Description : 重构物料分类 - 物料分组
 * @Author      : jinxin
 * @Date        : 2022-11-12 11:08:33
-->
<!-- 物料分类 -->
<template>
  <div class="main-container order-mc-bg">
    <div class="sale-container">
      <!-- 顶部按钮组 -->
      <toolBtn @actionhandel="actionhandel" :btnType="btnType"></toolBtn>
      <!-- 展示 -->
      <div class="sale-page-body material-group" ref="materialGroup">
        <div class="material-group-content">
          <!-- 分组 -->
          <div class="material-group-item" ref="materialGroupList">
            <div class="material-group-title">
              物料分组列表
            </div>
            <div class="material-group-tree">
              <el-tree ref="eltreecomponents" :data="data" :default-expand-all="true" :style="{maxHeight:heightNum - 84 + 'px'}" 
              :props="defaultProps" @node-click="handleNodeClick" node-key="id" :highlight-current="true"/>
              <!-- <el-tree ref="eltreecomponents" :data="data" :default-expand-all="true" :style="{maxHeight:heightNum - 84 + 'px'}" 
                :props="defaultProps" @node-click="handleNodeClick" node-key="id" :highlight-current="true">
                <template #default="{ node, data }">
                  <span class="custom-tree-node span-ellipsis">
                    <span :title="node.label">{{ node.label }}</span>
                  </span>
                </template>
              </el-tree> -->
            </div>
          </div>
          <!-- 分组内容 -->
          <div class="material-group-form">
            <el-form :model="form">
              <el-form-item label="分组名称" required>
                <el-input v-model.trim="form.groupName" />
              </el-form-item>
              <el-form-item label="分组编码" required>
                <el-input v-model.trim="form.groupCode" />
              </el-form-item>
              <el-form-item label="上级分类" required>
                <el-cascader
                    :popper-append-to-body="false"
                    :disabled="isEdit"
                    :options="mateOptions"
                    :props="{ 
                        expandTrigger: 'hover',
                        value:'id',
                        label:'name',
                        children:'chinds',
                        checkStrictly: true
                      }"
                    @change="changeMaterial"
                    @remove-tag="clearData"
                    clearable
                    ref="materialType"
                    v-model="form.superiorCode"
                  ></el-cascader>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { ElLoading } from 'element-plus'
export default {
  name: 'Materialclassification',
  data () {
    return {
      btnType: ['save', 'copy', 'audit', 's-p-t-g2', 'de-approval', 's-p-t-g4','s-p-t-g11','s-p-t-g1','refresh'],
      selectionItem: {}, //选中
      heightNum: 0,
      isEdit:true,
      windowHeight: 0,
      data:[],
      mateOptions: [],
      defaultProps:{
        children: 'chinds',
        label: 'nameNumber'
      },
      form:{
        groupName:'',
        groupCode:'',
        superiorCode:null,
      },
      requestUrl:'',
      editdata:[],
      parentId:null,
      parentData:[],
      editgetLevel:''
    }
  },
  computed: {
    ...mapState({
      orgId: state => (state && state.org && state.org.orgId ? state.org.orgId : null),
      orgIdArr: state => (state ? state.user.orgIdArr : null)
    })
  },
  created () {},
  mounted () {
    this.windowHeight = document.documentElement.clientHeight
    this.heightNum = this.windowHeight - 143
    this.$refs.materialGroup.style = 'height:' + this.heightNum + 'px'
    this.$refs.materialGroupList.style = 'height:' + (this.heightNum - 56) + 'px'
    // this.$refs.eltreecomponents.style = 'height' + (this.heightNum - 84) + 'px'
    // 获取数据
    this.$http.get('/MaterialGroup/GetDropDownAll').then((res)=>{
      if(res.status == 200){
        // 结构整理
        this.data = JSON.parse(JSON.stringify(this.newSubject(res.data)))
        this.mateOptions = JSON.parse(JSON.stringify(this.removeChildren(res.data)))
        // console.log(this.data)
      }
    })
  },
  methods: {
    // 初始化
    Init () {},
    // 顶部按钮
    actionhandel (type) {
      // 点击修改
      if (type === 'edit') {
        if(Object.keys(this.selectionItem).length != 0){
          if(this.parentData.data != undefined){
            this.parentId = this.parentData.id
            this.isEdit = false
          }else{
            this.$message.error('根级不允许修改')
            return 
          }
          // 编辑 url
          this.requestUrl = 'edit'
          // 回显
          // this.editgetLevel = this.$refs.materialType.getCheckedNodes()[0].level
          this.editgetLevel = 1
          this.form.groupName = this.selectionItem.name
          this.form.groupCode = this.selectionItem.number
          this.form.superiorCode = this.parentId
        }else{
          this.$message.error('请先选择需要修改的物料分组')
        }
      }
      // 点击删除
      if (type === 'delet') {
         if(Object.keys(this.selectionItem).length != 0){
          // 删除物料分组
          if(this.selectionItem.level != undefined && this.selectionItem.level != 1){
            this.$http.post('/MaterialGroup/Delete',{ids:[this.selectionItem.id]}).then(res => {
              if(res.status == 200){             
                if(res.data.length == 0){
                  this.$message.success('删除物料分组成功')
                  this.$refs.eltreecomponents.remove(this.selectionItem)
                  this.selectionItem = {}
                  this.form.groupName = ''
                  this.form.groupCode = ''
                  this.form.superiorCode = null
                }else{
                   this.$message.error(res.data[0].msg)
                }         
              }
            })
          }else{
            this.$message.error('该分组不允许删除')
          }
         }else{
            this.$message.error('请先选择需要删除的物料分组')
        }
      }
    },
    // 选择物料分类
    changeMaterial(val) {
      if (val) {
        this.form.superiorCode = val[val.length - 1]
      }
      // console.log('node --> tree ',this.$refs.materialType.getCheckedNodes())
      if(this.$refs.materialType.getCheckedNodes().length > 0){
        this.editgetLevel = this.$refs.materialType.getCheckedNodes()[0].level
      }
      
      this.$refs.materialType.togglePopperVisible()
      this.$refs.materialType.isDisabled = true
    },
    clearData() {
      //清空级联框对应操作
      this.form.superiorCode = ''
      this.$refs.materialType.togglePopperVisible()
      // this.getList()
    },
    // 去除空chinds
    removeChildren(arr) {
      if (arr.length) {
        for (let i in arr) {
          if (arr[i].chinds.length) {
            this.removeChildren(arr[i].chinds)
          } else {
            delete arr[i].chinds
          }
        }
      }
      return arr
    },
    // 点击条目
    handleNodeClick(event,node){
        // 获取父级node
        this.parentData = node.parent.data
        // 新增 url
        this.requestUrl = 'add'
        // 获取上级level
        this.templevel = event.level
        // 清空 名称、编码
        this.isEdit = true
        this.form.groupName = ''
        this.form.groupCode = ''
        // 回显上级分类编码 暂存该条目数据
        this.form.superiorCode = event.id
        this.selectionItem = event
    },
    // getTreeParams(event){
    //   console.log(event)
    // },
    // 新增、编辑 -- 提交
    onSubmit(){
        if(this.form.groupName && this.form.groupCode && this.form.superiorCode){
            if(this.requestUrl == 'add'){
              let adddata = {
                id:0,
                level:this.templevel + 1,
                name:this.form.groupName,
                number:this.form.groupCode,
                parentId:this.selectionItem.id,
                data:{
                  name:this.form.groupName,
                  number:this.form.groupCode
                }
              }
              this.loadingInstance = ElLoading.service({
                fullscreen: true
              })
              this.$http.post('/MaterialGroup/Commit',adddata).then(res => {
                if(res.status == 200){
                  // console.log('新增成功',res)
                  this.loadingInstance.close()
                  this.$message.success('新增分组成功')
                  adddata.id = res.data.id
                  this.$refs.eltreecomponents.append(adddata,this.selectionItem)
                  this.form.groupName = ''
                  this.form.groupCode = ''
                  this.form.superiorCode = ''
                  this.$http.get('/MaterialGroup/GetDropDownAll').then((res)=>{
                    if(res.status == 200){
                      // 重新获取上级分类编码数据
                      this.data = JSON.parse(JSON.stringify(this.newSubject(res.data)))
                      this.mateOptions = JSON.parse(JSON.stringify(this.removeChildren(res.data)))
                    }
                  })
                }else{
                  this.loadingInstance.close()
                }
              })
            }
            if(this.requestUrl == 'edit'){
              console.log('this.editgetLevel',this.editgetLevel)
              if(this.editgetLevel >= 3){
                this.$message.error('只能添加或者修改二,三级分组')
              }else{
                let updata = {
                  id:this.selectionItem.id,
                  level:this.templevel,
                  name:this.form.groupName,
                  number:this.form.groupCode,
                  parentId:this.form.superiorCode,
                  data:{
                    name:this.form.groupName,
                    number:this.form.groupCode
                  }
                }
                this.loadingInstance = ElLoading.service({
                  fullscreen: true
                })
                this.$http.post('/MaterialGroup/Commit',updata).then(res => {
                  if(res.status == 200){
                    // console.log('edit data',res.data)
                    this.loadingInstance.close()
                    this.$message.success('修改分组成功')
                    this.editUpdata(this.data,updata,this.selectionItem.id)
                    this.isEdit = true
                    this.form.groupName = ''
                    this.form.groupCode = ''
                    this.form.superiorCode = ''
                    this.$http.get('/MaterialGroup/GetDropDownAll').then((res)=>{
                      if(res.status == 200){
                        // 重新获取上级分类编码数据
                        this.data = JSON.parse(JSON.stringify(this.newSubject(res.data)))
                        this.mateOptions = JSON.parse(JSON.stringify(this.removeChildren(res.data)))
                      }
                    })
                  }else{
                    this.loadingInstance.close()
                  }
                })
              }
            }
        }else{
            this.$message.error('分组名称、分组编码、上级分类编码不能为空')
        }
    },
    // 递归
    editUpdata(data,update,id){
      data.forEach(el => {
        if(el.id == id){
          el.name = update.name
          el.number = update.number
          el.data.name = update.name
          el.data.number = update.number
          return 
        }else{
          if(el.chinds.length > 0){
            this.editUpdata(el.chinds,update,id)
          }
        }
      }); 
    },
    // 递归添加字段
    newSubject(data){
      return data.map(item => {
        item = Object.assign({},item)
        item.data = {
          groupName:item.name,
          groupCode:item.number,
          superiorCode:item.id
        }
        item.nameNumber= item.name + '(' + item.number + ')'
        if(item.chinds.length > 0){
          item.chinds = this.newSubject(item.chinds)
        }
        return item
      })
    }
  },
  watch: {}
}
</script>
<style lang="scss" scoped>
@import '@/assets/style/saleOrder/saleOrderCommon.scss';
@import '@/assets/style/saleOrder/orderList.scss';
@import '@/assets/style/saleOrder/common.scss';
.material-group-content{
  display: flex;
}
.material-group-item{
  width: 304px;
  margin: 16px;
  padding: 12px 8px;
  border: 1px solid #EBEEF5;
}
.material-group-title{
  font-size: 12px;
  font-weight: 600;
}
.material-group-form{
  width: 400px;
  margin: 16px;
}
.custom-tree-node{
  font-size: 12px;
}
.span-ellipsis {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: block;
}
::v-deep(.el-tree){
  background: none !important;
  box-sizing: content-box;
  overflow: auto;
  margin-right: 10px;
}

::v-deep(.el-tree .el-tree-node){
  margin-top: 7px!important;
  background: #F5F7FA!important;
  min-width: 100% !important;
  width: inherit!important;
  display: block !important;
  float: left;
}

::v-deep(.el-tree .el-tree-node .el-tree-node__content .expanded){
  color: #303133!important;
}
::v-deep(.el-tree .el-tree-node .el-tree-node__content .el-tree-node__label){
  font-size: 12px!important;
  color: #303133!important;
}
::v-deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content){
  background-color: #4178D5;
}
::v-deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content .expanded){
  color: #F5F7FA!important;
} 
::v-deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content .el-tree-node__label){
  color: #F5F7FA!important;
}
::v-deep(.el-input__suffix){
  top:-5px!important;
}
::v-deep(.el-select){
  width: 100%!important;
}
::v-deep(.el-input__suffix){
  top: 0!important;
}
::v-deep(.el-cascader-node.is-selectable.in-active-path){
  color: #409eff!important;
}
::v-deep(.el-tree-node.is-expanded>.el-tree-node__children){
  width: 276px!important;
}
</style>