<template>
    <app-view>
        <template #header>
            <app-navbar title="我的库存" />
        </template>
        <app-pull-refresh ref="pullRefreshRef" v-model:loading="loading" v-model:error="error"
            v-model:pageIndex="pageIndex" :page-count="pageCount" @refresh="run">
            <div class="g-order-list">
                <div class="g-order-list__box" v-for="(item, index) in dataList" :key="index">
                    <div class="g-order-list__titlebar">
                        <div class="left">
                            <h4>{{ item.goodsname }}</h4>
                        </div>
                        <div class="right">
                            <span>数量：{{ item.curqty }}{{ item.goodunit }}</span>
                        </div>
                    </div>
                    <div class="g-order-list__btnbar">
                        <Button size="small" @click="showComponent('inOut', item, 1)" round>入库申请</Button>
                        <Button size="small" @click="showComponent('inOut', item, 2)" round>出库申请</Button>
                        <Button size="small" @click="showComponent('logs', item, 1)" round>申请记录</Button>
                    </div>
                </div>
            </div>
        </app-pull-refresh>
        <component ref="componentRef" v-bind="{ selectedRow, inOutType }" :is="componentMap.get(componentId)"
            @closed="closeComponent" v-if="componentId" />
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, defineAsyncComponent } from 'vue'
import { Button } from 'vant'
import { useRequest } from '@/hooks/request'
import { queryUserGoodsInventory } from '@/services/api/order'
import { useComponent } from '@/hooks/component'
import AppPullRefresh from '@mobile/components/base/pull-refresh/index.vue'

const componentMap = new Map<string, unknown>([
    ['logs', defineAsyncComponent(() => import('./components/logs/index.vue'))], // 申请记录
    ['inOut', defineAsyncComponent(() => import('./components/inOut/index.vue'))], // 申请记录
])

const error = shallowRef(false)
const dataList = shallowRef<Model.UserGoodsInventoryRsp[]>([])
const selectedRow = shallowRef<Model.UserGoodsInventoryRsp>()
const inOutType = shallowRef(1)

const { componentRef, componentId, openComponent, closeComponent } = useComponent()

const { loading, pageIndex, pageCount, run } = useRequest(queryUserGoodsInventory, {
    onSuccess: (res) => {
        if (pageIndex.value === 1) {
            dataList.value = []
        }
        dataList.value.push(...res.data)
    },
    onError: () => {
        error.value = true
    }
})

const showComponent = (componentName: string, row: Model.UserGoodsInventoryRsp, type: number) => {
    inOutType.value = type
    selectedRow.value = row
    openComponent(componentName)
}
</script>