import order from "@/api/https/order"
import toast from '@/utils/toast'
import { store } from '@/store'
import { timeFormatHMS, timeFormatDHM, clearList } from '@/utils/tools'
import { onLoad,onShow } from '@dcloudio/uni-app'
import { computed, onBeforeUnmount, ref } from 'vue'
import useOrderInfo from '@/composables/useOrderInfo'
import configCms from "@/utils/configCms"
import { setStorage, getStorage, cleatStorage } from '@/utils/storage'

/**
 * 订单详情
 * @param *
 * @return 模板使用数据与方法，详情内容请查看return
 */
function orderDetailFn() {
    const { phoneCall, afterSalesDetaile } = useOrderInfo()

    /***************************************************************
     * 收集传递信息
     */
    const vendorID = ref<number>(0)
    const vendorOrderID = ref<number>(0)
    onLoad(async (options: any) => {
        vendorID.value = options.vendorID
        vendorOrderID.value = options.vendorOrderID
        await getOrderInfo(options.vendorOrderID) // 获取订单详情
        await getBarCode()  // 获取条形码
        await getWayBill(2)  // 获取运单状态
        await GetAfsOrders()  // 售后单
        await getSkuList()  // 获取商品列表
        await getComplaintList()   // 是否可以投诉骑手
    })

    onShow(() => {
        if(getStorage('reLoadOrderDetail')) getSkuList()
    })

    /***************************************************************
     * 获取订单详情
     * @vendorOrderID {number} 订单号
     */
    const invoiceTitle = ref<string>('')        // 发票抬头
    const invoiceTaxerID = ref<string>('')      // 纳税人ID
    const orderData = ref<AnyObject>({
        vendorID: -99   // 默认值判断，防止页面渲染报错
    })                     // 订单信息1
    async function getOrderInfo(vendorOrderID: number) {
        let res = await order.get_orders({ vendorOrderID })
        if (res.code == 0 && res.data.totalCount) {
            let newData = res.data.data[0]
            if (getStorage('storeID') != newData.jxStoreID) {
                setStorage('storeID', +newData.jxStoreID)
                await store.dispatch('storeInfo/getOneStore', +newData.jxStoreID)
            }
            invoiceTitle.value = newData.invoiceTitle
            invoiceTaxerID.value = newData.invoiceTaxerID
            orderData.value = newData
            GetOrderInfo(newData, vendorOrderID)
        } else {
            uni.jxAlert({
                title: '提示',
                content: '获取订单号信息失败',
                success: () => {
                    uni.navigateBack()
                }
            })
        }
    }
    const orderInfo = ref<AnyObject>({
        vendorID: -99   // 默认值判断，防止页面渲染报错
    })     // 订单信息2
    async function GetOrderInfo(orderData: AnyObject, vendorOrderID: number) {
        let data = {
            vendorOrderID,
            vendorID: orderData.vendorID,
            refresh: false
        }
        let res = await order.get_order_info(data)
        if (res.code == 0) {
            orderInfo.value = res.data
            // 是否是京西新用户
            if (res.data.vendorID == 9) getOrderUserBuyFirst(res.data.vendorOrderID)
        } else {
            uni.jxAlert({
                title: '提示',
                content: '获取订单号信息失败',
                success: () => {
                    uni.navigateBack()
                }
            })
        }
    }
    // 获取条形码
    const barCodeImg = ref<string>('https://image.jxc4.com/image/34e6c3b22b914d7102c99bebfc95f9dd.png')
    async function getBarCode() {
        let data = {
            width: 600,
            height: 200,
            codetype: 'bar',
            srcData: vendorOrderID.value,
        }
        let res = await order.create_qrOr_bar_code(data)
        if (res.code == 0) {
            barCodeImg.value = res.data
        }
    }
    // 查询京西是否是新用户
    const isNewUser = ref<boolean>(false)
    async function getOrderUserBuyFirst(vendorOrderID: number) {
        let res = await order.get_order_user_buy_first({ vendorOrderID })
        if (res.code == 0) {
            isNewUser.value = res.data
        }
    }


    /***************************************************************
     * 订单状态
     */
    const orderType:AnyObject = configCms.serveInfo
    const orderStatus = computed(() => {
        if (orderData.value.status != '') {
            return orderType.orderStatus[orderData.value.status]
        } else {
            return '未知'
        }

    })


    /***************************************************************
     * 取消订单
     */
    function cancelOrder(vendorOrderID: string) {
        uni.jxConfirm({
            title: '提示',
            content: '是否取消该订单',
            success: async () => {
                let data = {
                    vendorOrderID: vendorOrderID,
                    isDetail: true
                }
                let res = await order.getafs_orders(data)
                if (res.code == 0) {
                    handleResData(res.data)
                    if (cancelOrderFail.value) {
                        uni.jxAlert({
                            title: '提示',
                            content: '有待审核的售后单，请先审核售后单再取消订单',
                            success: () => {
                                afterSalesDetaile(res.data.data[0].afsOrderID || 123)
                            }
                        })
                    } else {
                        let data = {
                            vendorOrderID: vendorOrderID,
                            vendorID: vendorID.value,
                            // %E5%8D%8F%E5%95%86%E4%B8%80%E8%87%B4 这一串是啥密文，没搞清从哪编译来的
                            // reason: '%E5%8D%8F%E5%95%86%E4%B8%80%E8%87%B4'
                            reason: '协商一致'
                        }
                        let res = await order.cancel_order(data)
                        if (res.code == 0) {
                            toast('取消成功', 1)
                            uni.jxAlert({
                                title: '提示',
                                content: '取消成功'
                            })
                        } else {
                            uni.jxAlert({
                                title: '提示',
                                content: `取消失败：${res.desc || res.data}`
                            })
                        }
                    }
                } else {
                    uni.jxAlert({
                        title: '提示',
                        content: `取消失败：${res.desc || res.data}`
                    })
                }
            }
        })
    }
    const afsCount = ref<number>(0)     // 取消订单标识
    const cancelOrderFail = ref<boolean>(false)
    function handleResData(res: AnyObject) {
        res.data && res.data.forEach((item: AnyObject) => {
            item.skus.forEach((item: AnyObject) => {
                afsCount.value += item.count
                if (afsCount.value == orderData.value.goodsCount) cancelOrderFail.value = true
            })
            afsCount.value = 0
        })
    }


    /**
     * 拨打电话
     */
    function callPhone(item:AnyObject) {
        let itemList:string[] = []
        if(item.consigneeMobile) itemList.push('临1：' + item.consigneeMobile.split(',')[0] +'转' + item.consigneeMobile.split(',')[1])
        if(item.consigneeMobile2) itemList.push('临2：' + item.consigneeMobile2.split(',')[0] +'转' + item.consigneeMobile2.split(',')[1])
        if(itemList.length === 0) return toast('该订单暂无联系方式', 2)
        uni.showActionSheet({
            // title: '退出后不会删除任何数据',
            itemColor: '#4eb331',
            itemList,
            popover: {
                width: 5000,
            },
            success: function (res) {
                if(res.tapIndex === 0) phoneCall(item.consigneeMobile)
                if(res.tapIndex === 1) phoneCall(item.consigneeMobile2)
            }
        });
    }


    /***************************************************************
     * 联系用户
     */
    function realMobile() {
        if(orderData.value.vendorID === 1){
            if(store.getters['storeInfo/imMtStatus'][0].imStatus !== 1) return toast('美团IM状态已关闭', 2)
            setStorage('vendorUserInfo',{
                    venderOrderID:orderData.value.vendorOrderID,
                    orderSeq:orderData.value.orderSeq,
                    vendorOrgCode:orderData.value.vendorOrgCode,
                    vendorStoreID:orderData.value.vendorStoreID,
                    userID:orderData.value.vendorUserID,
                    vendorID:orderData.value.vendorID
              })
              uni.navigateTo({ url: '/subPages/messageChild/msgChat/msgChat' })
          }else{
            // 饿百
            toast('暂不支持聊天', 2)
          }
    }


    /***************************************************************
     * 饿佰订单号
     */
    const elemIDPre = computed(() => {
        return orderData.value.vendorOrderID2 ? orderData.value.vendorOrderID2.slice(0, orderData.value.vendorOrderID2.length - 4) : ''
    })
    const elemIDSuf = computed(() => {
        return orderData.value.vendorOrderID2 ? orderData.value.vendorOrderID2.slice(orderData.value.vendorOrderID2.length - 4) : ''
    })


    /***************************************************************
     * 格式化预计送达时间
     */
    const expectTime = computed(() => {
        if (
            !orderData.value.expectedDeliveredTime ||
            orderData.value.expectedDeliveredTime.indexOf('1970') !== -1
        ) {
            // 处理预计送达数据为空
            return timeFormatHMS()
        } else {
            return timeFormatHMS(orderData.value.expectedDeliveredTime)
        }
    })

    /**
     * 是否隐藏订单信息
     */
    const isHiddenOrderInfo = computed(() => {
        return  !(orderData.value.buyerComment && orderData.value.buyerComment.includes('支付方式'))
    })


    /***************************************************************
     * 收益异常处理
     */
    const isPointStore = computed(() => {
        return store.getters['storeInfo/isPointStore']
    })
    const earningTooSmall = computed(() => {
        const { payPercentage } = storeInfo.value
        const {
            totalShopMoney,
            desiredFee,
            shopPrice,
            distanceFreightMoney,
            waybillTipMoney,
        } = orderData.value
        let jxEarning = 0
        if (isPointStore.value) {
            // 扣点
            jxEarning = (totalShopMoney * payPercentage) / 200 / 100
        } else {
            // 报价
            jxEarning =
                (totalShopMoney -
                    desiredFee -
                    shopPrice -
                    distanceFreightMoney -
                    waybillTipMoney) /
                100
        }
        if (
            (jxEarning < -10 || totalShopMoney < 0) &&
            orderData.value.buyerComment.indexOf('【JD】') == -1
        ) {
            return true
        } else {
            return false
        }
    })


    /***************************************************************
     * 获取门店信息
     */
    const storeInfo = computed(() => {
        return store.state.storeInfo.allStoreInfo
    })


    /***************************************************************
     * 均价
     */
    const avgPriceInfo = computed(() => {
        const avgPrice = orderInfo.value.avgPrice || 0
        if (avgPrice <= 2000) {
            return '超低'
        } else if (avgPrice > 2000 && avgPrice <= 4000) {
            return '较低'
        } else if (avgPrice > 4000 && avgPrice <= 10000) {
            return '中等'
        } else if (avgPrice > 10000 && avgPrice <= 20000) {
            return '较高'
        } else if (avgPrice > 20000) {
            return '超高'
        }
    })


    /***************************************************************
     * 运单状态
     */
    const finallyWaybillStatus = ref<any>([])        // 最终运单状态
    const waybillStatus = computed(() => {
        let orderStatus:AnyObject = configCms.serveInfo.waybillStatus
        let newArr: Array<AnyObject> = []
        finallyWaybillStatus.value.forEach((element: AnyObject) => {
            if (element.vendorOrderID == orderData.value.vendorWaybillID) {
                let obj = {
                    ...element,
                    status: orderStatus[element.status],
                    statusTime: timeFormatDHM(element.statusTime)
                }
                newArr.push(obj)
            }
        })
        return newArr
    })
    async function getWayBill(orderType: number) {
        let data = {
            vendorOrderID: vendorOrderID.value,
            vendorID: vendorID.value,
            orderType
        }
        let res = await order.get_order_status_list(data)
        if (res.code == 0 && res.data != null) {
            finallyWaybillStatus.value = res.data
        }
    }


    /***************************************************************
     * 查询售后单
     */
    const afsOrder = ref<Array<AnyObject>>([])
    async function GetAfsOrders() {
        let data = {
            vendorOrderID: vendorOrderID.value
        }
        let res = await order.get_afs_orders(data)
        if (res.code == 0) {
            afsOrder.value = res.data.data || []
        }
    }


    /***************************************************************
     * 获取商品列表
     */
    const skuList = ref<Array<AnyObject>>([])
    const totalCount = ref<number>(0)
    async function getSkuList() {
        let data = {
            vendorOrderID: vendorOrderID.value,
            vendorID: vendorID.value
        }
        let res = await order.get_order_sku_info(data)
        if (res.code == 0) {
            skuList.value = res.data
            skuList.value.forEach((item: AnyObject) => {
                totalCount.value += item.count
                item.comparePrice = (item.shopPrice / 100).toFixed(2)
                item.earnPrice = (item.earningPrice / 100).toFixed(2)
                item.saleSalePrice = (item.salePrice / 100).toFixed(2)
            })
            setStorage('reLoadOrderDetail',false)
        }
    }


    /***************************************************************
     * 跳转创建售后单
     * @param {type} 1部分退款 2发起售后
     * @param {skuList} 部分退款数据
     * @param {tel} 用户手机号
     */
    function toCreateAfsOrderPage(type: number, tel?: string) {
        if (type == 1) {
            uni.jxConfirm({
                title: '提示',
                content: '修改订单比例大于10%您的门店将被下线。请联系客户\r\n1.请联系客户更换其他等价商品\r\n2.联系客户说明可做售后退款',
                confirmText: '继续退款',
                cancelText: '联系客服',
                success: () => {
                    let data = JSON.stringify({
                        vendorOrderID: vendorOrderID.value,
                        vendorID: vendorID.value,
                        buyerComment:orderData.value.buyerComment
                    })
                    uni.navigateTo({
                        url: `/subPages/orderChild/createAfterSales/createAfterSales?type=${type}&data=${data}`
                    })
                },
                fail: () => {
                    phoneCall(tel!)
                }
            })
        } else {
            let data = JSON.stringify({
                vendorOrderID: vendorOrderID.value,
                vendorID: vendorID.value,
                buyerComment:orderData.value.buyerComment
            })
            uni.navigateTo({
                url: `/subPages/orderChild/createAfterSales/createAfterSales?type=${type}&data=${data}`
            })
        }
    }


    /***************************************************************
     * 平台补贴筛选
     */
    const realPointStore = computed(() => {
        if (orderData.value.vendorPayPercentage != 0) {
            if (orderData.value.vendorPayPercentage < 50) {//扣点
                return true
            } else {//报价
                return false
            }
        } else {
            if (isPointStore.value) {//扣点
                return true
            } else {//报价
                return false
            }
        }
    })


    /***************************************************************
     * 运营负责人
     */
    const yunyingInfo = computed(() => {
        if (typeof vendorID.value === 'undefined') return { name: '', mobile: '' }
        const obj:AnyObject = {
            0: ['operatorName', 'operatorPhone'],
            1: ['operatorName2', 'operatorPhone2'],
            3: ['operatorName3', 'operatorPhone3'],
            9: ['operatorName', 'operatorPhone'],
            4: ['operatorName', 'operatorPhone'],
            5: ['operatorName', 'operatorPhone'],
            6: ['operatorName', 'operatorPhone'],
            7: ['operatorName', 'operatorPhone'],
            8: ['operatorName', 'operatorPhone'],
            14: ['operatorName', 'operatorPhone'],
            16: ['operatorName', 'operatorPhone'],
        }
        return {
            name: storeInfo.value[obj[vendorID.value][0]],
            mobile: storeInfo.value[obj[vendorID.value][1]],
        }
    })

    const waybillType = computed(() => {
        switch (orderData.value.waybillVendorID) {
            case 0:
                return 'dd'
            case 1:
                return 'mt'
            case 2:
                return 'fn'
            case 3:
                return 'fn'
            case 101:
                return 'dd'
            case 102:
                return 'mt'
            default:
                return orderData.value.waybillVendorID
        }
    })


    /*************************************************
     * 拣货完成
    */
    async function pickingComplete(vendorOrderID: string, vendorID: string) {
        let data = {
            vendorOrderID,
            vendorID,
        }
        let res = await order.finished_pickup(data)
        if (res.code == 0) {
            toast('拣货成功', 1)
        } else {
            toast('拣货异常', 2)
        }
    }


    /*************************************************
     * 投诉骑手
    */
    function complaintHandler(vendorOrderID: string) {
        uni.navigateTo({
            url: `/subPages/orderChild/complaint/complaint?vendorOrderID=${vendorOrderID}`
        })
    }

    const isComplaint = ref<boolean>(false)
    /*************************************************
     * 查看是否能投诉骑手
     */
    async function getComplaintList() {
        const res = await order.complaint_rider_list({ vendorOrderID: orderData.value.vendorOrderID })
        if (res.code == 0 && res.data != null) {
            // 可以投诉
            isComplaint.value = true
        } else {
            // 只能投诉三方配送，不能投诉官方配送
            isComplaint.value = false
        }
    }


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


    return {
        invoiceTitle,           // 抬头发票
        invoiceTaxerID,         // 纳税
        orderData,              // 信息1
        orderInfo,              // 信息2
        orderStatus,            // 订单状态
        cancelOrder,            // 取消订单
        elemIDPre,              // 饿了么订单编号
        elemIDSuf,              // 饿了么订单编号
        expectTime,             // 预计送达
        barCodeImg,             // 条形码
        earningTooSmall,        // 收益异常
        isNewUser,              // 新用户
        realMobile,             // 真实手机号
        avgPriceInfo,           // 均价
        waybillStatus,          // 运单状态
        afsOrder,               // 售后单
        skuList,                // 商品列表
        totalCount,             // 商品数量
        toCreateAfsOrderPage,   // 跳转到售后单页面
        isPointStore,           // 扣点信息
        realPointStore,         // 平台补贴筛选
        storeInfo,              // 门店收款人
        yunyingInfo,            // 运营负责人
        waybillType,            // 快递类型
        pickingComplete,        // 拣货完成
        complaintHandler,       // 投诉骑手
        isComplaint,            // 是否可以投诉骑手
        isHiddenOrderInfo,      // 是否隐藏订单信息
        callPhone               // 拨打电话
    }
}


export default orderDetailFn
