<template>
    <z-paging ref="paging" bgColor="#F7F7F7" safe-area-inset-bottom paging-class="paging-btm-shadow" scroll-with-animation>
        <template #top>
            <ut-navbar :title="did ? '编辑库房' : '新增库房'" :fixed="false" border ></ut-navbar>
        </template>
        <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
            <view class="pd-24">
                <view class="startline-title">库房信息</view>
            </view>
            <view class="pd-24 bg-#fff mb-10">
                <view class="h-1" id="typepppp"></view>
                <ut-action-sheet v-model="form.type" :tabs="pt_warehouse_type" title="选择库房类型">
                    <up-form-item borderBottom label="库房类型" required prop="type">
                        <view v-if="form.type" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_warehouse_type, form.type) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择库房类型</view>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                        </template>
                    </up-form-item>
                </ut-action-sheet>
                <view class="h-1" id="warehouseNamepppp"></view>
                <up-form-item borderBottom label="库房名称" required prop="warehouseName">
                    <up-input v-model="form.warehouseName" placeholder="请输入库房名称" border="none" clearable></up-input>
                </up-form-item>
                <up-form-item borderBottom label="库房编号" prop="sn">
                    <up-input v-model="form.sn" placeholder="请输入库房编号" border="none" clearable></up-input>
                </up-form-item>
                <up-form-item borderBottom label="库房面积" prop="area">
                    <up-input v-model="form.area" type="number" placeholder="请输入库房面积" border="none" clearable></up-input>
                    <template #right>
                        <span>平方米</span>
                    </template>
                </up-form-item>
                <up-form-item borderBottom label="所在位置" prop="address">
                    <up-input v-model="form.address" placeholder="请输入所在位置" border="none" clearable></up-input>
                </up-form-item>
                <view class="h-1" id="contactpppp"></view>
                <up-form-item @click="selectStorageMember" borderBottom label="负责人" required prop="contact">
                    <view v-if="form.contact" class="f-s-30 c-333 f-w-5 flex1">{{ form.contactName }}</view>
                    <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择负责人</view>
                    <template #right>
                        <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                    </template>
                </up-form-item>
                <!-- 填写基地联系电话 -->
                <view class="h-1" id="telpppp"></view>
                <up-form-item borderBottom label="联系电话" required prop="tel">
                    <up-input v-model="form.tel" placeholder="请输入联系电话" border="none" clearable></up-input>
                </up-form-item>
                <up-form-item label="库房条件" prop="storageCondition">
                    <up-textarea v-model="form.storageCondition" placeholder="请输入库房条件" maxlength="300" autoHeight clearable></up-textarea>
                </up-form-item>
                <up-form-item label="备注" prop="remark">
                    <up-textarea v-model="form.remark" placeholder="请输入备注" maxlength="300" autoHeight clearable></up-textarea>
                </up-form-item>
            </view>
            <view class="pd-24">
                <view class="startline-title">货位信息</view>
            </view>
            <view class="pd-24 bg-#fff mb-10">
                <up-form-item borderBottom :label="`货位数量（${form?.shelves?.length || 0}）`" prop="shelves"> </up-form-item>
                <up-swipe-action>
                    <template v-for="(item, index) in form.shelves" :key="index">
                        <up-swipe-action-item class="mb-20" :options="shelveOptions" @click="clickShelveSwipe($event, item, index)">
                            <view class="plot-item pd-24">
                                <view class="f-s-32 f-w-5 c-#333">{{ item?.shelvesName || '-' }}</view>
                                <view v-if="item?.sn" class="f-s-24 c-#666">{{ item?.sn }}</view>
                                <view class="pd-5"></view>
                                <view class="f-s-28 c-#333" v-if="item?.remark">
                                    <span class="">备注：</span>
                                    <span class="c-#333 f-w-5">{{ item?.remark }}</span>
                                </view>
                            </view>
                        </up-swipe-action-item>
                    </template>
                </up-swipe-action>
                <up-button @click="addShelve()" type="primary" text="确定" plain>
                    <up-icon class="mr-10" name="plus" color="#37A954"></up-icon>
                    <span>添加货位信息</span>
                </up-button>
            </view>
        </up-form>
        <template #bottom>
            <view class="base-bottom-wrap pd-20 pb-0">
                <up-button type="primary" @click="submit">
                    <text>{{ did ? '保存' : '提交' }}</text>
                </up-button>
            </view>
        </template>
    </z-paging>

    <!-- 悬浮新增按钮（编辑页通常不需要，但与列表风格一致时可保留） -->
    <!-- <ut-suspension @click="submit">
        <image src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/addBase.png" mode="widthFix" class="w-120 h-120"></image>
    </ut-suspension> -->

    <!-- 货位表单弹窗：新增/编辑 -->
    <FormShelve v-if="showShelve" v-model:show="showShelve" v-model="rowShelve" :title="shelveTitle" @submit="submitFormShelveAdd" />
    <FormShelve v-if="showShelveEdit" v-model:show="showShelveEdit" v-model="rowShelveEdit" :title="shelveTitle" @submit="submitFormShelveEdit" />
</template>
<script setup lang="ts">
import { WarehouseAddDTO, WarehouseShelfAddDTO } from './index';
import { useClientRequest } from '@/utils/request';
import FormShelve from './models/form-shelve.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_warehouse_type } = toRefs<any>(proxy?.useDict('pt_warehouse_type'));

