/**
 * 营业数据
 */

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


export default function orderRealTime() {
    const { globGetToDay } = useGlobalFunc()
    const { singleCalcPrice } = useGlobalFunc()

    /*************************************************
     * 接收参数
    */
    const isNotQuote = ref<boolean>(true)
    const isZero = ref<boolean>(true)
    const isUpperfif = ref<boolean>(true)
    onLoad((options) => {
        _vendorPayPercentage.value = options!._vendorPayPercentage
        isNotQuote.value = JSON.parse(options!.isNotQuote)
        isZero.value = JSON.parse(options!.isZero)
        isUpperfif.value = JSON.parse(options!.isUpperfif)
    })

    /**
     * 获取平台数据-平台名称
     */
    onLoad(async () => {
        await getPlatformList()
        await tabClick(0)
        await getFromTime()   // 获取营业概况数据
        await getToDay()      // 获取今日数据
    })


    /*************************************************
     * 平台列表数据
    */
    const vendorArr = ref<Array<AnyObject>>([
        {
            vendorID: -1,
            vendorStoreName: '全部'
        }
    ])

    /*************************************************
     * 切换平台更新数据
     */
    const pickValue = ref<string>('0')   // 代码高亮
    async function handleVendorChange(e: AnyObject) {
        pickValue.value = e.detail.value
        await changeStatus(active.value)
        await getFromTime()   // 获取营业概况数据
        await getToDay()      // 获取今日数据
    }


    /*************************************************
     * 获取今日数据
    */
    const toDaySaleInfo = ref<AnyObject>({})
    async function getToDay() {
        let fromTime = `${timeFormatD()} 00:00:00`;
        let toTime = `${timeFormatD()} 23:59:59`;
        let data = {
            storeIDs: `[${parseInt(getStorage("storeID"))}]`,
            fromTime,
            toTime,
            statuss:JSON.stringify([110])
        };
        let toDay = await globGetToDay(data)
        if (!toDay) toDay = []
        toDaySaleInfo.value = filterSaleInfo(toDay)
    }


    /*************************************************
     * 分时间段获取营业数据-营业概况
    */
    const saleInfo = ref<AnyObject>({})
    async function getFromTime() {
        let data = {
            storeIDs: `[${parseInt(getStorage("storeID"))}]`,
            fromTime: `${fromTime.value} 00:00:00`,
            toTime: `${toTime.value} 23:59:59`,
            statuss:JSON.stringify([110]) // 只统计已完成的订单，不包含取消单
        }
        let toDay = await globGetToDay(data)
        if (!toDay) toDay = []
        saleInfo.value = filterSaleInfo(toDay)
    }


    /*************************************************
     * 过滤今日营业数据
     */
    const isAllplatfrom = ref<boolean>(true)
    const checkVendorID = ref<number>(0)
    function filterSaleInfo(arr: Array<AnyObject>) {
        let vendorID = vendorArr.value[+pickValue.value].vendorID
        checkVendorID.value = vendorID
        let actualPayPrice = 0
        let realEarningPrice = 0
        let earningPrice = 0
        let shopPrice = 0
        let count = 0
        let cancelCount = 0
        let afsPrice = 0
        let afsCount = 0
        let waybillTipMoney = 0
        let distanceFreightMoney = 0
        let actualFee = 0
        let serverFee = 0       // 报价门店，管理费

        // 全部
        if (vendorID === -1) {
            arr.forEach((item) => {
                waybillTipMoney += item.waybillTipMoney
                serverFee += item.serverFee
                if (item.status === 110) {
                    distanceFreightMoney += item.distanceFreightMoney
                    realEarningPrice += item.platformSettlement
                    earningPrice += item.earningPrice
                    shopPrice += item.shopPrice
                    count += item.count
                    actualPayPrice += item.actualPayPrice
                    actualFee += item.actualFee
                } else if (item.status === 115) {
                    cancelCount += item.count
                } else if (item.status < 0) {
                    afsPrice += item.earningPrice
                    afsCount += item.count
                }
            })
            isAllplatfrom.value = true
        } else {
            // 走平台过滤
            arr.forEach((item) => {
                waybillTipMoney += item.waybillTipMoney
                serverFee += item.serverFee
                if (item.status === 110 && item.vendorID === vendorID) {
                    distanceFreightMoney += item.distanceFreightMoney
                    realEarningPrice += item.platformSettlement
                    earningPrice += item.earningPrice
                    shopPrice += item.shopPrice
                    count += item.count
                    actualPayPrice += item.actualPayPrice
                    actualFee += item.actualFee
                }
                if (item.status === 115 && item.vendorID === vendorID) {
                    cancelCount += item.count
                }
                if (item.status < 0 && item.vendorID === vendorID) {
                    afsPrice += item.earningPrice
                    afsCount += item.count
                }
            })
            isAllplatfrom.value = false
        }

        actualFee = +(actualFee / 100).toFixed(2)

        return {
            actualPayPrice,
            earningPrice,
            shopPrice,
            count,
            cancelCount,
            afsPrice,
            afsCount,
            waybillTipMoney,
            distanceFreightMoney,
            realEarningPrice,
            actualFee,
            serverFee
        }
    }


    /*************************************************
     * 获取门店信息
    */
    const _vendorPayPercentage = ref<number>(0)
    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
        } else {
            _vendorPayPercentage.value = 0
        }
    }


    /*************************************************
     * 平台名称
    */
    async function getPlatformList() {
        let data = {
            storeID: getStorage('storeID')
        }
        let platformRes = await merchant.get_stores(data)
        if (platformRes.code == 0) {
            let serveInfo:AnyObject = configCms.serveInfo
            let storeData = platformRes.data.stores[0]
            storeData.StoreMaps.forEach((element: AnyObject) => {
                vendorArr.value.push({
                    vendorID: element.vendorID,
                    vendorStoreName: `${serveInfo.vendorName[element.vendorID] ? serveInfo.vendorName[element.vendorID] : '未知平台'}`,
                    vendorPayPercentage: element.vendorPayPercentage
                })
            });
        } else {
            toast('平台数据异常', 2)
        }
    }


    /**
     * 打开说明窗口
     */
    function explain() {
        uni.jxAlert({
            title: '说明',
            content: `实际收入: 从当日0时到当前时间的实际获得，不再扣点，已扣除售后退款\r\n 有效订单: 统计时间内，已支付订单中未被取消的订单数量。\r\n取消订单: 统计时间内，取消订单的数量。\r\n订单取消率: 取消订单/(有效订单 + 取消订单)`,
        })
    }


    /*************************************************
     * 营业状况筛选列表
     */
    const tabArr = ref<Array<string>>(["昨日", "近7日", "近30日", "自定义"])


    /*************************************************
     * 营业概况筛选
     */
    const active = ref<number>(0)
    const fromTime = ref('')
    const toTime = ref('')
    async function tabClick(index: number) {
        switch (index) {
            case 0:
                fromTime.value = `${timeFormatD(+new Date().getTime() - 1000 * 60 * 60 * 24)}`
                toTime.value = `${timeFormatD(+new Date().getTime() - 1000 * 60 * 60 * 24)}`
                break
            case 1:
                fromTime.value = `${timeFormatD(+new Date().getTime() - 1000 * 60 * 60 * 24 * 6)}`
                toTime.value = timeFormatD()
                break
            case 2:
                fromTime.value = `${timeFormatD(+new Date().getTime() - 1000 * 60 * 60 * 24 * 29)}`
                toTime.value = timeFormatD()
                break
            case 3:
                fromTime.value = `${timeFormatD(+new Date().getTime() - 1000 * 60 * 60 * 24 * 6)}`
                toTime.value = timeFormatD()
                break

        }
        if (active.value == index) return
        active.value = index
        await changeStatus(active.value)
        await getFromTime()  // 营业概况数据
    }


    /*************************************************
     * 自定义开始日期
     */
    function fnChangeFrom(e: AnyObject) {
        fromTime.value = e.detail.value
    }
    // 自定义结束时间
    function fnChangeTo(e: AnyObject) {
        toTime.value = e.detail.value
    }


    /*************************************************
     * 实际收益
    */
    const isPointStore = computed(() => {
        return store.getters['storeInfo/isPointStore']
    })
    const price = computed(() => {
        if (isYesterday.value) {
            if (saleInfo.value.count) {
                //订单量不为0
                //单平台
                let calcData = {
                    vendorPayPercentage: _vendorPayPercentage.value,
                    actualPayPrice: saleInfo.value.actualPayPrice,
                    shopPrice: saleInfo.value.shopPrice,
                    isPointStore: isPointStore.value,
                    earningPrice: saleInfo.value.earningPrice,
                }
                return singleCalcPrice(calcData)
            } else {
                //订单量为0
                return 0
            }
        } else if (!isYesterday.value) {
            if (isPointStore.value) {
                //扣点
                return saleInfo.value.realEarningPrice
                    ? (saleInfo.value.realEarningPrice / 100).toFixed(2)
                    : 0
            } else {
                //报价
                return saleInfo.value.shopPrice
                    ? (saleInfo.value.shopPrice / 100).toFixed(2)
                    : 0
                // return saleInfo.value.earningPrice
                // ? (saleInfo.value.earningPrice / 100).toFixed(2)
                // : 0
            }
        }
    })


    /*************************************************
     * 结算类型
    */
    const vendortitle = computed(() => {
        if (isYesterday.value) {
            if (isPointStore.value) {
                return '实际支付'
            } else {
                if (
                    _vendorPayPercentage.value != 0 &&
                    _vendorPayPercentage.value < 50
                ) {
                    //扣点
                    return '实际支付'
                } else {
                    //报价
                    return '实际收入'
                }
            }
        } else {
            if (isPointStore.value) {
                //扣点
                return '平台结算'
            } else {
                //报价
                return '实际收入'
            }
        }
    })


    /*************************************************
     * 获取判断条件
    */
    const isYesterday = ref<boolean>(true)
    async function changeStatus(index: number) {
        await getStoreVendorMaps(checkVendorID.value)
        index == 0 ? (isYesterday.value = true) : (isYesterday.value = false)
    }


    /*************************************************
     * 配送小费
    */
    const waybillTipMoney = computed(() => {
        return saleInfo.value.waybillTipMoney
            ? (saleInfo.value.waybillTipMoney / 100).toFixed(2)
            : '0.00'
    })


    /*************************************************
     * 扣点：远距离配送费
     * 报价：服务费   * 远距离配送费
    */
    const distanceFreightMoney = computed(() => {
        if(isPointStore.value){
            // 扣点
            return saleInfo.value.distanceFreightMoney
            ? (saleInfo.value.distanceFreightMoney / 100).toFixed(2)
            : '0.00'
        }else{
            // 报价
            return saleInfo.value.serverFee
            ? (saleInfo.value.serverFee / 100).toFixed(2)
            : '0.00'
        }
    })


    /*************************************************
    * 售后退款
   */
    const afsPrice = computed(() => {
        return saleInfo.value.afsPrice
            ? (saleInfo.value.afsPrice / 100).toFixed(2)
            : '0.00'
    })


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


    return {
        vendorArr,          // 平台列表
        handleVendorChange,        // 切换平台
        explain,                   // 今日订单说明窗口
        tabArr,                    // 营业概况选择列表
        active,                    // 列表高亮
        tabClick,                  // 营业概况筛选
        fromTime,                  // 开始时间
        toTime,                    // 结束时间
        saleInfo,                  // 今日概况数据
        fnChangeFrom,              // 自定义开始时间
        fnChangeTo,                // 自定义结束时间
        pickValue,                 // 平台内容
        getFromTime,               // 查询订单
        toDaySaleInfo,              // 今日订单数据
        isAllplatfrom,
        isNotQuote,
        _vendorPayPercentage,
        isZero,
        isUpperfif,
        price,
        vendortitle,
        waybillTipMoney,
        distanceFreightMoney,
        afsPrice,
        isPointStore
    }
}