<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" @change="changeDepartment">
                  <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" @change="changeDepartment">
                  <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="checkTaker" style="width: 100%; margin-bottom: 18px">
                  <el-input v-model="formData.data.checkTaker" 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 #checkBomList>
          <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.checkBomList" :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="160">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'checkBomList.' + $index + '.checkQuantity'" :rules="rules.checkQuantity" :inline-message="true" style="width: 100%">
                    <el-input-number
                      onmousewheel="return false;"
                      v-model="row.checkQuantity"
                      placeholder="盘点数量"
                      style="width: 100%"
                      :controls="false"
                      :min="0"
                      :precision="0" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <span v-if="row.checkQuantity && Number(row.checkQuantity) === Number(row.surplusStock)">正常</span>
                  <span v-else-if="row.checkQuantity && Number(row.checkQuantity) < Number(row.surplusStock)" style="color: #d9001b">盘亏</span>
                  <span v-else-if="row.checkQuantity && Number(row.checkQuantity) > Number(row.surplusStock)" style="color: #f59a23">盘盈</span>
                </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: {
    checkTaker: proxy.useUserStore().user.nickName,
    checkBomList: [],
  },
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "盘点信息",
      label: "",
    },
    {
      type: "slot",
      slotName: "basicInformation",
      label: "",
    },
    {
      type: "title",
      title: "库存",
      label: "",
    },
    {
      type: "slot",
      slotName: "checkBomList",
      label: "",
    },
  ];
});
const rules = ref({
  departmentId: [{ required: true, message: "请选择事业部", trigger: "change" }],
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  checkTaker: [{ required: true, message: "请输入盘点人", trigger: "blur" }],
  checkQuantity: [{ 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.checkBomList && formData.data.checkBomList.length > 0) {
    let list = formData.data.checkBomList.filter((itemFilter) => itemFilter.bomSpecId === item.id);
    if (list && list.length > 0) {
      return ElMessage("该BOM已添加");
    }
  }
  if (item.id) {
    formData.data.checkBomList.push({
      bomSpecId: item.bomSpecId,
      code: item.bomSpecCode,
      name: item.bomSpecName,
      surplusStock: item.quantity,
      checkQuantity: undefined,
    });
    ElMessage({ message: "选择完成", type: "success" });
    console.log(formData.data.checkBomList, item);
  }
};
const changeDepartment = () => {
  formData.data.checkBomList = [];
};
const clickDelete = (index) => {
  formData.data.checkBomList.splice(index, 1);
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (formData.data.checkBomList && formData.data.checkBomList.length > 0) {
      proxy.post("/check/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-check",
  });
};
</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>
