<template>
  <div>
    <!-- 新增工艺资料弹窗 -->
    <el-dialog v-model="visible" :before-close="()=> visible = false" style="width: 70%;margin: 8px auto" :title="'新增工艺资料'" destroy-on-close>
      <el-form>
        <div>
          <div style="display: flex; gap: 0px;">
            <el-form-item label="印件编号:"  class="mab" prop="keyOrder">
              <el-input v-model="form.yjno" id="印件编号" @keydown="add_gyzlent($event, '质量隐患', '印件编号', '工序编号')"  style="width: 100px;"/>
            </el-form-item>
            <el-form-item label="工序编号:" class="mab" prop="keyOrder" label-width=" 90">
              <el-input v-model="form['工序']"  id="工序编号" @keydown="add_gyzlent($event, '印件编号', '工序编号', '重点工序')"  style="width: 100px;"/>
            </el-form-item>
            <el-form-item label="重点工序:"  class="mab" prop="keyOrder" label-width=" 90">
              <el-select  v-model="form['重点工序']" id="重点工序"  @keydown="add_gyzlent($event, '', '重点工序', '开数')"  style="width: 130px;">
                <el-option value=""></el-option>
                <el-option value="重点工序">重点工序</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备选工序："  class="mab" prop="isBanciSelected" label-width=" 100">
              <el-checkbox v-model="form['备选工序']"></el-checkbox>
            </el-form-item>
            <el-form-item label="加工开数:"  class="mab" prop="keyOrder" label-width=" 100">
              <el-input  v-model="form['开数']"  style="width: 80px;" id="开数"  @keydown="add_gyzlent($event, '重点工序  ', '开数', '联数')" />
            </el-form-item>
            <el-form-item label="加工联数:"  class="mab" prop="keyOrder" label-width=" 80">
              <el-input  v-model="form['联数']"  style="width: 80px;" id="联数"  @keydown="add_gyzlent($event, '开数', '联数', '车间名称')" />
            </el-form-item>
          </div>
          <div style="display: flex; gap: 0px;">
            <el-form-item label="车间名称:"  class="mab" prop="keyOrder">
              <el-input v-model="form['车间名称']" id="车间名称" style="width: 140px;" @keydown="add_gyzlent($event, '联数', '车间名称', '工序名称')"/>
            </el-form-item>
            <el-form-item label="工艺名称:"  class="mab" prop="keyOrder" label-width=" 90">
              <el-input disabled v-model="form['工艺名称']"  style="width: 140px;"/>
            </el-form-item>
            <el-form-item label="工序名称:"  class="mab" prop="keyOrder" label-width=" 90">
              <el-input  v-model="form['工序名称']"  style="width: 300px;" id="工序名称"   @keydown="add_gyzlent($event, '车间名称', '工序名称', '设备编号')" />
            </el-form-item>
            <el-form-item label="计损色数"  class="mab" prop="keyOrder" label-width=" 80">
              <el-input disabled v-model="form['计损色数']" style="width: 90px;"/>
            </el-form-item>
          </div>
          <el-form-item label="设备编号:"  class="mab" prop="remark">
            <el-select v-model="form['设备编号']" multiple
                       id="设备编号"  @keydown="add_gyzlent($event, '工序名称', '设备编号', '工序损耗')"
                       style="flex: 1; height: auto;">
              <el-option
                  @keydown.tab.prevent="sbbhclick"
                  @click="sbbhclick"
                  v-for="(item, index) in gdzl_MachineList_address"
                  :key="index"
                  :label="item.split('-->')[0].trim()"
                  :value="item.split('-->')[0].trim()">
                {{ item }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工序损耗:"  class="mab" prop="keyOrder" >
            <el-input v-model="form['shdh']"  style="width: 10%;" id="工序损耗"  @keydown="add_gyzlent($event, '设备编号', '工序损耗', '装版工时')"/>
            <el-input disabled v-model="form['工序损耗名称']"  style="width: 88.7%;margin-left: 10px"/>
          </el-form-item>
          <div style="display: flex; gap: 0px;">
            <el-form-item label="损耗系数:"  class="mab" prop="keyOrder">
              <el-input disabled v-model="form['损耗系数']"  style="flex: 1;" />
            </el-form-item>
            <el-form-item label="难度系数"  class="mab" prop="keyOrder">
              <el-input disabled v-model="form['难度系数']"  style="flex: 1;" />
            </el-form-item>
            <el-form-item label="装版工时:"  class="mab" prop="keyOrder">
              <el-input  v-model="form['装版工时']"  style="flex: 1;" id="装版工时"  @keydown="add_gyzlent($event, '工序损耗', '装版工时', '排产小时产能')"/>
            </el-form-item>
            <el-form-item label="排产小时产能:"  class="mab" prop="keyOrder" label-width=" 120px">
              <el-input  v-model="form['小时产能']"  style="flex: 1;" id="排产小时产能"  @keydown="add_gyzlent($event, '装版工时', '排产小时产能', '备注')"/>
            </el-form-item>
            <el-form-item label="印刷方式"  class="mab" prop="keyOrder">
              <el-input disabled v-model="form['印刷方式']"  style="flex: 1;"/>
            </el-form-item>
            <el-form-item label="版距"  class="mab" prop="keyOrder">
              <el-input disabled v-model="form['版距']"  style="flex: 1;"/>
            </el-form-item>
          </div>
          <el-form-item label="工序备注:"  class="mab" prop="remark">
            <el-input  type="textarea" resize="none" v-model="form['备注']" rows="3" clearable   style="flex: 1;resize: none" id="备注"  @keydown="add_gyzlent($event, '排产小时产能', '备注', '质量要求')"/>
          </el-form-item>
          <el-form-item  label="质量要求:"  class="mab" prop="remark">
            <el-input  type="textarea" resize="none" v-model="form['质量要求']" rows="2" clearable   style="flex: 1;resize: both;" id="质量要求"  @keydown="add_gyzlent($event, '备注', '质量要求', '质量隐患')"/>
          </el-form-item>
          <el-form-item label="质量隐患:"  class="mab" prop="remark">
            <el-input  type="textarea" resize="none" v-model="form['质量隐患']" rows="2" clearable   style="flex: 1;" id="质量隐患"  @keydown="add_gyzlent($event, '质量要求', '质量隐患', '印件编号')"/>
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer" style="text-align: right;top: auto;">
          <el-button @click="add_gdgycloseDialog">取 消</el-button>
          <el-button type="primary" disabled @click="add_gdgyenterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="yjdisplay" :before-close="()=> yjdisplay = false" style="width: 800px;" :title="'可选列表'" destroy-on-close>
      <el-tree :data="yjList" :props="{children: 'children',label: 'name', value: 'no'}" @node-click="changeHandle"
               default-expand-all style="border: 1px solid #ececec; padding: 10px;height: 400px;overflow: auto;">
      </el-tree>
    </el-dialog>

    <el-dialog v-model="cjdisplay" :before-close="()=> cjdisplay = false" style="width: 800px;" :title="'车间选择'" destroy-on-close>
      <el-tree
          :data="cjList"
          :render-after-expand="false"
          @node-click="selectHandle"
          :props="{children: 'children',label: 'label', value: 'value'}"
          style="border: 1px solid #ececec; padding: 10px;height: 400px;overflow: auto;"
          node-key="value"
          :default-expanded-keys="['标准工艺']"
      >
      </el-tree>
    </el-dialog>

<!--    工序损耗列表-->
    <el-dialog v-model="gxshdisplay" :before-close="()=> gxshdisplay = false" style="width: 800px;" :title="'工序损耗'" destroy-on-close>
      <el-tree
          :data="gxshList"
          :render-after-expand="false"
          @node-click="gxshselectHandle"
          :props="{children: 'children',label: 'label', value: 'value'}"
          style="border: 1px solid #ececec; padding: 10px;height: 400px;overflow: auto;"
          node-key="value"
          :default-expanded-keys="form['车间名称']"
      >
      </el-tree>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {gdzl_MachineList, PrintDetailList, WastageList,getDepartName, capacityList,
} from "@/api/yunyin/yunying";
import { ElMessage } from 'element-plus'

const form = reactive({})
const visible = ref(false)
const yjdisplay = ref(false)
const cjdisplay = ref(false)
const gxshdisplay = ref(false)
const id = ref()

const gxList = ref([])
const yjList = ref()
const cjList = ref([
  {
    label: '标准工艺',
    value: '标准工艺',
    children: []
  }
])
const gdzl_MachineList_address = ref()

//新增工艺资料弹窗 键盘 input框跳转
const add_gyzlent = async (event,id1,id2,id3) => {
  if (id2==='印件编号' && event.key==='Tab' || id2 === '印件编号' && event.key=== 'Enter') {
    const node = yjList.value.find(item => item.no ===form['yjno'])
    if (! node) {
      yjdisplay.value = true
    }
    document.getElementById(id3).focus()
  }
  if (id2 === '车间名称' && event.key==='Tab' || id2 === '车间名称' && event.key=== 'Enter') {
    document.getElementById(id3).focus()
    cjdisplay.value = true
  }
  if (id2 === '工序损耗' &&  event.key==='Tab' || id2 === '工序损耗' && event.key=== 'Enter') {
    if(form['车间名称']){
      await getGxshList();
      if (gxshList.value[0].children.length > 1) {
        gxshdisplay.value = true
      }
    }
  }
  if (event.keyCode === 13 || event.keyCode === 40) { // Enter 或向下箭头
    if(id3!=''){
      document.getElementById(id3).focus()
    }
  } else if (event.keyCode === 38) { // 向上箭头
    if(id1!=''){
      document.getElementById(id1).focus()
    }
  }else if (event.keyCode === 8) { // 删除箭头
    if(id1!='' && document.getElementById(id2).value==''){
      document.getElementById(id1).focus()
    }
    // console.log(document.getElementById(id2).value)
  }else if (event.keyCode === 37) { // 向左箭头
    if(id1!='' && document.getElementById(id2).selectionStart==0){
      document.getElementById(id1).focus()
    }
  }else if (event.keyCode === 39) { // 向右箭头
    if(id3!='' && document.getElementById(id2).selectionStart == document.getElementById(id2).value.length){
      document.getElementById(id3).focus()
    }
  }
}

const open = async (gdbh, gxlist) => {
  id.value = gdbh
  const res = await PrintDetailList({workOrder: id.value})
  const chejian = await getDepartName()
  cjList.value = [
    {
      label: '标准工艺',
      value: '标准工艺',
      children: []
    }
  ]
  initChejian(chejian.data['标准工艺'])
  yjList.value = res.data
  gxList.value = gxlist
  visible.value = true
}

//工序损耗列表
const gxshList = ref([])
const getGxshList = async ()=>{
  const WastageList_data = await WastageList({search: form['车间名称']})
  gxshList.value = [{
    label: form['车间名称'],
    value: form['车间名称'],
    children: []
  }]
  if (WastageList_data.data.length === 0) return
  if (WastageList_data.data.length > 1) {
    gxshList.value[0].children = WastageList_data.data.map(item => {
      return { label: `${item.编号} - ${item.名称}`, label2: item.名称, UniqId: item.UniqId, value: item.编号 }
    })
  } else {
    form['shdh'] = WastageList_data.data[0].编号;
    form['工序损耗名称'] = WastageList_data.data[0].名称;
  }
}
//点击工序损耗列表数据
const gxshselectHandle = async (node)=>{
  form['shdh'] = node.value
  form['工序损耗名称'] = node.label2
  gxshdisplay.value = false
}
const selectHandle = async (node)=>{
  if (node.children && node.children.length> 0) return
  function findParentInTree(tree, targetValue) {
    for (let node of tree) {
      // 如果找到了目标值，返回当前节点作为上级
      if (node.value === targetValue) {
        return node;
      }
      // 如果当前节点有子节点，递归地在子节点中查找
      if (node.children && node.children.length > 0) {
        let parent = findParentInTree(node.children, targetValue);
        if (parent) return parent
      }
    }
    // 如果没有找到目标值或其上级，返回null
    return null;
  }
  const _node = findParentInTree(cjList.value, node.value)
  if(_node.parent){
    form['车间名称'] = _node.parent
  }else{
    form['车间名称'] = _node.label
  }
  form['工艺名称'] = _node.label
  form['设备编号'] = []
  //通过车间名称查询机台
  const MachineList_jitai = await gdzl_MachineList({address:form['车间名称']});
  gdzl_MachineList_address.value = MachineList_jitai.data;
  form['shdh'] = ''
  form['工序损耗名称'] = ''
  //通过车间名称查询工序损耗
  await getGxshList()
  cjdisplay.value = false
}

const initChejian = (data) => {
  Object.keys(data).map( (name, index)=>{
    const tmp = {
      label: name, value: name, children: []
    }
    data[name].map(item => {
      tmp.children.push({
        label: item, value: item,parent: name,
      })
    })
    cjList.value[0].children.push(tmp)
  })
}

const changeHandle = (v) => {
  const no = '0' + v.no
  let list = gxList.value.map(item => {
    const yj = item.split('-')[0]
    if (yj === no) return Number(item.split('-')[1])
  })
  form['yjno'] = v.no
  form['工序'] = (list.sort((a, b) => b-a)[0] + 1)
  yjdisplay.value = false
}
const _capacityListsbbh = ref(null)
const sbbhclick = () => {
  _capacityList();
}


const _capacityList = async () => {
  if(form['设备编号'] === ''){
    return false;
  }else{
    _capacityListsbbh.value = form['设备编号'].join(' ');
    const editProductedit_machine = await capacityList({machine:_capacityListsbbh.value});
    form['小时产能'] = editProductedit_machine.data;
  }

};

const sbbh = ref(null)

//新增工艺资料确定
const add_gdgyenterDialog = async () => {
  if(!form['yjno']){
    ElMessage({ type: 'warning', message: '印件编号不能为空' });return;
  }
  if(!form['工序']){
    ElMessage({ type: 'warning', message: '工序编号不能为空' });return;
  }
  if(!form['车间名称']){
    ElMessage({ type: 'warning', message: '车间名称不能为空' });return;
  }
  if(!form['设备编号']){
    ElMessage({ type: 'warning', message: '设备编号不能为空' });return;
  }
  console.log(form)
  sbbh.value = form['设备编号'].join(' ');
  const formattedData = {
    Gy0_gdbh: id.value,
    Gy0_yjno: form['yjno'] ? form['yjno'] : "",
    Gy0_gxh: form['工序'] ? form['工序'] : "",
    重点工序: form['重点工序'] ? form['重点工序'] : "",
    备选工序: form['备选工序'] ? form['备选工序'] : "",
    Gy0_ks: form['开数'] ? form['开数'] : "",
    Gy0_ls: form['联数'] ? form['联数'] : "",
    车间名称: form['车间名称'] ? form['车间名称'] : "",
    工艺名称: form['工艺名称'] ? form['工艺名称'] : "",
    工序名称: form['工序名称'] ? form['工序名称'] : "",
    计损色数: form['计损色数'] ? form['计损色数'] : "",
    设备编号: sbbh.value ? sbbh.value : "",
    工序损耗: form['shdh'] ? form['shdh'] : "",
    工序损耗名称: form['工序损耗名称'] ? form['工序损耗名称'] : "",
    装版工时: form['装版工时'] ? form['装版工时'] : "",
    小时产能: form['小时产能'] ? form['小时产能'] : "",
    备注: form['备注'] ? form['备注'] : "",
    质量要求: form['质量要求'] ? form['质量要求'] : "",
    质量隐患: form['质量隐患'] ? form['质量隐患'] : "",
  };
  console.log(formattedData)
  // const ProcessDetailAdd_add = await ProcessDetailAdd(formattedData);
  // console.log(ProcessDetailAdd_add)
  // add_gdgydialogFormVisible.value = false
}
// 新增工艺资料取消
const add_gdgycloseDialog = () => {
  visible.value = false
}

defineExpose({ open })
</script>

<style scoped>

</style>
