import merchant from "@/api/https/merchant"
import { setStorage,getStorage } from '@/utils/storage'
import toast from '@/utils/toast'
import { onLoad, onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { onBeforeUnmount, Ref, ref } from 'vue'
import useGlobalFunc from '@/composables/useGlobalFunc'
import shopping from '@/api/https/shopping'

export default function waitGoodsDetaile() {
    const { copyInfo } = useGlobalFunc()
    /**
     * 接收数据
     */
    interface GoodsInfoType {
        nameID: number
        skuID: number
        goodsName: string
    }
    const goodsInfo = ref<GoodsInfoType>({
        nameID: 0,
        skuID: 0,
        goodsName: '商品名字'
    })
    const goodsTotalCount = ref<number>(0)
    onLoad(async (options) => {
        goodsInfo.value.nameID = options?.nameID
        goodsInfo.value.skuID = options?.skuID
        goodsInfo.value.goodsName = options?.goodsName
        await GetStoresSkus()
    })

    let onPullDownRefreshTimer: any = null
    onPullDownRefresh(() => {
        clearTimeout(onPullDownRefreshTimer)
        onPullDownRefreshTimer = setTimeout(async () => {
            uni.stopPullDownRefresh()
            await GetStoresSkus()
        }, 500)
    })

    /**
     * 通过nameID获取商品
     */
    interface SkuNameType {
        img: string
        prefix: string
        unit: string
        name: string
        unitPrice: number
        auditUnitPrice: number
    }
    const skuName: Ref = ref<SkuNameType>({
        img: '',
        prefix: '',
        unit: '',
        name: '',
        unitPrice: 0,
        auditUnitPrice: 0,
    })
    async function GetStoresSkus() {
        let data = {
            storeIDs: JSON.stringify([getStorage('storeID')]),
            isFocus: true,
            nameIDs: JSON.stringify([+goodsInfo.value.nameID]),
            fromStatus: 0,
            toStatus: 1,
        }
        let goodsDetailRes = await merchant.get_stores_skus(data)
        if (goodsDetailRes.code == 0) {
            goodsTotalCount.value = goodsDetailRes.data.totalCount
            if(goodsDetailRes.data.totalCount == 0) {
                uni.jxConfirm({
                    title: '提示',
                    content: `未创建该商品，请先创建该商品，商品名字：【${goodsInfo.value.goodsName}】`,
                    success: () => {
                        uni.navigateTo({url:'/subPages/shoppingChild/createGoods/createGoods',
                        success: () => {
                            copyInfo(goodsInfo.value.goodsName, '商品名字复制成功')
                        }})
                    }
                })
            } else {
                skuName.value = goodsDetailRes.data.skuNames[0]
            }
        } else {
            toast('商品数据异常', 2)
        }
    }

    const popupDialog = ref<any>(null)
    const skuNameItem = ref<AnyObject>({
        payload:{
            nameID:0,
            Skus:[],
        },
        name:'',
        type:'price'
    })
    const stockOrCode = ref('')
    // 修改库存确认
    async function sureStockOrCode() {
        const nameID = skuNameItem.value.payload.nameID
        const skuID = skuNameItem.value.payload.Skus[0].skuID
        let data:AnyObject = {
            storeIDs: JSON.stringify([+getStorage('storeID')])
        }
        if(skuNameItem.value.type === 'stock') {
            data.payload = JSON.stringify([{
                nameID: nameID,
                Skus:[{skuID: skuID,stock: +stockOrCode.value}]
            }])
        }else{
             data.payload = JSON.stringify([{
                nameID: nameID,
                Skus:[{skuID:skuID,locationCode: ''+ stockOrCode.value ? '' + stockOrCode.value : 'EMPTY_VALUE'}]
            }])
        }
        let res = await shopping.update_stores_skus(data)
        if (res.code == 0) {
            refresh(skuName.value.id)
            setStorage("reLoadOrderDetail", true )
            toast('修改成功')
        }
        popupDialog.value.close() // 关闭 popupDialog
    }

    // 打开dialog 修改库存以及货架码
    function openDialog(payload: AnyObject) {
        skuNameItem.value = payload
        const sku = payload.payload.Skus[0]
        if(payload.type === 'stock') stockOrCode.value = sku.stock + ''
        if(payload.type === 'locationCode') stockOrCode.value = sku.locationCode
        popupDialog.value.open()
    }

    /**
     * 刷新状态
     */
    function refresh(id: number) {
        goodsInfo.value.nameID = id
        GetStoresSkus()
    }

    onBeforeUnmount(() => {
        clearTimeout(onPullDownRefreshTimer)
    })

    return {
        skuName,         // 商品skuName
        goodsInfo,       // nameID and skuID
        refresh,         // 刷新状态
        goodsTotalCount, // 商品数量
        skuNameItem,     // 修改商品当前的数据
        popupDialog,     // 弹窗 stock locationCode
        sureStockOrCode, // 弹窗确认 sure
        stockOrCode,     // 库存 或 货架码
        openDialog       // 打开弹框
    }
}