<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" clearable :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="carrierIds" label-width="100px">
          <el-select v-model="form.carrierIds" :disabled="form.productionDeptId == null || !form.flag" multiple
            filterable remote reserve-keyword placeholder="请选择载具" value-key="value"
            :remote-method="(arg) => remoteCarriers(arg, form.carriers)" :loading="loadingCarrier"
            @change="(arg) => handleCarrierChange(arg)">
            <el-option v-for="item in carriers" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </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" 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,
  updateReceiptTurnover,
  getNowBindCarriers,
  checkCarriers
} 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 data = reactive({
  form: {},
  rules: {
    productionDeptId: [
      { required: true, message: "下序工段不能为空", trigger: "change" },
    ],
    carrierIds: [
      {
        required: true,
        type: "array",
        message: "周转载具不能为空",
        trigger: "blur",
      },
    ],
  },
});
const { form, rules } = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(data) {
  reset();
  visible.value = true;
  form.value = proxy.deepClone(data);
  form.value.isSortPackaging = "0"
  if (form.value.productionDeptId == 0) {
    form.value.productionDeptId = null;
  }
  console.log(form.value);
  getNowCarriers(form.value);
  getTurnoverDept(form.value);
  // getCarriers();
}

function getCarriers() {
  listCarriers({ isAbandoned: 0, pageSize: 200 }).then((res) => {
    if (res.code === 200) {
      carriers.value.push(
        ...res.rows.map((v) => ({ value: v.id, label: v.code }))
      );
      console.log(form.value.carriers);
      carriers.value.push(...form.value.carriers.map(v => ({ value: v.id, label: v.code })));
      // console.log(carriers.value);
    }
  });
}
function handleDeptChange() {
  console.log(deptList.value)
  let deptInfo = deptList.value.find(item => item.value == form.value.productionDeptId)
  console.log(deptInfo)
  if (deptInfo.isSortPackaging == 1) {
    form.value.isSortPackaging = 1
    console.log(form.value)
  } else {
    form.value.isSortPackaging = 0
  }
}
//判断箱子是否需要解绑
function getNowCarriers(data) {
  getNowBindCarriers(data).then((res) => {
    if (res.code == 200) {
      form.value.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) => ({
          value: v.carrierId,
          label: v.carrierCode,
        }))
        : []
      form.value.carrierIds = res.data.carrierIds.filter(v => form.value.carriers.some(e => e.id == v));
      getCarriers()
    }
  });
}
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 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,
      }));
      // console.log(choiced)
      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() {
  if (!form.value.flag) {
    visible.value = false;
  } else {
    proxy.$refs["returnTurnoverRef"].validate((valid) => {
      if (valid) {
        console.log(form.value)
        const carrierCode = form.value.carriers.map(v => v.code).join()
        checkCarriers({ carriers: carrierCode }).then(res => {
          if (!res.data) {
            proxy.$modal.msgError('请不要选择外协箱进行周转')
            return
          } else {
            //如果没有重新选箱
            if (form.value.carriers[0].value != undefined) {
              form.value.carriers = form.value.carriers.map((v) => ({
                id: v.value,
                code: v.label,
              }));
            }
            const carriersMap = new Map();
            // 填充映射，自动去重
            form.value.carriers.forEach((carrier) => {
              // 使用 code 作为键
              carriersMap.set(carrier.code, carrier);
            });
            // 从映射中提取唯一对象，形成新数组
            const uniqueCarriers = Array.from(carriersMap.values());
            form.value.carriers = uniqueCarriers;
            // 如果需要，可以创建一个由 code 组成的字符串
            form.value.productionCarrier = form.value.carriers
              .map((v) => v.code)
              .join(",");
            form.value.productionDeptName = deptList.value.find(
              (v) => v.value == form.value.productionDeptId
            ).label;
            console.log(form.value.carriers);
            console.log(form.value);
            updateReceiptTurnover(form.value).then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              visible.value = false;
              emit("handleSaveSuccess");
            });
          }
        })
      }
    });
  }
}

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({
  open,
});
</script>
