<template>
  <el-dialog title="批量周转信息表单" v-model="visible" width="500px" append-to-body draggable>
    <div class="form-container">
      <el-form ref="returnTurnoverRef" class="master-container" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="下序工段：" prop="productionDeptId" label-width="100px">
          <el-select-v2 v-model="form.productionDeptId" :disabled="!form.flag" :options="deptList"
            placeholder="请选择下序工段" style="width: 220px" @change="handleDeptChange" />
          <el-button @click="showProcessList">工序列表</el-button>
        </el-form-item>
        <el-form-item label="下序是否包装：" prop="isSortPackaging" label-width="130px">
          <el-switch v-model="form.isSortPackaging" active-text="是" :active-value="1" inactive-text="否"
            :inactive-value="0" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button v-if="form.flag" :loading="saveLoading" type="primary" icon="Check" @click="handleSave">确 定</el-button>
      <el-button v-if="form.flag" icon="Close" @click="handleCancel">取 消</el-button>
    </template>
    <dialog-process ref="dialogProcessRef" />
  </el-dialog>
</template>
<script setup>
import { listCarriers } from "@/api/business/lot";
import {
  getTurnoverDeptList,
  batchReceiptTurnover,
  getNowBindCarriers,
} from "@/api/business/returnTurnover";
import DialogProcess from './DialogProcess.vue'
import { ref } from "vue";
const { proxy } = getCurrentInstance();
const emit = defineEmits(["handleSaveSuccess"]);
/**工周转弹窗变量 */
const carriers = ref([]);
const deptList = ref([]);
const loadingCarrier = ref(false);
const visible = ref(false);
const dialogProcessRef = ref(null)
const saveLoading = ref(false)
const data = reactive({
  form: {},
  rules: {
    productionDeptId: [
      { required: true, message: "下序工段不能为空", trigger: "change" },
    ],
    carrierIds: [
      {
        required: true,
        type: "array",
        message: "周转载具不能为空",
        trigger: "blur",
      },
    ],
  },
});
const { form, rules } = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
function openBatch(batches) {
  reset();
  visible.value = true;
  console.log(batches)
  form.value = proxy.deepClone(batches[0]);
  form.value.isSortPackaging = "0"
  console.log(form.value)
  if (form.value.productionDeptId == 0) {
    form.value.productionDeptId = null;
  }
  form.value.batches = batches
  getTurnoverDept(form.value);
  form.value.batches.forEach((v, i) => {
    getNowCarriers(v, i)
  })
  // getCarriers();
}

//判断箱子是否需要解绑
function getNowCarriers(data, index) {
  getNowBindCarriers(data).then((res) => {
    if (res.code == 200) {
      form.value.batches[index].carriers =
        res.data.dayworkCarrierList && res.data.dayworkCarrierList.length > 0
          ? res.data.dayworkCarrierList.filter(v => v.processInspectionId == "0").map((v) => ({
            id: v.carrierId,
            code: v.carrierCode,
          }))
          : [];
      const carriers = res.data.dayworkCarrierList && res.data.dayworkCarrierList.length > 0
        ? res.data.dayworkCarrierList.filter(v => v.processInspectionId == "0").map((v) => ({
          id: v.carrierId,
          code: v.carrierCode,
        }))
        : []
      form.value.batches[index].carrierIds = res.data.carrierIds.filter(v => carriers.some(e => e.id == v));
    }
  });
}
function getTurnoverDept(data) {
  let lastProcessStepNumber =
    data.processes[data.processes.length - 1].processStepNumber;
  getTurnoverDeptList({
    dayworkId: form.value.dayworkId,
    processStepNumber: lastProcessStepNumber,
  }).then((res) => {
    if (res.code === 200) {
      deptList.value = res.data;
    }
  });
}
function handleDeptChange() {
  console.log(deptList.value)
  let deptInfo = deptList.value.find(item => item.value == form.value.productionDeptId)
  form.value.productionDeptName = deptInfo.label
  console.log(deptInfo)
  if (deptInfo.isSortPackaging == 1) {
    form.value.isSortPackaging = 1
    console.log(form.value)
  } else {
    form.value.isSortPackaging = 0
  }
}
function remoteCarriers(queryString, choiced) {
  console.log(choiced);
  loadingCarrier.value = true;
  listCarriers({
    isAbandoned: 0,
    pageSize: 200,
    code: queryString != "" ? queryString : null,
  }).then((res) => {
    if (res.code === 200) {
      carriers.value = res.rows.map((v) => ({
        value: v.id,
        label: v.code,
        category: v.categoryId,
      }));
      carriers.value.push(
        ...choiced
          .filter((v) => !carriers.value.map((e) => e.value).includes(v.id))
          .map((v) => ({ value: v.id, label: v.code }))
      );
    } else {
      carriers.value = [];
      carriers.value.push(...choiced);
    }
    loadingCarrier.value = false;
  });
}

function handleCarrierChange(arg) {
  form.value.carriers = carriers.value
    .filter((v) => arg.includes(v.value))
    .map((v) => ({ id: v.value, code: v.label }));
}

/** 取消按钮 */
function handleCancel() {
  visible.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    productionDeptId: null,
    productionCarrier: null,
    lotId: null,
    dayworkId: null,
  };
  proxy.resetForm("returnTurnoverRef");
}

/** 提交按钮 */
function handleSave() {
  console.log(saveLoading.value)
  saveLoading.value = true
  console.log(form.value)
  if (!form.value.flag) {
    visible.value = false;
    saveLoading.value = false
  } else {
    proxy.$refs["returnTurnoverRef"].validate((valid) => {
      if (valid) {
        console.log(saveLoading.value)
        //如果没有重新选箱
        batchReceiptTurnover(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          visible.value = false;
          emit("handleSaveSuccess");
          saveLoading.value = false
        }).catch(err => {
          saveLoading.value = false
        });
      } else {
        saveLoading.value = false
      }
    });
  }
}

function showProcessList() {
  console.log(form.value)
  dialogProcessRef.value.open({ dayworkId: form.value.dayworkId, lotId: form.value.lotId, isAmend: form.value.isAmend, isWasteRecycling: form.value.isWasteRecycling, finishedProcesses: form.value.finishedProcesses })
}
/** 暴露给父组件的方法 */
defineExpose({
  openBatch,
});
</script>
