<template>
  <!-- 添加或修改项目信息对话框 -->
  <el-dialog
    title="废品回用"
    v-model="visible"
    width="900px"
    append-to-body
    draggable
  >
    <div class="form-container">
      <el-form
        ref="wasteRecyclingRef"
        class="master-container"
        v-loading="loading"
        :model="form"
        label-width="100px"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="15">
            <el-form-item label="产品描述" label-width="90px">
              <el-input
                v-model.trim="detailsRow.productDescription"
                :disabled="true"
                style="width: 270px"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item
              label="首序工段"
              label-width="90px"
              prop="requisitionDepartmentId"
            >
              <el-select-v2
                v-model="form.requisitionDepartmentId"
                :options="deptList"
                placeholder="请选择首序工段"
                style="width: 165px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="参考批号" label-width="90px">
              <el-input v-model.trim="detailsRow.lotCode" :disabled="true">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="生成批数" label-width="90px" prop="lotNumber">
              <el-input-number
                v-model="form.lotNumber"
                style="width: 200px"
                controls-position="right"
                :min="0"
                :precision="0"
                @input="(val) => {handleUpdateLotNumber(val)}"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="单批量"
              label-width="90px"
              prop="productionQuantity"
            >
              <el-input-number
                v-model="form.productionQuantity"
                controls-position="right"
                style="width: 165px"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="新生成批号" label-width="90px">
              <el-input
                type="textarea"
                v-model.trim="form.newLots"
                :disabled="true"
                style="width: 710px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div>
        <span style="font-size: 18px; font-weight: 700; line-height: 25px"
          >工序</span
        >
        <div style="float: inline-end">
          <span
            style="
              color: rgba(0, 203, 117, 1);
              font-size: 16px;
              font-weight: 400;
              line-height: 23px;
              cursor: pointer;
              display: inline-block;
            "
            @click="handleAddPreProcess"
            >+导入历史工艺</span
          >
          <span
            style="
              margin-left: 30px;
              color: rgba(232, 122, 0, 1);
              font-size: 16px;
              font-weight: 400;
              line-height: 23px;
              cursor: pointer;
              display: inline-block;
            "
            @click="handleAddProcess"
            >+从工序库添加</span
          >
        </div>
      </div>
      <div id="insideProcessForm">
        <el-table
          class="elTable"
          ref="dialogTable"
          :data="processList"
          :row-key="getRowKey"
          size="small"
          v-loading="loading"
          border
          height="360px"
          header-row-class-name="list-header-row"
          row-class-name="currentRow"
        >
          <el-table-column label="移动" width="50" align="center">
            <div class="move-handle">
              <el-icon>
                <Rank />
              </el-icon>
            </div>
          </el-table-column>
          <el-table-column label="工序编码" align="center" prop="processCode" />
          <el-table-column
            label="工序简称"
            align="center"
            prop="processAlias"
          />
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="140px"
          >
            <template #default="scope">
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDeleteProcess(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="handleSave"
        >保存</el-button
      >
      <el-button icon="Close" @click="handleCancel">取 消</el-button>
    </template>
    <!-- 工序库选择工序 -->
    <processChoice
      ref="processChoiceRef"
      :multiple-selected="handleProcessSelected"
    />
  </el-dialog>
</template>
<script setup>
import { getLastLot, getProcess, addWasteRecycling } from "@/api/business/lot";
import { listDeptProcess } from "@/api/business/deptProcess";
import { getDeptList } from "@/api/system/dept";
import processChoice from "./DialogProcessChoice";
import { onMounted, ref } from "vue";
import Sortable from "sortablejs";
const { proxy } = getCurrentInstance();
const emit = defineEmits(["handleSaveSuccess"]);
/**工艺版本变更变量 */
const loading = ref(false);
let currentUID = ref(0);
const processLoading = ref(false);
const visible = ref(false);
const detailsRow = ref({});
const deptList = ref([]);
const processList = ref([]);
const referenceLotInfo = ref({});
//校验生成批数
const validateLotNumber = (rule, value, callback) => {
  const min = 0;
  if (value % 1 !== 0) {
    // 检查是否无法解析为整数
    callback(new Error(`当前生成批数不能是小数`));
  } else if (value <= min) {
    callback(new Error("当前生成批数应大于0"));
  } else {
    callback();
  }
};
//校验单批量
const validateproductionQuantity = (rule, value, callback) => {
  const min = 0;
  if (value % 1 !== 0) {
    callback(new Error(`当前单批量不能是小数`));
  } else if (value <= min) {
    callback(new Error("当前单批量应大于0"));
  } else {
    callback();
  }
};
/**查询对象 */
const data = reactive({
  form: {},
  queryParams: {
    referenceLot: null,
    lotNumber: null,
    productionQuantity: null,
  },
  rules: {
    lotNumber: [
      { required: true, message: "生成批数不能为空", trigger: "blur" },
      { validator: validateLotNumber, trigger: "blur" },
    ],
    productionQuantity: [
      { required: true, message: "单批量不能为空", trigger: "blur" },
      { validator: validateproductionQuantity, trigger: "blur" },
    ],
    requisitionDepartmentId: [
      { required: true, message: "领料部门不能为空", trigger: "blur" },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
const open = (data) => {
  reset();
  detailsRow.value = proxy.deepClone(data[0]);
  getDeptList({ type: 0, isWorkSection: 1 }).then((res) => {
    deptList.value = res.data;
  });
  processList.value = [];
  console.log(detailsRow.value);
  visible.value = true;
};

/** 表单重置 */
const reset = () => {
  form.value = {
    id: null,
    referenceLot: null,
    lotNumber: null,
    productionQuantity: null,
    requisitionDepartmentId: null,
  };
  proxy.resetForm("wasteRecyclingRef");
};
/**生成批数变化*/
function handleUpdateLotNumber(val) {
  form.value.lotNumber = val
  if (form.value.lotNumber > 0) {
    //查询该计划单最后一个批数(排除分批的批次)
    getLastLot({
      productionPlanDetailId: detailsRow.value.productionPlanDetailId,
    }).then((res) => {
      if (res.code == 200) {
        var lastLot = res.data.lotCode;
        var partOne = lastLot.substring(0, 8);
        var partTwo = lastLot.substring(8, 11);
        //获取生成批号
        var prefix = partTwo.replace(/[0-9]/g, "");
        var number = parseInt(partTwo.match(/[0-9]+/)[0]);
        var numbers = [];
        let currentNumber = number;
        for (let i = 0; i < form.value.lotNumber; i++) {
          var newNumber = currentNumber + (i + 1);
          numbers.push(
            prefix +
              newNumber
                .toString()
                .padStart(partTwo.match(/[0-9]+/)[0].length, "0")
          );
          if(newNumber  == 1000) {
              proxy.$modal.msgError("生成批数最多是" + i+",请重新输入");
              form.value.lotNumber = null
              form.value.newLots = null
              return
          }
        }
        var lots = [];
        for (let i = 0; i < numbers.length; i++) {
          lots.push(partOne + numbers[i] + "0");
        }
        form.value.newLots = lots;
      }
    });
  }
}

/**工序删除 */
function handleDeleteProcess(row) {
  processList.value.splice(processList.value.indexOf(row), 1);
}
/** 提交按钮 */
const handleSave = () => {
  proxy.$refs["wasteRecyclingRef"].validate((valid) => {
    if (valid) {
      var wasteRecyclingInfo = {};
      for (var i = 0; i < processList.value.length; i++) {
        processList.value[i].processStepNumber = 1000 + i * 10;
      }
      wasteRecyclingInfo.lotCodeList = form.value.newLots;
      wasteRecyclingInfo.productionPlanDetailId =
        detailsRow.value.productionPlanDetailId;
      wasteRecyclingInfo.technologicalProcessId =
        detailsRow.value.technologicalProcessId;
      wasteRecyclingInfo.technologyVersion = detailsRow.value.technologyVersion;
      wasteRecyclingInfo.productId = detailsRow.value.product.id;
      wasteRecyclingInfo.productionQuantity = form.value.productionQuantity;
      wasteRecyclingInfo.productDescription =
        detailsRow.value.productDescription;
      wasteRecyclingInfo.processList = processList.value;
      wasteRecyclingInfo.lotCode = detailsRow.value.lotCode;
      wasteRecyclingInfo.requisitionDepartmentId =
        form.value.requisitionDepartmentId;
      for (let i = 0; i < deptList.value.length; i++) {
        if (form.value.requisitionDepartmentId == deptList.value[i].value) {
          wasteRecyclingInfo.requisitionDepartmentName =
            deptList.value[i].label;
        }
      }
      console.log(wasteRecyclingInfo);
      //判断工序除了processId = 1 和等于2的工序，当前领料部门是否能干第一道序
      const filteredProcessList = processList.value.filter((item) => {
        return item.processId != 1 && item.processId != 2;
      });
      //该工段能干的工序
      listDeptProcess({
        flag: "true",
        deptId: form.value.requisitionDepartmentId,
      }).then((res) => {
        if (res.code == 200) {
          var deptProcess = res.rows;
          var flag = false;
          console.log(deptProcess);
          console.log(filteredProcessList[0].processAlias)
          console.log(filteredProcessList[0].processAlias,deptProcess[0].processAlias)
          for (var i = 0; i < deptProcess.length; i++) {
            if (
              filteredProcessList[0].processId == deptProcess[i].processId
            ) {
              flag = true;
              break;
            }
          }
          if (flag) {
            //保存废品回用
            addWasteRecycling(wasteRecyclingInfo).then((response) => {
              if (response.code == 200) {
                emit("handleSaveSuccess")
                proxy.$modal.msgSuccess("添加废品回用成功");
                handleCancel();
              }
            });
          } else {
            proxy.$modal.msgError("当前领料部门不能干首序");
          }
        }
      });
    }
  });
};

/**添加历史工艺 */
function handleAddPreProcess() {
  currentUID = processList.value.length + 1;
  processList.value = [];
  getProcess({
    id: detailsRow.value.lotId,
    isAmend: detailsRow.value.isAmend,
    isWasteRecycling: detailsRow.value.isWasteRecycling,
    technologicalProcessId: detailsRow.value.technologicalProcessId,
  }).then((res) => {
    if (res.code == 200) {
      referenceLotInfo.value = res.data;
      for (var i = 0; i < referenceLotInfo.value.length; i++) {
        let process = {};
        process.technologyVersion = detailsRow.value.technologyVersion;
        process.productId = detailsRow.value.product.id;
        process.productCode = referenceLotInfo.value[i].productCode;
        process.processId = referenceLotInfo.value[i].processId;
        process.processKey = referenceLotInfo.value[i].processKey;
        process.processCode = referenceLotInfo.value[i].processCode;
        process.processAlias = referenceLotInfo.value[i].processAlias;
        process.productShaftCategory =
          referenceLotInfo.value[i].productShaftCategory;
        process.productShaftCategoryName =
          referenceLotInfo.value[i].productShaftCategoryName;
        process.productDescription =
          referenceLotInfo.value[i].productDescription;
        process.uuid = currentUID++;
        processList.value.push(process);
      }
      rowDrop();
    }
  });
}
/** 行拖拽 */
function rowDrop() {
  // 要侦听拖拽响应的DOM对象
  const tbody = document.querySelector(
    "#insideProcessForm .el-table__body-wrapper tbody"
  );
  Sortable.create(tbody, {
    // 指定父元素下可被拖拽的子元素
    handle: ".move-handle",
    // 结束拖拽后的回调函数
    onEnd({ newIndex, oldIndex }) {
      const currentRow = processList.value.splice(oldIndex, 1)[0];
      processList.value.splice(newIndex, 0, currentRow);
    },
  });
}

/**工序库添加工序 */
function handleAddProcess() {
  proxy.$refs.processChoiceRef.open();
}

/**工序库添加工序带回 */
function handleProcessSelected(selection) {
  console.log(detailsRow.value.product);
  currentUID = processList.value.length + 1;
  for (var i = 0; i < selection.length; i++) {
    var processAdd = {};
    //工艺从参考工艺取
    processAdd.technologyVersion = detailsRow.value.technologyVersion;
    processAdd.productId = detailsRow.value.product.id;
    processAdd.productCode = detailsRow.value.product.productCode;
    processAdd.processId = selection[i].id;
    processAdd.processAlias = selection[i].processAlias;
    processAdd.processCode = selection[i].processCode;
    processAdd.productShaftCategory =
      detailsRow.value.product.shaftCategoryCode;
    processAdd.productShaftCategoryName =
      detailsRow.value.productShaftCategoryName;
    processAdd.processKey = selection[i].processKey;
    processAdd.productDescription = detailsRow.value.productDescription;
    processAdd.uuid = currentUID++;
    processList.value.push(processAdd);
  }
  console.log(processList.value);
  rowDrop();
}
/** 获取行 id */
function getRowKey(row) {
  return row.uuid;
}
/** 取消按钮 */
const handleCancel = () => {
  visible.value = false;
  reset();
};

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
