
import { computed, onBeforeUnmount, ref } from 'vue'
import { timeFormatD } from '@/utils/tools'
import { getStorage } from '@/utils/storage'
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import { store } from '@/store'
import useGlobalFunc from '@/composables/useGlobalFunc'
import merchant from "@/api/https/merchant"

/*************************************************
 * 商家中心
*/
const merchantFn = function () {
    const { logOutFn, getMtStoreIMStatus } = useGlobalFunc()

    /*************************************************
     * 下拉刷新
    */
    let onPullDownRefreshTimer: any = null
    onPullDownRefresh(() => {
        clearTimeout(onPullDownRefreshTimer)
        onPullDownRefreshTimer = setTimeout(async () => {
            uni.stopPullDownRefresh()
            await getSaleInfo()
            await getStoreVendorMaps(-1)
            await getCid()
            await getMtStoreIMStatus()  // 获取美团门店的im状态
            clearTimeout(onPullDownRefreshTimer)
        }, 1000)
    })

    /*************************************************
     * cid通知提示
    */
    let cidNotice = ref<boolean>(false)
    async function getCid() {
        let infoRes = await merchant.get_self_info()
        if (infoRes.code == 0) {
            if (getStorage('cid') == infoRes.data.c_id) {
                cidNotice.value = false
            } else {
                cidNotice.value = true
            }
        }
    }


    /*************************************************
     * 页面加载获取数据
    */
    onLoad(async () => {
        await getStoreVendorMaps(-1)
        await getSaleInfo()
        await getCid()
    })


    const saleInfo = ref({
        earningPrice: 0,
        count: 0,
    })

    /*************************************************
     * 获取今日营业数据
    */
    async function getSaleInfo() {
        let fromTime = `${timeFormatD()} 00:00:00`
        let toTime = `${timeFormatD()} 23:59:59`
        let data = {
            storeIDs: `[${parseInt(getStorage('storeID'))}]`,
            fromTime,
            toTime,
            statuss:JSON.stringify([110]) // 只统计已完成的订单，不包含取消单
        }
        await merchant.get_store_order_sale_info(data).then((res) => {
            let json = {
                earningPrice: 0,
                shopPrice: 0,
                realEarningPrice: 0,
                count: 0,
                actualPayPrice: 0,
                actualFee: 0
            }
            if (res.code == 0) {
                let data = res.data || []
                data.forEach((item: AnyObject) => {
                    if (item.status === 110) {
                        json.actualPayPrice += item.actualPayPrice
                        json.realEarningPrice += item.realEarningPrice
                        json.earningPrice += item.earningPrice
                        json.shopPrice += item.shopPrice
                        json.count += item.count
                        json.actualFee += item.actualFee
                    }
                })
                json.actualFee = +(json.actualFee / 100).toFixed(2)
                saleInfo.value = json
            } else {
                saleInfo.value = json
            }
        })
    }


    /*************************************************
     * 获取门店信息数据
    */
    const _vendorPayPercentage = ref<number>(0)
    const isNotQuote = ref<boolean>(true)
    const isZero = ref<boolean>(true)
    const isUpperfif = ref<boolean>(false)
    const isShowShop = ref<boolean>(false)
    async function getStoreVendorMaps(vendorID: number) {
        let data = {
            storeID: getStorage('storeID'),
            vendorID: vendorID
        }
        let res = await merchant.get_store_vendor_maps(data)
        if (res.code == 0) {
            let data = res.data
            _vendorPayPercentage.value = data[0].vendorPayPercentage
            isNotQuote.value = true
            isNotQuote.value = data.some((item: AnyObject) => {
                return item.vendorPayPercentage != 0 && item.vendorPayPercentage <= 50
            })
            isZero.value = data.every((item: AnyObject) => {
                return item.vendorPayPercentage == 0
            })
            isUpperfif.value = data.every((item: AnyObject) => {
                return item.vendorPayPercentage > 50
            })
            if (isNotQuote.value) {
                isShowShop.value = data.every((v: AnyObject) => {
                    return v.vendorPayPercentage > 50
                })
            }
        } else {
            _vendorPayPercentage.value = 0
        }
    }

    // 系统信息
    function getMsg() {
        uni.removeTabBarBadge({ index: 3 })
        store.commit('storeInfo/setIsNewMessage', false)
        uni.navigateTo({
            url: '/subPages/merchantChild/message/message',
        })
    }

    const isMsg = computed(() => {
        return store.state.storeInfo.isNewMessage
    })


    /*************************************************
     * 退出登录
    */
    function goLogin() {
        uni.showActionSheet({
            title: '退出后不会删除任何数据',
            itemColor: '#e70808',
            itemList: ['重新登录'],
            popover: {
                width: 5000,
            },
            success: function (res) {
                logOutFn();
                // uni.navigateTo({ url: '/subPages/login/wxLogin/wxLogin' })
                uni.reLaunch({ url: '/subPages/login/wxLogin/wxLogin' })
            }
        });
    }


    /*************************************************
     * 做收尾工作
     */
    onBeforeUnmount(() => {
        clearTimeout(onPullDownRefreshTimer)
    })

    return {
        saleInfo,           // 今日订单数据
        _vendorPayPercentage,   // 供应商百分比
        isShowShop,         // 是否为出售金额
        isNotQuote,
        isZero,
        isUpperfif,
        getMsg,
        isMsg,
        goLogin,
        cidNotice,
    }
}

export default merchantFn