<template>
  <div class="process-table">
    <el-button class="process-table-addprocess" type="primary" @click="addProcess">{{ $t('module.art.processList.addProcess') }}</el-button>
    <el-collapse class="process-table-main" @change="handleChange">
      <vuedraggable v-model="dataList" group="process">
        <el-collapse-item v-for="(item, index) in dataList" :key="index" :name="index">
          <template slot="title">
            <div class="process-table-main-title">
              <span>{{ processObj[item.workSequenceId].name }}</span>
              <div class="process-table-main-title-delbtn">
                <el-button v-if="showAddList.indexOf(index) >= 0" type="primary" size="mini" icon="el-icon-plus" @click="addProcessItem($event, index)">{{ 'btn.add' | i18nFilter }}</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="delProcess($event, index)">{{ 'btn.delete' | i18nFilter }}</el-button>
              </div>
            </div>
          </template>
          <el-row v-for="(i, idx) in item.processFlowEquipmentParams" :key="'item' + index + idx" class="process-table-main-item" :gutter="20">
            <el-col :span="4" class="process-table-main-item-item">
              <el-button icon="el-icon-edit" @click="choiceEquipment(index, idx, i.equipmentId, item.workSequenceId)">
                {{ i.equipmentId ? equipmentObj[i.equipmentId] : $t('module.art.eqName') }}
              </el-button>
            </el-col>
            <!-- <el-col :span="4" class="process-table-main-item-item">
              <el-button v-if="!processPortObj[item.workSequenceId]" icon="el-icon-edit" @click="choiceRecipe(index, idx, i.equipmentRecipeId)">
                {{ i.equipmentRecipeId ? equipmentRecipeObj[i.equipmentRecipeId] : $t('module.art.recipeName') }}
              </el-button>
            </el-col> -->
            <!-- <el-col :span="4" class="process-table-main-item-item">
              <el-button v-if="!processPortObj[item.workSequenceId]" icon="el-icon-edit" @click="choiceArtType(index, idx, i.nodeType)">
                {{ i.nodeType ? nodeTypesObj[i.nodeType] : $t('module.art.artType') }}
              </el-button>
            </el-col> -->
            <el-col :span="4" class="process-table-main-item-item">
              <el-input v-model="i.description" :placeholder="$t('module.art.processList.description')" @change="changeDescription(index, idx)" />
            </el-col>
            <el-col :span="4" class="process-table-main-item-item">
              <el-input v-model="i.remark" :placeholder="$t('module.art.remark')" @change="changeRemark(index, idx)" />
            </el-col>
            <el-col :span="3" class="process-table-main-item-item">
              <el-button type="danger" icon="el-icon-delete" @click="delProcessItem(index, idx)">
                {{ 'btn.delete' | i18nFilter }}
              </el-button>
            </el-col>
          </el-row>
        </el-collapse-item>
      </vuedraggable>
    </el-collapse>
    <!-- 添加工序 -->
    <process-table-add ref="processtableadd" :process-list="processList" @handleProcess="handleProcess" />
    <process-table-select ref="processtableselect" @handleSelect="handleSelect" />
  </div>
</template>
<script>
import Vue from 'vue'
import processTableSelect from './process-table-select.vue'
import processTableAdd from './process-table-add.vue'
import vuedraggable from 'vuedraggable'
import {
  // listAllEquipmentRecipe,
  addProcessFlows,
  listProcessFlowNode,
  listProcess
} from '@/api/art-manage/art.js'
import { listEquipment } from '@/api/material-manage/material'

