<template>
  <div v-loading="loading">
    <div style="height: calc(100vh - 174px); overflow-y: auto; overflow-x: hidden">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #basicInformation>
          <div style="width: 100%">
            <el-row>
              <el-col :span="12">
                <el-form-item label="事业部" prop="outDepartmentId" style="width: 100%; margin-bottom: 18px">
                  <el-select v-model="formData.data.outDepartmentId" placeholder="请选择事业部" style="width: 100%" @change="changeDepartment">
                    <el-option v-for="item in departmentList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
                  </el-select>
                </el-form-item>
                <el-form-item label="申请人" prop="applicant" style="width: 100%; margin-bottom: 18px">
                  <el-input v-model="formData.data.applicant" placeholder="请输入申请人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remark" style="width: 100%; margin-bottom: 18px">
                  <el-input v-model="formData.data.remark" :rows="4" type="textarea" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </template>
        <template #inOutStorageBomList>
          <div style="width: 100%; padding: 0 20px">
            <div style="margin-bottom: 10px">{{ statisticalQuantity() }}</div>
            <el-table :data="inOutStorageBomList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
              <el-table-column label="BOM品号" prop="bomSpecCode" width="180" />
              <el-table-column label="BOM品名" prop="bomSpecName" min-width="220" />
              <el-table-column label="仓库名称" prop="warehouseName" width="160" />
              <el-table-column label="剩余库存" prop="inventoryQuantity" width="120" />
              <el-table-column label="出库数量" width="140">
                <template #default="{ row }">
                  <span :style="!row.inventoryQuantity || row.inventoryQuantity < row.outQuantity ? 'color: red' : ''">{{ row.outQuantity }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
    </div>
    <div style="text-align: center; margin: 10px">
      <el-button @click="clickCancel()" size="large">取 消</el-button>
      <el-button type="primary" @click="submitForm()" size="large" v-preReClick>确 定</el-button>
    </div>
  </div>
</template>

<script setup>
import byForm from "/src/components/byForm/index";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const departmentList = ref([{ dictKey: "0", dictValue: "胜德体育" }]);
const props = defineProps({
  pagination: Object,
});
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: "100px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
});
const formData = reactive({
  data: {
    // departmentId: props.departmentId,
    outDepartmentId: "0",
    applicant: proxy.useUserStore().user.nickName,
    ...props.pagination,
  },
});
const inOutStorageBomList = ref([]);
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "出库信息",
      label: "",
    },
    {
      type: "slot",
      slotName: "basicInformation",
      label: "",
    },
    {
      type: "title",
      title: "物料信息",
      label: "",
    },
    {
      type: "slot",
      slotName: "inOutStorageBomList",
      label: "",
    },
  ];
});
const rules = ref({
  outDepartmentId: [{ required: true, message: "请选择事业部", trigger: "change" }],
  applicant: [{ required: true, message: "请输入申请人", trigger: "blur" }],
});
const getDemandData = () => {
  proxy.post("/department/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      departmentList.value = departmentList.value.concat(
        res.rows.map((item) => {
          return {
            dictKey: item.id,
            dictValue: item.name,
          };
        })
      );
    }
  });
};
getDemandData();
const emit = defineEmits(["clickCancel"]);
const loading = ref(false);
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (inOutStorageBomList.value && inOutStorageBomList.value.length > 0) {
      for (let i = 0; i < inOutStorageBomList.value.length; i++) {
        if (Number(inOutStorageBomList.value[i].inventoryQuantity) < Number(inOutStorageBomList.value[i].outQuantity)) {
          return ElMessage("出库数量大于剩余库存数量");
        }
      }
      loading.value = true;
      proxy.post("/stockPreparation/submit", formData.data).then(
        () => {
          ElMessage({ message: "提交完成", type: "success" });
          emit("clickCancel", true);
        },
        (err) => {
          console.log(err);
          loading.value = false;
        }
      );
    } else {
      return ElMessage("请添加BOM");
    }
  });
};
const clickCancel = () => {
  emit("clickCancel", false);
};
onMounted(() => {
  proxy.post("/stockPreparation/outBomList", formData.data).then((res) => {
    inOutStorageBomList.value = Object.freeze(res);
  });
});
const changeDepartment = () => {
  proxy.post("/stockPreparation/outBomList", formData.data).then((res) => {
    inOutStorageBomList.value = Object.freeze(res);
  });
};
const statisticalQuantity = () => {
  let quantity = 0;
  let material = {};
  if (inOutStorageBomList.value && inOutStorageBomList.value.length > 0) {
    let principal = inOutStorageBomList.value.filter((item) => item.classifyParentId == "1");
    if (principal && principal.length > 0) {
      for (let j = 0; j < principal.length; j++) {
        if (principal[j].outQuantity) {
          quantity = Number(Math.round(quantity + principal[j].outQuantity));
        }
      }
    }
    let auxiliaryMaterial = inOutStorageBomList.value.filter((item) => item.classifyParentId != "1");
    if (auxiliaryMaterial && auxiliaryMaterial.length > 0) {
      for (let i = 0; i < auxiliaryMaterial.length; i++) {
        if (material[auxiliaryMaterial[i].classifyId]) {
          material[auxiliaryMaterial[i].classifyId].quantity = Number(
            Math.round(material[auxiliaryMaterial[i].classifyId].quantity + auxiliaryMaterial[i].outQuantity)
          );
        } else {
          material[auxiliaryMaterial[i].classifyId] = {
            name: auxiliaryMaterial[i].classifyName,
            quantity: auxiliaryMaterial[i].outQuantity,
          };
        }
      }
    }
  }
  let text = "主材数量： " + quantity;
  for (let key in material) {
    if (key && material[key].name) {
      text = text + "， " + material[key].name + "： " + material[key].quantity;
    }
  }
  return text;
};
</script>

<style lang="scss" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
:deep(.el-dialog) {
  margin-top: 10px !important;
  margin-bottom: 10px !important;
}
</style>
