<template>
    <div class="table-box">
        <div style="padding-bottom: 16px">
            <PermissionButton
                :buttons="dataStore.buttons"
                @handleButtonClickCallback="handleButtonClickCallback"
            ></PermissionButton>
        </div>
        <div class="card table-main">
            <DetailsSearch
                :formData="dataStore.formData"
                :ruleForm="dataStore.ruleForm"
                :labelWidth="dataStore.labelWidth"
                :inline="true"
                ref="detailsRef"
                @selectChange="handleChange"
            />
        </div>
    </div>
</template>

<script setup lang="ts" name="foundationSetGoodsAdd">
import { BUTTON } from "./constant/list/addButton";
import { cloneDeep } from "lodash-es";
import { DETAILS_FORM_DATA, DETAILS_RULE_FORM } from "./constant/list/add";
import DetailsSearch from "@/components/DetailsSearch/index.vue";
import PermissionButton from "@/components/PermissionButton/index.vue";
import { useUserStore } from "@/stores/modules/user";
import $Bus from "@/utils/mittBus";
import { getGoodsAddApi, getGoodsUpApi, getGoodsDetailsApi, getGoodsCheckExistswApi } from "@/api/modules/setGoods";
import { getWarehousesListApi } from "@/api/modules/global";
import { useMsg } from "@/hooks/useMsg";
const userStore = useUserStore();
const route = useRoute();
const $router = useRouter();
// 数据源
const dataStore = reactive<any>({
    buttons: cloneDeep(BUTTON),
    labelWidth: "120px",
    formData: cloneDeep(DETAILS_FORM_DATA),
    ruleForm: cloneDeep(DETAILS_RULE_FORM),
    compareRuleForm: {},
    id: null,
    title: ""
});
// 详情表单实例
const detailsRef = ref(null);

//初始化组织数据
const init = () => {
    if (userStore.orgIdArr.length) {
        dataStore.formData[0].options = userStore?.orgIdArr;
    }
};
init();

//新增
const handleAdd = async () => {
    const result = await getGoodsAddApi(dataStore.ruleForm);
    if (result?.code === 0) {
        useMsg("success", "新增成功 ！");
        dataStore.id = result?.data?.id;
        $Bus.emit("setGoodsResetList");
    }
};
//更新
const getGoodsUp = async () => {
    const result = await getGoodsUpApi(dataStore.id, dataStore.ruleForm);
    if (result?.code === 0) {
        useMsg("success", "更新成功 ！");
        $Bus.emit("setGoodsResetList");
        //更新成功以后调用详情接口是为了刷新对比数据防止对比数据不一致
        getGoodsDetails();
    }
};
//详情
const getGoodsDetails = async () => {
    dataStore.id = route.query.id;
    if (!dataStore.id) {
        return;
    }
    //getGoodsDetailsApi
    const result = await getGoodsDetailsApi(dataStore.id);
    if (result?.code === 0) {
        dataStore.ruleForm = result?.data;
        dataStore.compareRuleForm = cloneDeep(result?.data);
    }
};
getGoodsDetails();
//验证
const getGoodsCheckExistsw = async () => {
    const result = await getGoodsCheckExistswApi({
        use_org_number: dataStore.ruleForm.use_org_number,
        warehouse_number: dataStore.ruleForm.warehouse_number
    });
    if (result?.code === 0 && result?.data?.exists) {
        useMsg("error", "仓库已存在数据, 无需再次新增 ！");
    }
};
// 按钮点击事件
const handleButtonClickCallback = (item: any) => {
    const { type } = item;
    dataStore.title = route.query.title;
    if (type === "save") {
        if (!dataStore.ruleForm.use_org_number) {
            return useMsg("warning", "组织不能为空 !");
        }
        if (!dataStore.ruleForm.warehouse_number) {
            return useMsg("warning", "仓库不能为空 !");
        }
        if (!dataStore.ruleForm.pos_picking_priority) {
            return useMsg("warning", "仓位不能为空 !");
        }
        dataStore.title === "新增仓位找货优先级" ? handleAdd() : getGoodsUp();
    }
    if (type === "preview") {
        if (!dataStore.id && dataStore.title === "新增仓位找货优先级") {
            useMsg("warning", "请先保存数据 !");
            return;
        }
        // 编辑的话需要判断用户是否有修改
        if (dataStore.title === "编辑仓位找货优先级") {
            if (dataStore.compareRuleForm.use_org_number !== dataStore.ruleForm.use_org_number) {
                useMsg("warning", "请先保存数据 !");
                return;
            }
            if (dataStore.compareRuleForm.warehouse_number !== dataStore.ruleForm.warehouse_number) {
                useMsg("warning", "请先保存数据 !");
                return;
            }
            if (dataStore.compareRuleForm.pos_picking_priority !== dataStore.ruleForm.pos_picking_priority) {
                useMsg("warning", "请先保存数据 !");
                return;
            }
        }

        $router.push({
            path: "/foundation/set/goods/preview",
            query: { id: dataStore.id, name: dataStore.title }
        });
    }
    if (type === "return") {
        $router.push({
            path: "/foundation/set/goods/index"
        });
    }
};

//去重
const uniqueArrayObject = (arr: any[], uniqueKey: any = "value") => {
    // 边界处理：如果传入的不是数组，直接返回空数组
    if (!Array.isArray(arr)) {
        console.warn("传入的参数不是数组，返回空数组");
        return [];
    }
    // 方法1：Map 实现（高效，保留顺序）
    const uniqueMap = new Map();
    arr.forEach(item => {
        // 确保对象存在该字段，避免报错
        if (item.hasOwnProperty(uniqueKey)) {
            // 以 uniqueKey 的值为键，重复键会自动覆盖（保留最后一次出现？不，forEach 顺序遍历，后出现的会覆盖前面的，如需保留首次出现，用下面的逻辑）
            // 如需保留首次出现：只有 Map 中没有该键时才添加
            if (!uniqueMap.has(item[uniqueKey])) {
                uniqueMap.set(item[uniqueKey], item);
            }
        }
    });
    // 转换为数组返回
    return Array.from(uniqueMap.values());
};

//仓库列表 /foundation/set/goods/preview
const getWarehousesList = async () => {
    const result = await getWarehousesListApi({ use_org_number: dataStore.ruleForm.use_org_number });
    if (result?.code === 0) {
        const { data } = result;
        if (data?.length) {
            let options: any = [];
            data.forEach((item: any) => {
                options.push({
                    // id: item.id,
                    value: item.warehouse_number,
                    label: item.warehouse_name
                });
            });
            dataStore.formData[1].options = options;
            if (dataStore.ruleForm.warehouse_name) {
                dataStore.formData[1].options.push({
                    value: dataStore.ruleForm.warehouse_number,
                    label: dataStore.ruleForm.warehouse_name
                });

                dataStore.formData[1].options = uniqueArrayObject(dataStore.formData[1].options);
            }
        } else {
            dataStore.formData[1].options = [];
        }
    }
};
const handleChange = (item: any) => {
    console.log(item);
    if (item.prop === "warehouse_number") {
        if (!dataStore.ruleForm.use_org_number || !dataStore.ruleForm.warehouse_number) {
            return;
        }
        getGoodsCheckExistsw();
    }
};
//监听当前组织
watch(
    () => dataStore.ruleForm.use_org_number,
    (newVal: any) => {
        if (!newVal) {
            dataStore.ruleForm.warehouse_number = "";
            dataStore.formData[1].options = [];
            return;
        }
        getWarehousesList();
    },
    {
        deep: true,
        immediate: true
    }
);
</script>

<style scoped></style>
