import order from "@/api/https/order"
import toast from "@/utils/toast"
import { computed, ref } from "vue"
import configData from "@/utils/configCms"
import { jx_throttles } from "@/utils/tools"

/*************************************************
 * 三方配送
*/
interface propType {
    vendor: string | number
    waybillFee: AnyObject
    orderData: AnyObject
    accountBalance: number
    sotreID: number
    createDeliveryType: number
}
function threeDeliverFn(props: Readonly<propType>, emit: any) {
    const waybillFeeStatus = ref<AnyObject>(props.waybillFee)

    /*************************************************
     * 动态class
    */
    const vendorClass = computed(() => {
        if (props.waybillFee.waybill && props.waybillFee.waybill.status > 10) {
            return 'delivering' + props.vendor
        } else {
            return ''
        }
    })

    /*************************************************
     * 配送名称
    */
    const configCms = configData.serveInfo
    const vendorName = computed(() => {
        return props.vendor ? (configCms as AnyObject).vendorName[props.vendor] : ''
    })

    /*************************************************
     * 等待发单
    */
    const countDown = computed(() => {
        // 计算分
        let minites = Math.floor(props.waybillFee.timeoutSecond / 60)
        // 计算秒
        let seconds = props.waybillFee.timeoutSecond % 60
        return `${minites < 10 ? '0' + minites : minites}分${seconds < 10 ? '0' + seconds : seconds}秒`
    })

    /*************************************************
     * 新的计算方式
    */
    const newPrice = computed(() => {
        if (waybillFeeStatus.value.status) {
            const fee = props.waybillFee.waybill ? props.waybillFee.waybill.desiredFee : props.waybillFee.deliveryFee
            return `<span style="font-size: 10px;">¥</span>${(fee / 100).toFixed(2)}<span class="small"><br/>(预估支出)</span>`
        } else {
            return '<span style="font-size: 10px;"></span>--<span class="small"><br/>(预估支出)</span>'
        }
    })

    /*************************************************
     * 判断是否展示无骑手文字
    */
    const tipText = computed(() => {
        if (waybillFeeStatus.value.status) {
            const fee = props.waybillFee.waybill ? props.waybillFee.waybill.desiredFee : props.waybillFee.deliveryFee
            if (fee == 0) {
                return true
            } else {
                return false
            }
        }
    })

    /*************************************************
     * 切换发单状态
    */
    const switchStatus = jx_throttles({
        time: 1000,
        success: (status: number) => {
            uni.vibrateShort({})
            if (status === waybillFeeStatus.value.status && status == 0) {
                return toast('已经是关闭状态')
            }
            if (status === waybillFeeStatus.value.status && status == 1) {
                return toast('已经是打开状态')
            }
            waybillFeeStatus.value.status = status
            emit('switchStatus', {
                vendorID: props.vendor,
                status,
                waybillFee: props.waybillFee,
            })
        },
        fail: (t: number) => {
            toast('操作过快')
        }
    })


    /*************************************************
     * 立即召唤
    */
    const maskMap = ref<AnyObject>({
        '101': 16,
        '102': 32
    })

    /*************************************************
     * 立即发单
    */
    const createWaybill = jx_throttles({
        time: 3000,
        success: () => {
            uni.vibrateShort({})
            let data =
                (props.orderData.baseFreightMoney || 400) * 0.9 -
                (props.waybillFee.waybill
                    ? props.waybillFee.waybill.desiredFee
                    : props.waybillFee.deliveryFee)
            let tempdata = Math.abs(data / 100)
            if (props.createDeliveryType == 0) {
                //系统发单
                if (tempdata > 10) {
                    uni.jxConfirm({
                        title: '提示',
                        content: `配送费超过10元，是否继续发单`,
                        success: () => {
                            hireRider()
                        }
                    })
                } else {
                    hireRider()
                }
            } else {
                //门店发单
                if (props.accountBalance < 10) {
                    uni.jxAlert({
                        title: '提示',
                        content: '余额不足10元，请充值后发单'
                    })
                } else {
                    orderCreate(tempdata)
                }
            }
        },
        fail: (t: number) => {
            toast(`${t}秒后在试`)
        }
    })
    async function hireRider() {
        uni.showLoading({ title: '召唤中...' })
        let data = {
            vendorOrderID: props.orderData.vendorOrderID,
            vendorID: props.orderData.vendorID,
            courierVendorIDs: JSON.stringify([Number(props.vendor)]),
            forceCreate: false,
            maxAddFee: 0,
            maxDiffFee2Mtps: 0,
        }
        let res = await order.create_waybill_on_providers(data)
        uni.hideLoading()
        if (res.code == 0) {
            uni.jxAlert({
                title: '提示',
                content: '召唤成功',
                success: () => {
                    emit('refresh')
                }
            })
        } else {
            uni.jxAlert({
                title: '提示',
                content: `召唤失败${res.desc || res.data}`
            })
        }
    }
    function orderCreate(tempdata: number) {
        if (props.accountBalance > tempdata) {
            uni.jxConfirm({
                title: '提示',
                content: `是否手动召唤${vendorName.value}`,
                confirmText: '召唤',
                success: () => {
                    hireRider()
                }
            })
        } else {
            uni.jxConfirm({
                title: '提示',
                content: '配送余额不足，点击确定对账号充值'
            })
        }
    }

    /*************************************************
     * 取消三方配送
    */
    function cancelWaybill() {
        uni.jxConfirm({
            title: '提示',
            content: `是否取消${vendorName.value}`,
            success: async () => {
                uni.showLoading({ title: '取消中...' })
                let data = {
                    vendorWaybillID: props.waybillFee.waybill.vendorWaybillID,
                    waybillVendorID: props.waybillFee.waybill.waybillVendorID,
                    reasonID: 0,
                    reason: '不想发了',
                }
                let res = await order.cancel_waybill(data)
                uni.hideLoading()
                if (res.code == 0) {
                    uni.jxAlert({
                        title: '提示',
                        content: '取消成功',
                        success: () => {
                            emit('refresh')
                        }
                    })
                } else {
                    uni.jxAlert({
                        title: '提示',
                        content: `取消失败${res.desc || res.data}`
                    })
                }
            }
        })
    }

    return {
        vendorClass,            // 动态class
        vendorName,             // 配送名字
        countDown,              // 等待发单
        newPrice,               // 新的计算方式
        maskMap,                // 立即召唤
        createWaybill,          // 立即发单
        switchStatus,           // 切换发单
        cancelWaybill,          // 取消三方配送
        waybillFeeStatus,       // 是否开启自动发单
        tipText,                // 是否展示当前范围无骑手问题
    }
}

export default threeDeliverFn

