<template>
  <!-- 添加或修改项目信息对话框 -->
  <el-dialog title="投产" height="400px" v-model="visible" width="900px" append-to-body draggable>
    <div class="form-container">
      <el-form ref="productRef" class="master-container" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产计划单号">
              <span>{{ detailsRow.productionPlanNo }}</span>
            </el-form-item>
            <el-form-item label="当前投产批数" prop="lotNumber">
              <el-input-number v-model="form.lotNumber" controls-position="right" style="width: 150px"
                @input="handleUpdateLotNumber" :min="0" />
              <el-button v-hasPermi="['business:productionBatch:outsourcedAdd']" :disabled="detailsRow.status"
                style="margin-left: 10px;" type="primary" @click="handleComputedMaterial">投料计算</el-button>
            </el-form-item>
            <el-form-item label="下达日期" prop="issuanceDate">
              <el-date-picker clearable v-model="form.issuanceDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择实际开始 时间" style="width: 150px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品描述" prop="productDescription">
              <span>{{ detailsRow.productDescription }}</span>
            </el-form-item>
            <el-form-item label="当前投产量" prop="productionQuantity">
              <el-input-number v-model="form.productionQuantity" :precision="0" :disabled="true"
                controls-position="right" style="width: 150px" />
            </el-form-item>
            <el-form-item label="尾批" style="align-items: center" prop="lastLotStatus">
              <el-switch v-model="form.lastLotStatus" :disabled="detailsRow.lastLot || detailsRow.status" size="large"
                style="
                  --el-switch-on-color: #13ce66;
                  --el-switch-off-color: #ff4949;
                " active-text="是" inactive-text="否" :active-value="1" :inactive-value="0"
                @change="handleUpdateLastLotStatus" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 计算外协领料 -->
      <form-computed-material ref="formComputedMaterialRef" :single-selected="handleInputLotNumber" />
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="handleSave" :loading="buttonLoading">确定</el-button>
      <el-button icon="Close" @click="handleCancel">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import {
  savePlanDetailSubDetail,
  getLastLotStatus,
} from "@/api/business/planDetailSubDetail.js";
import { updateLotCodeStatus } from "@/api/business/productionPlanDetail.js";
import formComputedMaterial from "./computedMaterialForm.vue"
const { proxy } = getCurrentInstance();
const emit = defineEmits(["handleSaveSuccess"]);

/** 表单抽屉 页变量 */
const loading = ref(false);
const detailsRow = ref({});
const visible = ref(false);
const buttonLoading = ref(false)
//校验投产批次
const validateLotNumber = (rule, value, callback) => {
  let min = 0
  console.log(detailsRow.value.status)
  if (detailsRow.value.status) {
    min = detailsRow.value.minLotNumber - 1
  }
  console.log(min)

  const max = detailsRow.value.lotNumber;
  //如果生产子计划里没有尾批并且是编辑状态时
  if (!detailsRow.value.lastLot && detailsRow.value.status) {
    const max = detailsRow.value.lotNumber - 1;
    if (value > max) {
      callback(new Error(`尾批未投,当前投产批数不能超过` + max));
    } else if (value <= min) {
      callback(new Error(`当前投产批数最少应为` + (min + 1)));
    } else {
      callback();
    }
  } else {
    if (!Number.isInteger(value)) {
      callback(new Error(`当前投产批数不能是小数`));
    } else if (value <= min) {
      callback(new Error(`当前投产批数最少应为` + (min + 1)));
    } else if (value > max) {
      callback(new Error(`当前投产批数不能超过` + max));
    } else {
      callback();
    }
  }
};
//校验投产量
const validateproductionQuantity = (rule, value, callback) => {
  //如果此批为尾批
  if (form.value.lastLotStatus == 1) {
    var max =
      detailsRow.value.productionQuantity + detailsRow.value.lastLotQuantity;
  } else {
    var max = detailsRow.value.productionQuantity;
  }
  if (value <= 0) {
    callback(new Error("当前投产量应大于0"));
  } else if (value > max) {
    callback(new Error(`当前投产量不能超过` + max));
  } else {
    callback();
  }
};
//校验尾批switch
const validateSwitch = (rule, value, callback) => {
  //detailsRow.value.status为true时为编辑，为false时是新增
  if (detailsRow.value.status) {
    callback();
  } else {
    //当此批没选择尾批时
    if (form.value.lastLotStatus == 0) {
      //当前投产批数+子计划累计投产批数 = 总批数时，并且已投产的生产子计划没有尾批
      if (
        form.value.lotNumber + detailsRow.value.lotTotalNumber ==
        detailsRow.value.totalLotNumber &&
        !detailsRow.value.lastLot
      ) {
        callback(new Error("此次投产应选尾批"));
      } else {
        callback();
      }
    } else {
      callback();
    }
  }
};
const data = reactive({
  form: {
    deptId: null,
    lotNumber: 0,
  },
  rules: {
    lotNumber: [
      { required: true, message: "当前投产批数不能为空", trigger: "blur" },
      { validator: validateLotNumber, trigger: "blur" },
    ],
    issuanceDate: [
      { required: true, message: "下达日期不能为空", trigger: "blur" },
    ],
    productionQuantity: [
      { required: true, message: "当前投产量不能为空", trigger: "blur" },
      { validator: validateproductionQuantity, trigger: "blur" },
    ],
    lastLotStatus: [
      {
        required: false,
        message: "请选择是否尾批",
        trigger: ["change", "blur"],
      },
      { validator: validateSwitch, trigger: "blur" }, // 使用自定义验证函数进行验证
    ],
  },
});
const { form, rules } = toRefs(data);
/***********************  方法区  ****************************/
/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    productionPlanId: 0,
    productionPlanDetailId: "0",
    productionQuantity: 0,
    productId: "0",
    technologicalProcessId: "0",
    technologyVersion: "",
    lotNumber: 0,
    productionQuantity: 0,
    issuanceDate: proxy.moment().format("YYYY-MM-DD"),
    remark: null,
    lastLotStatus: 0,
  };
  proxy.resetForm("productRef");
}