export default {
  name: 'ProcessTable',
  components: {
    vuedraggable,
    processTableAdd,
    processTableSelect
  },
  props: {
    processFlowId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      dataList: [],
      processList: [],
      processObj: {},
      processPortObj: {},
      equipmentRecipeList: [],
      // equipmentRecipeObj: [],
      equipmentList: [],
      equipmentObj: {},
      showAddList: [],
      // 1、上片设备，2、加工设备，3、下片设备
      nodeTypes: [
        {
          id: 1,
          name: '上片设备'
        },
        {
          id: 2,
          name: '加工设备'
        },
        {
          id: 3,
          name: '下片设备'
        }
      ],
      nodeTypesObj: {
        1: '上片设备',
        2: '加工设备',
        3: '下片设备'
      }
    }
  },
  created() {
    this.init()
    this.$bus.on('on-process-save', this.save)
  },
  beforeDestroy() {
    this.$bus.off('on-process-save', this.save)
  },
  mounted() {},
  methods: {
    // 初始化
    async init() {
      // 获取工序列表
      const allProcessRes = await listProcess({})
      this.processList = allProcessRes.data
      allProcessRes.data.map(item => {
        this.processObj[item.id] = item
        if (item.type === 1) {
          this.processPortObj[item.id] = item.name
        }
      })
      console.log(this.processList)
      console.log(this.processObj)
      // 获取配方列表
      // const allRecipeRes = await listAllEquipmentRecipe()
      // this.equipmentRecipeList = allRecipeRes.data
      // allRecipeRes.data.map(item => {
      //   this.equipmentRecipeObj[item.id] = item.name
      // })
      // console.log(this.equipmentRecipeList)
      // 获取设备列表
      const allEquipmentRes = await listEquipment()
      this.equipmentList = allEquipmentRes.data
      allEquipmentRes.data.map(item => {
        this.equipmentObj[item.id] = item.name
      })
      console.log(this.equipmentList)
      // 获取列表
      const allNodeRes = await listProcessFlowNode({
        processFlowId: this.processFlowId
      })
      console.log(allNodeRes)
      this.dataList = allNodeRes.data.map(item => {
        delete item.id
        item.processFlowEquipmentParams.map(i => {
          delete i.id
          i.workSequenceId = item.workSequenceId
          i.processFlowId = item.processFlowId
          return i
        })
        return item
      })
      console.log(this.dataList)
    },
    // 添加工序
    addProcess() {
      this.$refs.processtableadd.init()
    },
    handleProcess(process) {
      // for (let i = 0; i < this.dataList.length; i++) {
      //   if (this.dataList[i].workSequenceId === process) {
      //     this.$message.warning(this.$t('module.art.NotSameProcess'))
      //     return
      //   }
      // }
      this.dataList.push({
        processFlowId: this.processFlowId,
        workSequenceId: process,
        processFlowEquipmentParams: [
          {
            equipmentId: '',
            equipmentRecipeId: '',
            nodeType: '',
            processFlowId: this.processFlowId,
            workSequenceId: process,
            description: '',
            remark: ''
          }
        ]
      })
      this.$refs.processtableadd.closeDialog()
    },
    // 添加工序下设备
    addProcessItem(e, index) {
      this.dataList[index].processFlowEquipmentParams.push({
        equipmentId: '',
        equipmentRecipeId: '',
        nodeType: '',
        processFlowId: this.processFlowId,
        workSequenceId: this.dataList[index].workSequenceId,
        description: this.dataList[index].processFlowEquipmentParams[0].description ? this.dataList[index].processFlowEquipmentParams[0].description : '',
        remark: this.dataList[index].processFlowEquipmentParams[0].remark ? this.dataList[index].processFlowEquipmentParams[0].remark : ''
      })
      e.stopPropagation()
    },
    // 删除工序
    delProcess(e, index) {
      this.$confirm(`${this.$t('deleteTip.header')}${this.processObj[this.dataList[index].workSequenceId].name}${this.$t('deleteTip.footer')}`, this.$t('deleteTip.tip'), {
        confirmButtonText: this.$t('deleteTip.confirm'),
        cancelButtonText: this.$t('deleteTip.cancel'),
        type: 'warning'
      }).then(() => {
        this.dataList.splice(index, 1)
      }).catch(() => {})
      e.stopPropagation()
    },
    // 删除工序下设备
    delProcessItem(first, sec) {
      this.$confirm(`${this.$t('deleteTip.header')}${this.dataList[first].processFlowEquipmentParams[sec].equipmentId ? this.equipmentObj[this.dataList[first].processFlowEquipmentParams[sec].equipmentId] : this.$t('deleteTip.this')}${this.$t('deleteTip.footer')}`, this.$t('deleteTip.tip'), {
        confirmButtonText: this.$t('deleteTip.confirm'),
        cancelButtonText: this.$t('deleteTip.cancel'),
        type: 'warning'
      }).then(() => {
        this.dataList[first].processFlowEquipmentParams.splice(sec, 1)
      }).catch(() => {})
    },
    // 折叠菜单状态改变事件
    handleChange(list) {
      this.showAddList = list
    },
    // 选择设备
    choiceEquipment(first, sec, id, processId) {
      this.$refs.processtableselect.init('equipmentId', first, sec, id, this.processObj[processId].equipments)
    },
    // 选择配方
    // choiceRecipe(first, sec, id) {
    //   if (this.dataList[first].processFlowEquipmentParams[sec]?.equipmentId) {
    //     this.$refs.processtableselect.init('equipmentRecipeId', first, sec, id, this.equipmentRecipeList.filter(f => f.equipmentId === this.dataList[first].processFlowEquipmentParams[sec].equipmentId))
    //   } else {
    //     this.$message.error(this.$t('module.art.choiceEqError'))
    //   }
    // },
    // 选择工艺类型
    choiceArtType(first, sec, id) {
      if (this.dataList[first].processFlowEquipmentParams[sec].equipmentId) {
        this.$refs.processtableselect.init('nodeType', first, sec, id, this.nodeTypes)
      } else {
        this.$message.error(this.$t('module.art.choiceEqError'))
      }
    },
    // 选择设备配方工艺类型
    handleSelect(type, first, sec, val) {
      let change = true
      if (type === 'equipmentId') {
        this.dataList[first].processFlowEquipmentParams.map((item, index) => {
          if (val === item.equipmentId && index !== sec) {
            change = false
          }
        })
      }
      if (change) {
        Vue.set(this.dataList[first].processFlowEquipmentParams[sec], type, val)
        this.$refs.processtableselect.closed()
      } else {
        this.$message.error(this.$t('module.art.sameEqError'))
      }
      console.log(this.dataList)
    },
    // 描述变更
    changeDescription(first, sec) {
      if (sec === 0 && this.dataList[first].processFlowEquipmentParams.length > 1) {
        this.$confirm(`${this.$t('module.art.changeTipHeaderDes')}${this.processObj[this.dataList[first].workSequenceId].name}${this.$t('module.art.changeTipFooter')}`, this.$t('deleteTip.tip'), {
          confirmButtonText: this.$t('deleteTip.confirm'),
          cancelButtonText: this.$t('deleteTip.cancel'),
          type: 'info'
        }).then(() => {
          this.dataList[first].processFlowEquipmentParams.map(item => {
            Vue.set(item, 'description', this.dataList[first].processFlowEquipmentParams[0].description)
          })
        }).catch(() => {})
      }
    },
    // 备注变更
    changeRemark(first, sec) {
      if (sec === 0 && this.dataList[first].processFlowEquipmentParams.length > 1) {
        this.$confirm(`${this.$t('module.art.changeTipHeaderRemark')}${this.processObj[this.dataList[first].workSequenceId].name}${this.$t('module.art.changeTipFooter')}`, this.$t('deleteTip.tip'), {
          confirmButtonText: this.$t('deleteTip.confirm'),
          cancelButtonText: this.$t('deleteTip.cancel'),
          type: 'info'
        }).then(() => {
          this.dataList[first].processFlowEquipmentParams.map(item => {
            Vue.set(item, 'remark', this.dataList[first].processFlowEquipmentParams[0].remark)
          })
        }).catch(() => {})
      }
    },
    // 保存
    save() {
      const vm = this
      let hasNull = false
      this.dataList.map(item => {
        if (item.processFlowEquipmentParams.length === 0) {
          hasNull = true
        }
        if (this.processPortObj[item.workSequenceId]) {
          item.processFlowEquipmentParams.map(i => {
            if (!i.equipmentId) {
              hasNull = true
            }
          })
        }
        // else {
        //   item.processFlowEquipmentParams.map(i => {
        //     if (!i.equipmentId || !i.equipmentRecipeId) {
        //       hasNull = true
        //     }
        //   })
        // }
      })
      // console.log(JSON.stringify(vm.dataList))
      // if (vm.dataList.length === 0) {
      //   vm.$alert(this.$t('module.art.nodeNull'), this.$t('module.art.tip'), {
      //     confirmButtonText: this.$t('module.art.confirm'),
      //     callback: action => {
      //       console.log('保存')
      //       vm.handleSave(vm)
      //     }
      //   })
      // } else
      if (hasNull) {
        vm.$message.error(this.$t('module.art.hasNull'))
      } else {
        vm.handleSave(vm)
      }
    },
    handleSave(vm) {
      const processFlowParamObj = {
        processFlowSequenceEquipmentParams: vm.dataList
      }
      console.log(JSON.stringify(processFlowParamObj))
      addProcessFlows(processFlowParamObj).then(res => {
        this.$emit('on-save-success')
      })
    }
  }
}
</script>
<style lang="scss">
  .process-table{
    .process-table-addprocess{
      margin-left: 20px;
      margin-top: 20px;
    }
    .process-table-main{
      width: calc(100% - 40px);
      margin: 20px;
      border: 1px solid #e6ebf5;
      border-radius: 5px;
      min-width: 1000px;
      .process-table-main-title{
        padding: 0 20px;
        width: 100%;
        position: relative;
        .process-table-main-title-delbtn{
          position: absolute;
          top: 50%;
          right: 20px;
          transform: translateY(-50%);
        }
      }
      .process-table-main-item{
        width: calc(100% - 40px);
        margin: 0 10px !important;
        line-height: 48px;
      }
    }
  }
</style>
