/**
 * options 选项
 */
import toast from "@/utils/toast"
import { store } from '@/store'
import { timeFormatD } from "@/utils/tools"
import { getStorage } from "@/utils/storage"
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app"
import { Ref, ref, onBeforeUnmount,watch } from "vue"
import merchant from "@/api/https/merchant"
import useGlobalFunc from '@/composables/useGlobalFunc'
import order from "@/api/https/order"

function options() {
    const { openWeixin, watchVersion } = useGlobalFunc()


    /**
     * 进入群聊
     */
    function getGroupChat() {
        openWeixin('subPages/merchantChild/enterGroupChat/enterGroupChat')
    }

    /**
     * 注册时间
     */
    async function getSelfInfo() {
        let infoRes = await merchant.get_self_info()
        if (infoRes.code == 0) {
            let time1 = Math.floor((+new Date() - +new Date(infoRes.data.createdAt)) / 1000 / 24 / 3600)
            let time2 = Math.floor((+new Date() - +new Date(store.state.storeInfo.createStoreTimer)) / 1000 / 24 / 3600)
            uni.jxAlert({
                title: '回首过往',
                content: `门店ID:${getStorage('storeID')}\r\n\r\n您注册于${timeFormatD(infoRes.data.createdAt)}\r\n来到京西${time1}天\r\n\r\n门店创建于${timeFormatD(store.state.storeInfo.createStoreTimer)}\r\n在平台经营${time2}天`
            })
        } else toast('注册数据异常', 2)
    }


    /**
     * 物料申请
     */
    function moveToWM() {
        let tel = store.state.storeInfo.allStoreInfo.marketManPhone ? store.state.storeInfo.allStoreInfo.marketManPhone : "18048531223"
        if (getStorage('terrace') != 'jxcs') {
            // 果园禁止物料跳转
            uni.jxAlert({
                title: '物料申请',
                content: `非常抱歉，无法进入物料商城，请联系运营${tel}`
            })
            return
        } else {
            if (store.state.storeInfo.allStoreInfo.packageSwitch === 1) {
                uni.jxAlert({
                    title: '物料申请',
                    content: `非常抱歉，无法进入物料商城，请联系运营${tel}`
                })
                return
            }
        }

        if (store.state.storeInfo.storeStatus === -2) {
            uni.jxAlert({
                title: '物料申请',
                content: '门店已被禁用，请联系运营'
            })
        }
        openWeixin(`pages/index/index?storeID=666666&fromStoreID=${getStorage('storeID')}&storeType=c4`, 'gh_0d7e2243b51f')
    }

    /**
     * 查询是否有新账单
     */
    const isInstallWx = ref<boolean>(false) // 是否安装微信
    onLoad(async () => {
        if (plus.runtime.isApplicationExist({ pname: 'com.tencent.mm', action: 'weixin://' })) {
            isInstallWx.value = true
        } else {
            isInstallWx.value = false
        }
        await handleMsg()
        await tmpGetJxBadCommentsNo()
        await getMessageData()
    })
    // 处理新账单
    const billUrl: Ref<string | undefined | object[]> = ref('')
    const newBillShow: Ref<boolean> = ref(false)        // 是否有新帐单
    function handleMsg() {
        getStoreBills((url: Array<object> | string) => {
            if (typeof (url) == 'string') {
                billUrl.value = url
                // 保存新账单url地址 （存vuex）
                store.commit('serveInfo/setOrderUrl', url)

                // 查询本地账单地址
                if (getStorage('newBillUrl') !== billUrl.value) {
                    // 有新账单
                    newBillShow.value = true
                } else {
                    // 没有新帐单
                    newBillShow.value = false
                }
            }
        })
    }
    // 查询新订单
    interface BillListType {
        billName: string
        billTitle: string
        date: string
        id: number
        shopName: string
        storeId: string
        url: string
    }
    const billList = ref<Array<BillListType>>([])
    async function getStoreBills(fn: Function) {
        let data = {
            storeID: getStorage('storeID')
        }
        let newOrderRes = await merchant.get_store_bills(data)
        if (newOrderRes.code == 0) {
            let newMsg: Array<object> | string = []
            if (newOrderRes.data != null) {
                billList.value = newOrderRes.data.slice(0, 5)
                billList.value = billList.value.map((bill) => {
                    let time = bill.date
                    bill.date = timeFormatD(time)
                    return bill
                })
                newMsg = newOrderRes.data[0].url.trim()
                fn && fn(newMsg)
            } else {
                billList.value = []
                fn && fn(newMsg)
            }
        } else {
            toast('账单数据异常', 2)
        }
    }


    /**
     * 是否有新信息
     */
    const msgCount = ref<number>(0)
    async function getMessageData() {
        let data = {
            storeIDs: JSON.stringify([+getStorage('storeID')]),
            fromReadCount: 0,
            toReadCount: 0,
            offset: 0,
            pageSize: -1,
            fromTime:
                timeFormatD(+new Date() - 7 * 24 * 60 * 60 * 1000) + ' 00:00:00',
            toTime: timeFormatD(+new Date()) + ' 23:59:59',
        }
        let msgRes = await merchant.Get_store_message_statuses(data)
        if (msgRes.code == 0) {
            msgCount.value = msgRes.data.totalCount
        } else {
            toast('消息数据异常')
        }
    }


    /**
     * 获取差评数量
     */
    let badCommentCount: Ref<number | string> = ref(0)
    async function tmpGetJxBadCommentsNo() {
        let data = {
            jxStoreId: getStorage('storeID')
        }
        let evaluateMRes = await merchant.tmp_get_jx_bad_comments_no(data)
        if (evaluateMRes.code == 0) {
            badCommentCount.value = evaluateMRes.data ?  evaluateMRes.data : 0
        } else toast('差评数据异常', 2)
    }

    watch(() =>  store.getters['storeInfo/imMtStatus'],
    (val) => {
        if(val && val.length>0) getInvoiceInfo()
    })

    /**
     * 发票数量
     */
    const invoiceCount:Ref<number | string> = ref(0)
    async function getInvoiceInfo() {
        // if(store.getters['storeInfo/imEbStatus'] && store.getters['storeInfo/imEbStatus'].length>0){
        //   // 存在饿百门店
        // }
        // 美团们门店
        if(store.getters['storeInfo/imMtStatus'] && store.getters['storeInfo/imMtStatus'].length>0) {
            let data:AnyObject = {
                storeId: getStorage('storeID'),
                startTime: `${timeFormatD(+new Date() - 7 * 24 * 60 * 60 * 1000)}` + ' 00:00:00',
                endTime:`${timeFormatD()}` + ' 23:59:59',
                pageSize: -1,
                offset: 0
            }
            let res = await order.query_mt_invoice(data)
            invoiceCount.value = res.data.totalCount
        }
    }

    /**
     * 打开小程序
     */
    function openAppOrApplet() {
        openWeixin('pages/merchant/index')
    }


    /*************************************************
     * 下拉刷新
    */
    let onPullDownRefreshTimer: any = null
    onPullDownRefresh(() => {
        clearTimeout(onPullDownRefreshTimer)
        onPullDownRefreshTimer = setTimeout(async () => {
            uni.stopPullDownRefresh()
            await tmpGetJxBadCommentsNo()
            await getMessageData()
            await handleMsg()
            await getInvoiceInfo()
        }, 1000)
    })


    /**
     * 版本更新
     */
    const isVarsion = ref<boolean>(false)
    function isUpdate(type: number) {
        watchVersion((res: boolean) => {
            if (res) {
                uni.globalAlert({
                    data: {
                        type: 3,
                    },
                })
                isVarsion.value = true
            } else {
                isVarsion.value = false
                if (type == 1) toast('已经是最新版')
            }
        })
    }
    onBeforeUnmount(() => {
        clearTimeout(onPullDownRefreshTimer)
    })


    return {
        getGroupChat,           // 跳转加入群聊
        getSelfInfo,            // 获取门店来京西的时间
        moveToWM,               // 物料申请
        newBillShow,            // 是否有新账单
        billList,               // 账单列表
        msgCount,               // 是否有信息
        badCommentCount,        // 获取差评数量
        invoiceCount,           // 发票数量
        openAppOrApplet,        // app or 小程序
        isVarsion,              // 是否现实新版本
        isUpdate,               // 版本更新   
        isInstallWx,            // 是否安装微信     
    }

}
export default options

