<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: 140px;">
                <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=" 90">
              <el-checkbox v-model="form['备选工序']"></el-checkbox>
            </el-form-item>
            <el-form-item label="加工开数:"  class="mab" prop="keyOrder" label-width=" 125">
              <el-input  v-model="form['开数']"  style="width: 100px;" 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: 100px;" 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" @click="add_gdgyenterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="yjdisplay" :before-close="()=> yjdisplay = false" style="width: 800px;margin: 8px auto" :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">
      </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"
          node-key="value"
          :default-expanded-keys="['标准工艺']"
      >
      </el-tree>
    </el-dialog>
  </div>
</template>

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

const form = reactive({})
const visible = ref(false)
const yjdisplay = ref(false)
const cjdisplay = 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 = (event,id1,id2,id3) => {
  if (id2==='印件编号' && event.key==='Tab') {
    const node = yjList.value.find(item => item.no ===form['yjno'])
    if (! node) {
      yjdisplay.value = true
    }
  }
  if (id2 === '车间名称' && event.key==='Tab') {
    cjdisplay.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 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['车间名称']});
  console.log(MachineList_jitai)
  gdzl_MachineList_address.value = MachineList_jitai.data;

  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 sbbhclick = () => {
  _capacityList();
}


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

};

// //默认弹窗关闭
// const add_gdgydialogFormVisible = ref(false)
// const add_gdgyformData = reactive({});
// //清空对象的属性值
// const gdgy_clearFormData = () => {
//   Object.keys(add_gdgyformData).forEach(key => {
//     add_gdgyformData[key] = '';
//   });
// };
// //新增工艺资料弹窗
// const addgdgy_onclick = () => {
//   if(_Gd_gdbh.value == null){
//     cgugdlist.value = false;
//     ElMessage({
//       type: 'warning',
//       message: '请选择具体的工单后，再操作此功能'
//     })
//   }else{
//     let gongxu = gytableData.value.map(item => {
//       return item['印件-工序']
//     })
//     addGongYiRef.value.open(_Gd_gdbh.value, gongxu)
//   }
// }
// //新增工艺资料确定
// const add_gdgyenterDialog = async () => {
//   console.log(add_gdgyformData)
//   // const formattedData = {
//   //   Yj_Gdbh: _Gd_gdbh.value,
//   //   yj_Yjno: add_gdgyformData['yjno'],
//   //   yj_Yjdh: add_gdgyformData['yjdh'],
//   // };
//   // 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>
