<template>
    <root-portal>
        <up-popup :show="show" mode="right" @close="close">
            <view class="w-680 p-rtv" style="height: 100vh">
                <z-paging ref="paging" v-model="list" bgColor="#fff" :fixed="false" @query="query" safe-area-inset-bottom hide-no-more-inside :show-loading-more-no-more-view="false">
                    <template #top>
                        <up-navbar :fixed="false" border>
                            <template #left>
                                <view class="f-s-34 c-#333 f-w-500">{{ title }}</view>
                            </template>
                        </up-navbar>
                    </template>
                    <template>
                        <view>
                            <template v-for="item in list" :key="item?.id">
                                <view @click="expandeds[item?.id] = !expandeds[item?.id]" class="pd-24 d-flex bg-#f7f7f7 btn-row-box a-c">
                                    <view>
                                        <up-checkbox :label="item?.warehouseName" iconSize="36rpx" v-model:checked="aloneCheckeds[item.id]" labelSize="28rpx" name="agree" usedAlone> </up-checkbox>
                                    </view>
                                    <view class="flex1 ov-hd j-ed d-flex">
                                        <up-icon size="30rpx" color="#333" name="arrow-down"></up-icon>
                                    </view>
                                </view>
                                <view v-show="expandeds[item?.id]" class="pd4-12-24-12-60">
                                    <SelectShelvesInput :warehouseId="item.id" :warehouseName="item.warehouseName" :expandeds="expandeds" @changeIdNameMap="changeIdNameMap">
                                        <template #default="{ list }">
                                            <template v-for="(sitem, index) in list" :key="sitem?.id">
                                                <view class="pd2-6-12">
                                                    <up-checkbox :label="sitem?.shelvesName" iconSize="36rpx" v-model:checked="aloneCheckeds[item.id + '-' + sitem.id]" labelSize="28rpx" name="agree" usedAlone></up-checkbox>
                                                </view>
                                            </template>
                                        </template>
                                    </SelectShelvesInput>
                                </view>
                            </template>
                        </view>
                    </template>
                    <!-- 空数据处理 -->
                    <template #empty>
                        <ut-empty class="mg-at" size="28rpx" color="#999" padding="10rpx">
                            <view>暂未设置细分库房，如由需要， </view>
                            <view>可前往<span class="c-primary">仓储-库房管理</span>里进行设置 </view>
                        </ut-empty>
                    </template>
                    <template #bottom>
                        <view class="pd-24 bg-#fff d-flex">
                            <up-button @click="close" class="mr-30" color="#F2F2F2" style="color: #333">取消</up-button>
                            <up-button @click="confirmSelection" type="primary">确认选择</up-button>
                        </view>
                    </template>
                </z-paging>
            </view>
        </up-popup>
    </root-portal>
</template>
<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import SelectShelvesInput from '../select-shelves-input/select-shelves-input.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_cus_type, pt_cpy_type } = toRefs<any>(proxy?.useDict('pt_cus_type', 'pt_cpy_type'));
const paging = ref();
const props = defineProps({
    params: {
        type: Object,
        default: () => ({}),
    },
    show: {
        type: Boolean,
        default: false,
    },
    modelValue: {
        type: Array,
        default: () => [],
    },
    title: {
        type: String,
        default: '选择存放库房',
    },
});
const aloneCheckeds = reactive<{ [key: string]: boolean }>({});
// 展开收起对象
const expandeds = reactive<{ [key: string]: boolean }>({});
const form = ref({});
const emit = defineEmits(['update:show', 'confirm', 'update:modelValue']);
const list = ref<any[]>([]);
const query = async (pageNum: number, pageSize: number) => {
    const params = {
        pageNum,
        pageSize,
        ...props.params,
        ...form.value,
    };
    const res = await useClientRequest.get<any>('/plt-api/app/warehouse/pageList', params);
    if (!res || res.code !== 200) return;
    const { rows } = res;
    // 构建id名称映射
    rows.forEach((item: any) => {
        idNameMap[item.id] = {
            warehouseName: item.warehouseName,
            warehouseId: item.id,
        };
    });
    paging.value?.complete(rows);
};
// 根据id获取名称的对象
const idNameMap = reactive<{ [key: string]: { warehouseName?: string; shelvesName?: string; warehouseId?: string; shelfId?: string } }>({});
const confirmSelection = () => {
    console.log(aloneCheckeds);
    console.log(idNameMap);
    const values: any[] = [];
    Object.keys(aloneCheckeds).forEach((key) => {
        if (aloneCheckeds[key]) {
            const names = idNameMap[key];
            if (names) {
                values.push({
                    id: key,
                    warehouseName: names.warehouseName,
                    shelvesName: names.shelvesName,
                    warehouseId: names.warehouseId,
                    shelfId: names.shelfId,
                });
            }
        }
    });
    emit('update:modelValue', values);
    emit('confirm', values);
    close();
};
const changeIdNameMap = (map: { [key: string]: { shelvesName: string; warehouseName: string } }) => {
    Object.assign(idNameMap, map);
};
const close = () => {
    emit('update:show', false);
};
watch(
    () => props.modelValue,
    (val) => {
        // 初始化选中状态
        Object.keys(aloneCheckeds).forEach((key) => {
            delete aloneCheckeds[key];
        });
        val.forEach((item: any) => {
            // warehouseId-shelfId warehouseName or warehouseId shelvesName
            expandeds[item.warehouseId] = true;
            aloneCheckeds[item.warehouseId + (item.shelfId ? '-' + item.shelfId : '')] = true;
            idNameMap[item.warehouseId + (item.shelfId ? '-' + item.shelfId : '')] = {
                warehouseName: item.warehouseName,
                shelvesName: item.shelvesName,
                warehouseId: item.warehouseId,
                shelfId: item.shelfId,
            };
        });
    },
    { immediate: true },
);
</script>
<style scoped lang="scss">
.btn-row-box {
    margin-top: -1rpx;
    border: 1rpx solid #e6e6e6;
}
</style>
