<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="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 useUserStore().allDict['come_stock_type']" :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="剩余库存" prop="surplusStock" width="140" />
              <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%">
      <SelectInventory
        :selectStatus="true"
        :departmentId="formData.data.departmentId"
        :warehouseId="formData.data.warehouseId"
        @selectBOM="selectBOM"></SelectInventory>
      <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 SelectInventory from "/src/views/production/warehouse/inventory/index";

const { proxy } = getCurrentInstance();
const departmentList = ref([{ dictKey: "0", dictValue: "胜德体育" }]);
const warehouseList = 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: 0,
    applicant: proxy.useUserStore().user.nickName,
    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,
        };
      });
    }
  });
};
getDemandData();
const openBOM = ref(false);
const clickAddBOM = () => {
  if (!(formData.data.departmentId || formData.data.departmentId === "0")) {
    return ElMessage("请先选择事业部");
  }
  if (!(formData.data.warehouseId || formData.data.warehouseId === "0")) {
    return ElMessage("请先选择仓库");
  }
  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已添加");
    }
  }
  if (item.id) {
    formData.data.inOutStorageBomList.push({
      bomSpecId: item.bomSpecId,
      code: item.bomSpecCode,
      name: item.bomSpecName,
      surplusStock: item.quantity,
      quantity: undefined,
    });
    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) {
      for (let i = 0; i < formData.data.inOutStorageBomList.length; i++) {
        if (Number(formData.data.inOutStorageBomList[i].surplusStock) < Number(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-outbound",
  });
};
</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>
