<!-- 新增/编辑仓库 -->
<template>
    <simple-form-modal
        :title="title"
        :items="formItems"
        ref="editRef"
        :baseUrl="baseUrl"
        labelWidth="120px"
        width="700px"
        @success="(data) => emit('success', data)"
        :type="type"
    />
</template>

<script setup>
    import { reactive, ref, computed, defineEmits, getCurrentInstance } from 'vue';
    import SimpleFormModal from '@/components/CommonPage/SimpleFormModal.vue';
    import request from '@/utils/request';

    const { proxy } = getCurrentInstance();
    const emit = defineEmits(['success']);

    const provinceList = ref([]);
    const cityList = ref([]);
    const countyList = ref([]);
    const title = ref('新增仓库');
    const type = ref('');
    const editRef = ref(null);

    const formItems = computed(() => {
        return [
            {
                type: 'input',
                label: '仓库名称',
                prop: 'repositoryName',
                required: true
            },
            {
                type: 'input',
                label: '联系人',
                prop: 'contactsName',
                required: true
            },
            {
                type: 'radio',
                label: '状态',
                prop: 'status',
                required: true,
                options: [
                    { label: '启用', value: '1' },
                    { label: '停用', value: '2' }
                ]
            },
            {
                type: 'select',
                label: '省份',
                prop: 'provinceId',
                required: true,
                options: provinceList.value.map((d) => ({
                    label: d.district,
                    value: d.id
                })),
                props: {
                    filterable: true,
                    onChange: (val) => {
                        cityList.value = [];
                        countyList.value = [];
                        if (val) {
                            getDistrictList(val).then((res) => {
                                cityList.value = res.data.data || [];
                            });
                        }
                    }
                }
            },
            {
                type: 'select',
                label: '所在市',
                prop: 'cityId',
                required: true,
                options: cityList.value.map((d) => ({
                    label: d.district,
                    value: d.id
                })),
                props: {
                    filterable: true,
                    onChange: (val) => {
                        countyList.value = [];
                        if (val) {
                            getDistrictList(val).then((res) => {
                                countyList.value = res.data.data || [];
                            });
                        }
                    }
                }
            },
            {
                type: 'select',
                label: '所在区',
                prop: 'countyId',
                required: true,
                options: countyList.value.map((d) => ({
                    label: d.district,
                    value: d.id
                })),
                props: {
                    filterable: true
                }
            },
            {
                type: 'input',
                label: '详细地址',
                prop: 'addressDetail',
                required: true
            },
            {
                type: 'input',
                label: '手机号码',
                prop: 'mobile',
                required: true,
                itemProps: {
                    rules: [
                        {
                            pattern: /^1[3-9]\d{9}$/,
                            message: '请输入正确的手机号码'
                        }
                    ]
                }
            }
        ];
    });

    const baseUrl = reactive({
        add: '/activation/bookActivationCodeRepository/add',
        update: '/activation/bookActivationCodeRepository/update'
    });

    const initParams = {
        status: '1'
    };

    function getDistrictList(id = 1) {
        return proxy.$http.get(`/baseinfo/districtInfo/findInfo/${id}`);
    }

    async function handleOpen(data = {}, optType) {
        type.value = optType || '';
        const isEdit = !!(data && data.id);

        if (optType === 'detail') {
            title.value = '仓库详情';
        } else {
            title.value = isEdit ? '编辑仓库' : '新增仓库';
        }

        await getDistrictList().then((res) => {
            provinceList.value = res.data.data || [];
        });

        let formData = isEdit ? { ...data } : { ...initParams };

        if (isEdit) {
            try {
                const res = await request.get(
                    `/activation/bookActivationCodeRepository/getInfo/${data.id}`
                );
                if (res.data.code === 200 && res.data.data) {
                    formData = { ...res.data.data };
                    formData.status = String(formData.status ?? '1');
                }
            } catch (e) {
                // 列表行数据兜底
            }

            if (formData.provinceId) {
                await getDistrictList(formData.provinceId).then((res) => {
                    cityList.value = res.data.data || [];
                });
            }
            if (formData.cityId) {
                await getDistrictList(formData.cityId).then((res) => {
                    countyList.value = res.data.data || [];
                });
            }
        } else {
            cityList.value = [];
            countyList.value = [];
        }

        editRef.value?.handleOpen(formData);
    }

    defineExpose({ handleOpen });
</script>