/** 打开抽屉 */
function open(row) {
  reset();
  visible.value = true;
  loading.value = true;
  if (row) {
    detailsRow.value = proxy.deepClone(row);
    form.value.id = row.id;
    form.value.productionPlanNo = row.productionPlanNo;
    form.value.productionPlanDetailId = row.productionPlanDetailId;
    form.value.productId = row.productId;
    form.value.deptId = row.deptId;
    form.value.technologicalProcessId = row.technologicalProcessId;
    form.value.technologyVersion = row.technologyVersion;
    form.value.lastLotStatus = detailsRow.value.lastLotStatus;
    if (typeof row.pickUpQuantity == "undefined") {
      detailsRow.value.pickUpQuantity = 0;
    }
    if (typeof row.lotTotalNumber == "undefined") {
      detailsRow.value.lotTotalNumber = 0;
    }
    //当row.status为true时编辑状态
    if (row.status) {
      form.value.lotNumber = row.lotNumber;
      detailsRow.value.lotNumber =
        detailsRow.value.totalLotNumber -
        detailsRow.value.lotTotalNumber +
        row.lotNumber;
      form.value.productionQuantity = row.productionQuantity;
      //已投产的生产子计划有尾批
      if (detailsRow.value.lastLot) {
        detailsRow.value.productionQuantity =
          detailsRow.value.productionQuantityTotal -
          detailsRow.value.pickUpQuantity +
          detailsRow.value.productionQuantity;
      } else {
        detailsRow.value.productionQuantity =
          detailsRow.value.productionQuantityTotal -
          detailsRow.value.pickUpQuantity +
          detailsRow.value.productionQuantity -
          detailsRow.value.lastLotQuantity;
      }
      //新增状态
    } else {
      detailsRow.value.lotNumber =
        detailsRow.value.totalLotNumber - detailsRow.value.lotTotalNumber;
      //子计划已经有尾批
      if (detailsRow.value.lastLot) {
        detailsRow.value.productionQuantity =
          detailsRow.value.productionQuantityTotal -
          detailsRow.value.pickUpQuantity;
      } else {
        detailsRow.value.productionQuantity =
          detailsRow.value.productionQuantityTotal -
          detailsRow.value.pickUpQuantity -
          detailsRow.value.lastLotQuantity;
      }
    }
  }
  loading.value = false;
}
//当前投产批数修改时，投产量自动改变
function handleUpdateLotNumber(data) {
  if (data <= 0) {
    form.value.productionQuantity = 0;
  } else {
    //该批为尾批
    if (form.value.lastLotStatus == 1) {
      if (
        (data - 1) * detailsRow.value.oneLotQuantity >
        detailsRow.value.productionQuantity
      ) {
        form.value.productionQuantity =
          detailsRow.value.productionQuantity +
          detailsRow.value.lastLotQuantity;
      } else {
        form.value.productionQuantity =
          (data - 1) * detailsRow.value.oneLotQuantity +
          detailsRow.value.lastLotQuantity;
      }
    }
    //该批不是尾批
    else {
      //当前投产批数*生产计划单批量>总投产量时，投产量为总投产量
      if (
        data * detailsRow.value.oneLotQuantity >
        detailsRow.value.productionQuantity
      ) {
        form.value.productionQuantity = detailsRow.value.productionQuantity;
      } else {
        form.value.productionQuantity = data * detailsRow.value.oneLotQuantity;
      }
    }
  }
}
function handleInputLotNumber(data) {
  form.value.lotNumber = data
  handleUpdateLotNumber(data)
}
//当尾批switch状态改变时
function handleUpdateLastLotStatus() {
  handleUpdateLotNumber(form.value.lotNumber);
}

/** 提交按钮 */
function handleSave() {
  proxy.$refs["productRef"].validate((valid) => {
    if (valid) {
      // /**工艺版本变成P2拉取过来先绑定个假数据 */
      buttonLoading.value = true
      savePlanDetailSubDetail(form.value).then((res) => {
        buttonLoading.value = false
        if (res.code == 200) {
          proxy.$modal.msgSuccess("保存成功！");
          visible.value = false;
          //detailsRow.value.id = detailsRow.value.productionPlanDetailId
          if (detailsRow.value.lotTotalNumber == 0) {
            updateLotCodeStatus({
              id: detailsRow.value.productionPlanDetailId,
              lotCodeStatusCode: "OKK",
            }).then((res) => { });
          }
          emit("handleSaveSuccess");
        }
      });
    }
  });
}
//外协投料计算
function handleComputedMaterial() {
  proxy.$refs.formComputedMaterialRef.open(detailsRow.value);
}
/** 取消按钮 */
function handleCancel() {
  visible.value = false;
  reset();
}

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