const upFormRef = ref();
const paging = ref();
const did = ref<string>('');

const form = ref<WarehouseAddDTO>({
    warehouseName: '',
    sn: '',
    type: '',
    contactName: '',
    tel: '',
    address: '',
    area: undefined,
    storageCondition: '',
    extraInfo: '',
    remark: '',
    shelves: [],
});

const rules = {
    warehouseName: [{ required: true, message: '请输入库房名称', trigger: ['blur', 'change'] }],
    type: [{ required: true, message: '请选择库房类型', trigger: ['change'] }],
    tel: [
        {
            validator: (rule: any, value: string) => {
                if (!value) return true;
                return /^\d[\d-]{5,20}$/.test(value);
            },
            message: '联系电话格式不正确',
            trigger: ['blur', 'change'],
        },
    ],
    area: [
        {
            validator: (rule: any, value: any) => {
                if (value === undefined || value === null || value === '') return true;
                return Number(value) >= 0;
            },
            message: '面积需为非负数',
            trigger: ['blur', 'change'],
        },
    ],
};

const loadDetail = async (id: string) => {
    if (!id) return;
    const res = await useClientRequest.get(`/plt-api/app/warehouse/getInfoById/${id}`);
    if (res && res.code === 200) {
        const data = res.data || {};
        // 仅映射已知字段，避免污染
        form.value = {
            warehouseName: data.warehouseName || '',
            sn: data.sn || '',
            type: data.type || '',
            contact: data.contact || '',
            contactName: data.contactName || '',
            tel: data.tel || '',
            address: data.address || '',
            area: data.area || '',
            storageCondition: data.storageCondition || '',
            extraInfo: data.extraInfo || '',
            remark: data.remark || '',
            shelves: data.shelves || [],
        } as WarehouseAddDTO;
    }
};

const submit = async () => {
    try {
        await upFormRef.value?.validate();
    } catch (error: any) {
        // 滚动到第一个错误字段
        const firstErrorField = error && error[0].prop + 'pppp';
        paging.value?.scrollIntoViewById(firstErrorField, 30, true);
        return;
    }
    try {
        await uni.showLoading({ title: did.value ? '保存中...' : '提交中...', mask: true });
        const url = did.value ? '/plt-api/app/warehouse/update' : '/plt-api/app/warehouse/add';
        const payload = { ...(form.value as any) };
        if (did.value) payload.id = did.value;
        const res = await useClientRequest.post(url, payload);
        uni.hideLoading();
        if (res && res.code === 200) {
            uni.showToast({ title: did.value ? '保存成功' : '新增成功', icon: 'success' });
            uni.$emit('refreshStorageRoomList');
            uni.$emit('storage-room-detail-refresh');
            setTimeout(() => uni.navigateBack(), 300);
        }
    } catch (e) {
        uni.hideLoading();
        console.error('保存库房失败:', e);
    }
};
const selectStorageMember = () => {
    uni.$on('selectCpyMember', (item: any) => {
        form.value.contact = item.userInfo?.id;
        form.value.contactName = item.userInfo?.name;
        form.value.tel = item.userInfo?.phone;
        uni.$off('selectCpyMember');
    });
    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/select-cpy-member/index',
    });
};

// 货位增删改
const shelveOptions = ref([
    { text: '编辑', name: 'edit', style: { backgroundColor: '#37a954', color: '#fff' } },
    { text: '删除', name: 'delete', style: { backgroundColor: '#FF3B30', color: '#fff' } },
]);
const showShelve = ref(false);
const showShelveEdit = ref(false);
const shelveTitle = ref('添加货位');
const rowShelve = ref<WarehouseShelfAddDTO>({ shelvesName: '', sn: '', remark: '', warehouseId: 0 });
const rowShelveEdit = ref<WarehouseShelfAddDTO>({ shelvesName: '', sn: '', remark: '', warehouseId: 0 });
const rowShelveEditIdx = ref<number>(-1);

const addShelve = () => {
    rowShelve.value = { shelvesName: '', sn: '', remark: '', warehouseId: did.value ? Number(did.value) : 0 };
    shelveTitle.value = '添加货位';
    showShelve.value = true;
};
const clickShelveSwipe = (e: any, item: WarehouseShelfAddDTO, idx: number) => {
    const index = e.index;
    if (index === 0) {
        // 编辑
        shelveTitle.value = '编辑货位';
        rowShelveEdit.value = { ...(item || {}) } as WarehouseShelfAddDTO;
        rowShelveEditIdx.value = idx;
        showShelveEdit.value = true;
    }
    if (index === 1) {
        // 删除
        form.value.shelves?.splice(idx, 1);
    }
};
const submitFormShelveAdd = (data: WarehouseShelfAddDTO) => {
    form.value.shelves?.push({ ...data });
};
const submitFormShelveEdit = (data: WarehouseShelfAddDTO) => {
    if (rowShelveEditIdx.value === -1) return;
    form.value.shelves![rowShelveEditIdx.value] = { ...data };
};
onLoad((options: any) => {
    did.value = options?.id || '';
    if (did.value) {
        loadDetail(did.value);
    }
    paging.value?.complete();
});
</script>
<style lang="scss" scoped>
.startline-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}
.base-bottom-wrap {
    background-color: #fff;
}
.plot-item {
    border: 1rpx solid rgba($u-primary, 0.4);
    border-radius: 10rpx;
}
</style>
