<template>
  <div>
    <el-card class="box-card">
      <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="purchaseId"
                  :rules="[{ required: formData.data.detailType === '1' ? true : false, message: '请选择采购合同', trigger: 'change' }]"
                  style="width: 100%; margin-bottom: 18px">
                  <el-select
                    v-model="formData.data.purchaseId"
                    placeholder="请选择采购合同"
                    clearable
                    filterable
                    style="width: 100%"
                    @change="changePurchase()">
                    <el-option v-for="item in purchaseContractList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
                  </el-select>
                </el-form-item>
                <el-form-item label="事业部" prop="departmentId" style="width: 100%; margin-bottom: 18px">
                  <el-select v-model="formData.data.departmentId" placeholder="请选择事业部" clearable style="width: 100%">
                    <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="warehouseId" style="width: 100%; margin-bottom: 18px">
                  <el-select v-model="formData.data.warehouseId" placeholder="请选择仓库" clearable style="width: 100%">
                    <el-option v-for="item in warehouseList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
                  </el-select>
                </el-form-item>
                <el-form-item label="入库类型" prop="detailType" style="width: 100%; margin-bottom: 18px">
                  <el-select v-model="formData.data.detailType" placeholder="请选择入库类型" clearable style="width: 100%">
                    <el-option v-for="item in getType()" :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">
              <el-button type="primary" size="small" @click="clickAddBOM()">选择BOM</el-button>
            </div>
            <el-table :data="formData.data.inOutStorageBomList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
              <el-table-column label="品号" prop="code" width="180" />
              <el-table-column label="品名" prop="name" min-width="220" />
              <el-table-column label="单品尺寸（L*W*H）" align="center" width="300">
                <template #default="{ row }">
                  <span>{{ `${row.length} * ${row.width} * ${row.height}` }}</span>
                </template>
              </el-table-column>
              <el-table-column label="可入库数量" width="140" v-if="formData.data.purchaseId">
                <template #default="{ row }">
                  <span v-if="row.purchaseQuantity && row.arrivalQuantity">{{ Number(Math.round(row.purchaseQuantity - row.arrivalQuantity)) }}</span>
                  <span v-else>{{ row.purchaseQuantity }}</span>
                </template>
              </el-table-column>
              <el-table-column label="入库数量" width="180">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'inOutStorageBomList.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true" style="width: 100%">
                    <el-input-number
                      onmousewheel="return false;"
                      v-model="row.quantity"
                      placeholder="入库数量"
                      style="width: 100%"
                      :controls="false"
                      :min="0"
                      :precision="0" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" fixed="right" width="60">
                <template #default="{ $index }">
                  <el-button type="danger" @click="clickDelete($index)" text>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <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>
    </el-card>

    <el-dialog title="选择BOM" v-if="openBOM" v-model="openBOM" width="90%">
      <SelectBOM :selectStatus="true" :purchaseId="formData.data.purchaseId" @selectBOM="selectBOM"></SelectBOM>
      <template #footer>
        <el-button @click="openBOM = false" size="large">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import byForm from "/src/components/byForm/index";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import useTagsViewStore from "/src/store/modules/tagsView";
import SelectBOM from "/src/views/group/BOM/management/index";

const { proxy } = getCurrentInstance();
const departmentList = ref([{ dictKey: "0", dictValue: "胜德体育" }]);
const warehouseList = ref([]);
const purchaseContractList = ref([]);
const router = useRouter();
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: "100px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
});
const formData = reactive({
  data: {
    type: 1,
    applicant: proxy.useUserStore().user.nickName,
    departmentId: "0",
    inOutStorageBomList: [],
  },
});
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({
  departmentId: [{ required: true, message: "请选择事业部", trigger: "change" }],
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  detailType: [{ required: true, message: "请选择入库类型", trigger: "change" }],
  applicant: [{ required: true, message: "请输入申请人", trigger: "blur" }],
  quantity: [{ 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,
          };
        })
      );
    }
  });
  proxy.post("/warehouse/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      warehouseList.value = res.rows.map((item) => {
        return {
          dictKey: item.id,
          dictValue: item.name,
        };
      });
    }
  });
  proxy.post("/purchase/purchaseInStorageList", {}).then((res) => {
    if (res && res.length > 0) {
      purchaseContractList.value = res.map((item) => {
        return {
          ...item,
          dictKey: item.id,
          dictValue: item.code + "，" + item.deliveryDate + "，" + item.supplierName,
        };
      });
    }
  });
};
getDemandData();
const changePurchase = () => {
  formData.data.inOutStorageBomList = [];
  if (formData.data.purchaseId) {
    let list = purchaseContractList.value.filter((item) => item.id === formData.data.purchaseId);
    if (list && list.length > 0) {
      if (list[0].supplierId && list[0].supplierId === "1698993849235431426") {
        formData.data.warehouseId = "1684037244354052098";
      } else {
        formData.data.warehouseId = "1684037201379213314";
      }
    }
  }
};
const openBOM = ref(false);
const clickAddBOM = () => {
  openBOM.value = true;
};
const selectBOM = (item) => {
  if (formData.data.inOutStorageBomList && formData.data.inOutStorageBomList.length > 0) {
    let list = formData.data.inOutStorageBomList.filter((itemFilter) => itemFilter.bomSpecId === item.id);
    if (list && list.length > 0) {
      return ElMessage("该BOM已添加");
    }
  }
  let id = item.id;
  if (formData.data.purchaseId) {
    id = item.bomSpecId;
  }
  formData.data.inOutStorageBomList.push({
    bomSpecId: id,
    code: item.code,
    name: item.name,
    length: item.length,
    width: item.width,
    height: item.height,
    quantity: undefined,
    purchaseQuantity: item.purchaseQuantity,
    arrivalQuantity: item.arrivalQuantity,
  });
  ElMessage({ message: "选择完成", type: "success" });
};
const clickDelete = (index) => {
  formData.data.inOutStorageBomList.splice(index, 1);
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (formData.data.inOutStorageBomList && formData.data.inOutStorageBomList.length > 0) {
      if (formData.data.purchaseId) {
        for (let i = 0; i < formData.data.inOutStorageBomList.length; i++) {
          let quantity = formData.data.inOutStorageBomList[i].purchaseQuantity;
          if (formData.data.inOutStorageBomList[i].purchaseQuantity && formData.data.inOutStorageBomList[i].arrivalQuantity) {
            quantity = Number(Math.round(formData.data.inOutStorageBomList[i].purchaseQuantity - formData.data.inOutStorageBomList[i].arrivalQuantity));
          }
          if (quantity < formData.data.inOutStorageBomList[i].quantity) {
            return ElMessage("入库数量不能大于可入库数量");
          }
        }
      }
      proxy.post("/inOutStorage/add", formData.data).then(() => {
        ElMessage({
          message: "提交成功",
          type: "success",
        });
        clickCancel();
      });
    } else {
      return ElMessage("请添加BOM");
    }
  });
};
const clickCancel = () => {
  const useTagsStore = useTagsViewStore();
  useTagsStore.delVisitedView(router.currentRoute.value);
  router.replace({
    path: "/production/warehouse/warehouse-putInStorage",
  });
};
const getType = () => {
  let list = [];
  if (proxy.useUserStore().allDict["put_stock_type"] && proxy.useUserStore().allDict["put_stock_type"].length > 0) {
    list = proxy.useUserStore().allDict["put_stock_type"].filter((item) => item.dictKey == "1");
  }
  return list;
};
</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>
