<template>
  <el-dialog title="选择箱号表单" v-model="visible" width="400px" append-to-body draggable>
    <div class="form-container">
      <el-form ref="categoryRef" v-loading="loading" class="master-container" :model="form" :rules="rules"
        label-width="100px">
        <el-form-item label="外协单号：" prop="formCode" :rules="rules">
          {{ form.formCode }}
        </el-form-item>
        <el-form-item label="外协日期：" prop="formDate" :rules="rules">
          {{ form.formDate }}
        </el-form-item>
        <el-form-item label="批次号：" prop="lotCode" :rules="rules">
          {{ form.lotCode }}
        </el-form-item>
        <el-form-item label="产品描述：" prop="productDescription" :rules="rules">
          {{ form.productDescription }}
        </el-form-item>
        <el-form-item label="箱号：" prop="carrierIds">
          <el-select v-model="form.carrierIds" multiple filterable remote reserve-keyword placeholder="请选择箱号"
            :remote-method="(arg) => remoteCarriers(arg, form.newCarriers, form)" :loading="loadingCarrier"
            @change="(arg) => handleCarrierChange(arg, form)">
            <el-option v-for=" item in form.carriers " :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="handleSave">确 定</el-button>
      <el-button icon="Close" @click="handleCancel">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import {
  carrierForOutsource,
  saveCarriers,
} from "@/api/business/outsourcedOrder";
const { proxy } = getCurrentInstance();
const emit = defineEmits(["handleSaveSuccess"]);
/** 字典数组区 */
const { is_allow_more } = proxy.useDict("is_allow_more");
/** 父类别 */
const parentCategories = ref([]);
const loading = ref(false);
const loadingCarrier = ref(false)
const visible = ref(false);
const carriers = ref([])
const data = reactive({
  form: {},
  rules: {
  }
});
const { form, rules } = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(row) {
  reset();
  visible.value = true;
  form.value = { ...row, carriers: row.carriers.map(v => ({ label: v.code, value: v.id })) }
}

/** 取消按钮 */
function handleCancel() {
  visible.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null
  };
  proxy.resetForm("categoryRef");
}

function carrierValidator(rules, value) {
  console.log(rules)
  console.log(value)
}

/** 提交按钮 */
function handleSave() {
  if (form.value.carrierIds == null || form.value.carrierIds.length === 0) {
    proxy.$modal.msgError("箱号不能为空");
    return
  }
  proxy.$refs["categoryRef"].validate((valid) => {
    if (valid) {
      saveCarriers(form.value).then((res) => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess("操作成功");
          emit("handleSaveSuccess");
        }
        visible.value = false;
      });
    }
  });
}

function remoteCarriers(code, newCarrier, row) {
  loadingCarrier.value = true;
  // console.log("row", row);
  let categoryId;
  // if (form.value.packagingMethod == 1) {
  categoryId = "1783783697558847489";
  // } else {
  //   categoryId = "2";
  // }
  if (code == "") {
    return;
  }
  carrierForOutsource({
    code: code,
    dayworkId: row.dayworkId
  }).then((res) => {
    if (res.code === 200) {
      carriers.value = res.rows.map((v) => ({ value: v.id, label: v.code }));
      row.carriers = res.rows.map((v) => ({ value: v.id, label: v.code }));
      if (Array.isArray(newCarrier)) {
        // 安全地更新 carriers
        row.carriers.push(
          ...newCarrier
            .filter((v) => !row.carriers.map((e) => e.value).includes(v.id))
            .map((v) => ({ value: v.id, label: v.code }))
        );
      }
    } else {
      row.carriers = [];
      row.carriers.push(...newCarrier);
    }
    loadingCarrier.value = false;
  });
}

function handleCarrierChange(arg, item) {
  item.newCarriers = item.carriers
    .filter((v) => arg.includes(v.value))
    .map((v) => ({ id: v.value, code: v.label }));
  // console.log(item.newCarriers);
  item.carrierNum = item.newCarriers.length;
}

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