import useGlobalFunc from '@/composables/useGlobalFunc'
import { store } from '@/store'
import { getStorage } from '@/utils/storage'
import toast from '@/utils/toast'
import { timeFormatD, jx_trembling } from '@/utils/tools'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { watch, ref, onBeforeUnmount } from 'vue'
import order from "@/api/https/order"
import merchant from "@/api/https/merchant"
/**
 * 订单管理方法
 * @author zhangshuwie <2966211270@qq.com>
 * @param *
 * @return 模板使用数据与方法，详情内容请查看return
 */
function orderInfoFn() {
    const { isTrades } = useGlobalFunc()

    /**
     * 公共复位函数
     */
    function reset() {
        orderDataList.value = []
        page.value = 1
        totalCount.value = 0
    }

    /*************************************************
     * 获取门店信息
    */
    async function getStores() {
        await store.dispatch('storeInfo/getOneStore',getStorage("storeID"))
    }


    /**
     * tab单击事件
     * @param target 点击对应tab获取到的信息
     */
    const status = ref<Array<number>>([10])     // 默认显示待拣货
    const orderState = ref<number>(2)           // 默认显示待拣货
    const orderStateInfo = ref()
    async function jxTabClick(target: AnyObject) {
        orderStateInfo.value = target
        await reset()
        uni.removeTabBarBadge({ index: 0 })
        keyword.value = ''
        // 列表展示判断条件
        orderState.value = target.id
        // 请求数据订单状态
        status.value = target.status
        // 请求数据
        if (target.id == 6) {
            // 获取售后单
            if (orderStateInfo.value.count) {
                allData.value.fromTime = timeFormatD(+new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 2))
                allData.value.afsStatus = '155'
            }
            await getAfsOrders()
        } else {
            await getOrderAllInfo()
        }
    }


    /**
     * 下拉刷新
     */
    let refresherrefreshTimer: any = null
    const triggered = ref<boolean>(false)
    function refresherrefresh() {
        uni.removeTabBarBadge({ index: 0 })
        triggered.value = true
        clearTimeout(refresherrefreshTimer)
        refresherrefreshTimer = setTimeout(async () => {
            triggered.value = false
            await reset()
            await refreshTab()
            if (orderState.value == 5) {
                totalCount.value = 0
            }
            if (orderState.value == 6) {
                await getAfsOrders()
            } else {
                await getOrderAllInfo()
            }
        }, 500)
    }

    /**
     * 页面触底
     */
    const isLoad = ref<boolean>(false)
    async function scrolltolower() {
        uni.removeTabBarBadge({ index: 0 })
        page.value++
        if (pageSize.value * (page.value - 1) > totalCount.value || totalCount.value < pageSize.value) {
            isLoad.value = false
        } else {
            if (isLoad.value) return
            if (orderState.value == 7) {
                await getOrderAllInfo()
            } else {
                await getAfsOrders()
            }
        }
    }


    /**
     * 获取订单详情数据
     */
    type emitType = {
        fromTime: string
        toTime: string
        vendorID: number | string
        waybillVendorID?: number | string
        isDateFinish?: boolean
        appealTypes?: number | string
        afsStatus?: number | string
    }
    let oldStoreID: any = 0


    let battery = ref<boolean>(false)
    let notice = ref<boolean>(false)
    let lockScreen = ref<boolean>(true)
    /*************************************************
     * 安卓通知情况
    */
    onShow(() => {
        let port = uni.getSystemInfoSync().platform
        switch (port) {
            case 'android':
                //电池白名单 res返回值 1为白名单  0为无白名单
                const MyPlugin = uni.requireNativePlugin("RC-NoticeMonitoring")
                MyPlugin.isBatteryOptimizations((res: any) => {
                    res == 1 ? battery.value = false : battery.value = true
                })
                //是否打开了通知权限 返回true和false
                const notify = uni.requireNativePlugin('Ba-Notify')
                notify.isNotifyEnabled((res: any) => {
                    notice.value = !res.isNotifyEnabled
                })
                //是否打开锁屏通知 res返回值 1为有权限  0为无权限
                MyPlugin.isNotification((res: any) => {
                    res == 1 ? lockScreen.value = false : lockScreen.value = true
                })
                break
            case 'ios':
                console.log('iOS不支持此功能')
                break
        }
    })


    /*************************************************
     * 设置来单不响
    */
    function setNotice() {
        uni.navigateTo({ url: '/subPages/merchantChild/backstageApp/backstageApp' })
    }


    /*************************************************
     * 门店休息情况
    */
    const isRest = ref<boolean>(true)
    const isStatu = ref<boolean>(false)
    onShow(async () => {
        uni.removeTabBarBadge({ index: 0 })
        if (!store.state.storeInfo.allStoreInfo.id) {
            await getStores()
        }
        if (oldStoreID != getStorage('storeID') && oldStoreID != 0) {
            await reset()
            triggered.value = true
        }
        oldStoreID = getStorage('storeID')
        isRest.value = isTrades(new Date())     // 门店是否接受预订单
        let storeInfo = store.state.storeInfo.allStoreInfo
        isStatu.value = storeInfo.status == 1 ? true : false
        uni.removeTabBarBadge({ index: 0 })
    })

    const statusBarHeight = ref<string>('0px') // 状态栏高度
    onLoad(async () => {
        // 获取状态栏高度
        uni.getSystemInfo({
            success: (res: any) => {
                statusBarHeight.value = res.statusBarHeight + 'px'
            }
        })
        // 请求数据
        await reset()
        await getOrderAllInfo()
    })
    const pageSize = ref<number>(33)        // 每一页条数
    const page = ref<number>(1)             // 第多少条
    const orderDataList = ref<any>([])      // 订单数据
    const totalCount = ref<number>(0)       // 订单条数
    const allData = ref<emitType>({
        fromTime: timeFormatD(+new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7)),
        toTime: timeFormatD(+new Date()),
        vendorID: '',
        waybillVendorID: '',
        isDateFinish: false,
        appealTypes: '',
        afsStatus: ''
    })         // 已完成数据筛选
    async function getOrderAllInfo() {
        isLoad.value = true
        let time1 = timeFormatD(+new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7))
        let time2 = timeFormatD(+new Date())
        // 待接单、待检货、待配送、配送中、异常单、已完成
        let data: any = {
            fromDate: time1,
            toDate: time2,
            storeIDs: JSON.stringify([getStorage('storeID')]),
            statuss: JSON.stringify(status.value),
            offset: pageSize.value * (page.value - 1),
            pageSize: pageSize.value,
            isJxFirst: true
        }
        if (orderState.value == 7) {
            data = {
                fromDate: allData.value.fromTime ? allData.value.fromTime : time1,
                toDate: allData.value.toTime ? allData.value.toTime : time2,
                storeIDs: JSON.stringify([getStorage('storeID')]),
                statuss: JSON.stringify(status.value),
                offset: pageSize.value * (page.value - 1),
                pageSize: pageSize.value,
                isDateFinish: allData.value.isDateFinish,
                vendorIDs: `[${allData.value.vendorID}]`,
                waybillVendorIDs: `[${allData.value.waybillVendorID}]`,
                isJxFirst: true,
                keyword: keyword.value
            }
        }

        let res = await order.get_orders(keyFilter(data))
        if (res.code == 0) {
            if (page.value <= 1) {
                reset()
            }
            let data: Array<any> = res.data.data || []
            if (data.length == 0) toast('暂无该类型订单')
            orderDataList.value = orderDataList.value.concat(data)
            totalCount.value = res.data.totalCount
        } else {
            await reset()
            totalCount.value = 0

        }
        isLoad.value = false
    }


    /*************************************************
     * 过滤对象空字段
     */
    function keyFilter(obj: AnyObject) {
        for (let key in obj) {
            // if ((obj[key] == "" || obj[key] == [""] || obj[key] == '[-1]')) {
            if ((obj[key] == "" || obj[key] == '[-1]')) {
                delete obj[key]
            }
        }
        return obj
    }


    /**
     * 获取异常单
     */
    async function getAfsOrders() {
        isLoad.value = true
        // 待接单、待捡货、待配送、配送中、异常单、已完成
        let data = {
            storeIDs: JSON.stringify([getStorage('storeID')]),
            fromTime: `${allData.value.fromTime} 00:00:00`,
            toTime: `${allData.value.toTime} 23:59:59`,
            pageSize: pageSize.value,
            offset: pageSize.value * (page.value - 1),
            vendorIDs: `[${allData.value.vendorID}]`,
            appealTypes: `[${allData.value.appealTypes}]`,
            statuss: `[${allData.value.afsStatus}]`,
            isDetail: true,
            keyword: keyword.value
        }
        let res = await order.get_afs_orders(keyFilter(data))
        if (res.code == 0) {
            if (page.value <= 1) {
                reset()
            }
            let data: Array<any> = res.data.data || []
            if (data.length == 0) toast("暂无售后订单")
            orderDataList.value = orderDataList.value.concat(data)
            totalCount.value = res.data.totalCount
        } else {
            await reset()
            totalCount.value = 0
        }
        isLoad.value = false
    }


    /**
     * 刷新导航栏
     */
    const tabInfo = ref<any>(null)
    function refreshTab() {
        tabInfo.value.getOrderCount()
    }


    /**
     * 输入确认按钮
     */
    const keyword = ref<string>('')
    async function searchStore(keywords: string) {
        keyword.value = keywords
        await reset()
        if (orderState.value == 7) {
            await getOrderAllInfo()
        } else {
            await getAfsOrders()
        }
    }


    /**
     * 输入框输入值变化
     */
    let trembling = jx_trembling(getOrderAllInfo, 800)
    let trembling2 = jx_trembling(getAfsOrders, 800)
    async function changeIpt(keywords: string) {
        keyword.value = keywords
        await reset()
        if (orderState.value == 7) {
            await trembling()
        } else {
            await trembling2()
        }
    }


    /**
     * 清空输入框
     */
    async function clearIpt() {
        keyword.value = ''
        await reset()
        if (orderState.value == 7) {
            await getOrderAllInfo()
        } else {
            await getAfsOrders()
        }
    }


    /**
     * 已完成和售后单筛选
     */
    const active = ref<number>(0)
    async function filterData(data: emitType) {
        let ruler = (+new Date() - +new Date(data.fromTime)) / 1000 / 60 / 60 / 24
        if (orderState.value != 7 && ruler > 59) {
            return toast('售后查询不能超过60天')
        }
        if (orderState.value == 7 && ruler > 180) {
            return toast('最大查询天数为180天')
        }
        allData.value = data
        await reset()
        if (orderState.value == 7) {
            await getOrderAllInfo()
        } else {
            await getAfsOrders()
        }
    }

    /**
     * 筛选条件实例对象
     */
    const orderFilterRef = ref<any>(null)

    /**
     * 监听新订单刷新页面
     */
    watch(() => store.state.serveInfo.updateOrder, async () => {
        await reset()
        await refreshTab()
        if (orderState.value == 6) {
            await getAfsOrders()
        } else {
            await trembling()
        }
    })



    /**
     * 动态计算scorll-view 高度
     */
    const scorllHeight = ref<string>('94rpx')
    watch(() => orderState.value, (nweVal) => {
        let arr: Array<number> = [1, 2, 4, 5]
        if (arr.includes(nweVal)) {
            scorllHeight.value = '100rpx'
        } else {
            scorllHeight.value = '190rpx'
        }
    })


    /*************************************************
     * 配送状态筛选
    */
    function distributionStatu(type: number) {
        active.value = type
    }

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



    return {
        jxTabClick,                 // 导航栏按钮
        orderDataList,              // 订单数据
        totalCount,                 // 订单条数
        orderState,                 // 订单列表判断条件
        orderStateInfo,             // 订单列表信息
        tabInfo,                    // 导航栏实例
        searchStore,                // 输入库条件筛选
        keyword,                    // 输入库内容
        changeIpt,                  // 输入款输入变化
        clearIpt,                   // 清空输入框
        scorllHeight,               // 动态计算scorll-view高度
        active,                     // 待配送筛选高亮
        orderFilterRef,             // 筛选条件实例对象
        filterData,                 // 筛选条件数据
        refresherrefresh,           // 下拉刷新
        triggered,                  // 下拉加载
        scrolltolower,              // 页面触底
        isLoad,                     // 触底加载
        distributionStatu,          // 配送筛选
        isRest,                     // 是否显示休息状态
        isStatu,                    // 门店是否在营业
        statusBarHeight,            // 状态栏高度
        battery,                    // 电池
        notice,                     // 通知
        lockScreen,                 // 锁屏
        setNotice,                  // 设置来单不响
    }
}

export default orderInfoFn