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


/*************************************************
 * 配送管理
 * @author zhang-shu-wei <2966211270@qq.com>
 * @date 2023-02-06 17:49:16
 * @param {}-
 * @return {*}
*/
function deliverMangetFn() {
    const {
        openWeixin,
    } = useGlobalFunc()

    /*************************************************
     * 接收数据
    */
    const vendorOrderID = ref<string>('')
    onLoad(async (options) => {
        vendorOrderID.value = options?.orderId
        await getOrder()
        await getWaybillFee()
    })
    onShow(async () => {
        await getDeliverMoney()
        await getStoreMoney()
    })

    /*************************************************
     * 下拉刷新
    */
    let onPullDownRefreshTimer: any = null
    onPullDownRefresh(() => {
        clearTimeout(onPullDownRefreshTimer)
        onPullDownRefreshTimer = setTimeout(async () => {
            allFn()
            clearTimeout(onPullDownRefreshTimer)
        }, 1000)
    })

    /*************************************************
     * 获取订单信息
    */
    const orderData = ref<AnyObject>({})        // 订单数据
    const courierMaps = ref<Array<AnyObject>>([])         // 快递地图
    const createDeliveryType = ref<number>(0)
    async function getOrder() {
        let data = {
            vendorOrderID: vendorOrderID.value
        }
        let res = await order.get_orders(data)
        if (res.code == 0 && res.data.totalCount >= 1) {
            orderData.value = res.data.data[0]
            let store = await getStoreInfo(orderData.value.jxStoreID)
            courierMaps.value = store.CourierMaps
            createDeliveryType.value = orderData.value.createDeliveryType
        } else {
            uni.jxAlert({
                title: '提示',
                content: '未查询到订单信息',
                success: () => {
                    uni.navigateBack()
                }
            })
        }
    }

    /*************************************************
     * 获取门店信息
    */
    async function getStoreInfo(storeID: string) {
        let data = {
            storeIDs: JSON.stringify([storeID]),
            pageSize: 1
        }
        let res = await merchant.get_stores(data)
        if (res.code == 0) {
            return res.data.stores[0]
        }
    }

    /*************************************************
     * 配送状态
    */
    const waitingStatus = computed(() => {
        if (orderData.value.waybillVendorID === -1 && orderData.value.status === 15 && (orderData.value.deliveryFlag & 16) === 0 && (orderData.value.deliveryFlag & 32) === 0) {
            if (orderData.value.businessType === 1) {
                // 立即达
                return '待配送'
            } else {
                // 预订单
                let keys = Object.keys(deliverList.value)
                if (keys.length > 0) {
                    if (deliverList.value[keys[0]].timeoutSecond) {
                        return '待配送'
                    } else {
                        return '预订单'
                    }
                } else {
                    return '预订单'
                }
            }
        } else if (orderData.value.waybillVendorID === -1 && orderData.value.status === 15 && ((orderData.value.deliveryFlag & 16) === 16 || (orderData.value.deliveryFlag & 32) === 32)) {
            return '正在召唤三方配送'
        } else {
            if (orderData.value.waybillVendorID >= 0) {
                return configCms.vendorName[orderData.value.waybillVendorID]
            } else {
                return '商家自送'
            }
        }
    })

    /*************************************************
     * 订单状态
    */
    const configCms:AnyObject = configData.serveInfo
    const orderStatus = computed(() => {
        let status = orderData.value.status
        if (status === 15) {
            return '待配送'
        } else if (status === 20) {
            return '配送中'
        } else {
            if (status) {
                return configCms.orderStatus[status]
            } else {
                return '未知状态'
            }
        }
    })

    /*************************************************
     * 获取配送费用
    */
    const deliverList = ref<AnyObject>({})
    async function getWaybillFee() {
        let data = {
            vendorOrderID: orderData.value.vendorOrderID,
            vendorID: orderData.value.vendorID
        }
        let res = await order.query_order_waybill_fee_info(data)
        if (res.code == 0) {
            let info = res.data
            courierMaps.value && courierMaps.value.forEach((element: AnyObject) => {
                if (info[element.vendorID]) info[element.vendorID].status = element.status
            })
            deliverList.value = info
            isShouldCharge(deliverList.value)
        } else {
            uni.jxAlert({
                title: '提示',
                content: '未获取到配送费用',
                success: () => {
                    uni.navigateBack()
                }
            })
        }
    }

    /*************************************************
     * 
    */
    const isCharge = ref<boolean>(false)
    function isShouldCharge(item: AnyObject) {
        for (let key in item) {
            var currentNum =
                (orderData.value.baseFreightMoney || 400) * 0.9 -
                (item[key].waybill
                    ? item[key].waybill.actualFee
                    : item[key].deliveryFee)
            Math.abs(currentNum) > accountBalance.value
                ? (isCharge.value = true)
                : null
        }
    }

    const accountBalance = ref<number>(0) // 品牌账号余额
    /*************************************************
     * 获取品牌账户余额
    */
    async function getDeliverMoney() {
        let res = await order.get_brands()
        if (res.code == 0) {
            let brandID = store.state.storeInfo.allStoreInfo.brandID
            const resAll = res.data.find((item: any) => item.id === brandID)
            accountBalance.value = resAll.balance || 0
        } else {
            toast('账户余额信息异常')
        }
    }

    const StoreMoneyBalance = ref<number>(0) // 门店账号余额
    /*************************************************
     * 门店账号余额
     */
    async function getStoreMoney() {
        let data = {
            storeID: getStorage('storeID'),
        }
        let res = await order.get_store_acct_balance(data)
        if (res.code == 0) {
            StoreMoneyBalance.value = res.data.accountBalance
        } else {
            toast('门店账号余额异常')
            StoreMoneyBalance.value = 0
        }
    }



    /*************************************************
     * 召唤骑手费用
    */
    const feeCall = computed(() => {
        // 拿到平台
        const waybillFee = deliverList.value[orderData.value.waybillVendorID]
        // 拿到费用
        let fee = 0
        if (waybillFee) {
            fee = waybillFee.waybill
                ? waybillFee.waybill.desiredFee
                : waybillFee.deliveryFee
        }
        return (fee / 100).toFixed(2)
    })

    /*************************************************
     * 平台补贴
    */
    const selfDeliveryPrice = computed(() => {
        return (((orderData.value.baseFreightMoney || 400) * 0.9) / 100).toFixed(1)
    })

    /*************************************************
     * 立即召唤
    */
    const isSelfDeliver = computed(() => {
        let order = orderData.value
        if ('deliveryFlag' in order) {
            return (
                (order.deliveryFlag & 3) === 3 &&
                order.lockStatus === 0 &&
                order.deliveryType !== 'self' &&
                !order.vendorWaybillID
            )
        } else {
            return false
        }
    })

    /*************************************************
     * 立即充值金额
    */
    const chargeMoney = ref<number>(100)
    function handleChargeNow(type: number) {
        uni.vibrateShort({})
        if (getStorage('terrace') == 'jxgy') {
            uni.jxAlert({
                title: '提示',
                content: '果园App暂不支持在线充值，请联系运营进行充值。',
            })
            return
        }
        let data = JSON.stringify({
            type: type,
            storeName: getStorage('storeName'),
            storeID: getStorage('storeID'),
            token: getStorage('token'),
            platform: 1
        })
        uni.jxConfirm({
            title: '提示',
            content: '即将打开微信进行充值，如果打开失败，请重新操作',
            confirmText: '确认充值',
            success: () => {
                openWeixin(`subPages/messageChild/appPlay/appPlay?playData=${data}`)
            }
        })
    }

    /*************************************************
     * 立即自送
    */
    const dyPopup = ref<any>(null)
    function selfDelivery() {
        uni.jxConfirm({
            title: '提示',
            content: '是否将该订单转为自送',
            success: () => {
                // 抖音小时购和饿佰新零售转自送
                if (orderData.value.vendorID == 14 || orderData.value.vendorID == 3 || orderData.value.vendorID == 1) {
                    uni.jxConfirm({
                        title: '提示',
                        content: '是否填写骑手信息',
                        confirmText: '填写',
                        cancelText: '不填写',
                        success: () => {
                            dyPopup.value.open()
                        },
                        fail: () => {
                            selfDelivering()
                        }
                    })
                } else {
                    // 非抖店订单自送
                    selfDelivering()
                }
            },
        })
    }
    async function selfDelivering() {
        let data = {
            vendorOrderID: orderData.value.vendorOrderID,
            vendorID: orderData.value.vendorID,
        }
        let res = await order.self_delivering(data)
        if (res.code == 0) {
            allFn()
            uni.jxAlert({
                title: '提示',
                content: '转自送成功，请尽快安排给客户送货',
            })
        } else {
            uni.jxAlert({
                title: '提示',
                content: `转自送失败：${res.desc || res.data}`,
            })
        }
        dyCancel()
    }

    /*************************************************
     * 抖音自送
    */
    const deliveryRider = ref<{
        name: string
        tel: string
    }>({
        name: '',
        tel: ''
    })
    async function handleConfirm() {
        if (deliveryRider.value.name == '') return toast('请填写骑手姓名')
        let ruler = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
        if (!ruler.test(deliveryRider.value.tel)) return toast('请填写正确的骑手电话')
        let data = {
            vendorOrderID: orderData.value.vendorOrderID,
            vendorID: orderData.value.vendorID,
            courierName: deliveryRider.value.name,
            courierMobile: deliveryRider.value.tel
        }
        dyCancel()
        let res = await order.self_delivering(data)
        if (res.code == 0) {
            allFn()
            uni.jxAlert({
                title: '提示',
                content: '转自送成功，请尽快安排给客户送货',
            })
        } else {
            uni.jxAlert({
                title: '提示',
                content: `转自送失败：${res.desc || res.data}`,
            })
        }
    }
    let allFnTimer: any = null
    // 重新请求数据
    function allFn() {
        clearTimeout(allFnTimer)
        allFnTimer = setTimeout(async () => {
            await getOrder()
            await getWaybillFee()
            await getDeliverMoney()
            await getStoreMoney()
        }, 1000)
    }

    /*************************************************
     * 取消抖音自送
    */
    function dyCancel() {
        dyPopup.value.close()
        deliveryRider.value = {
            name: '',
            tel: ''
        }
    }

    /*************************************************
     * 添加小费
    */
    function addTipMoney() {
        uni.jxConfirm({
            title: '添加小费',
            content: `当前已加小费：${(orderData.value.waybillTipMoney / 100).toFixed(
                2
            )}\r\n是否再添加 1元`,
            confirmText: '加1元',
            cancelText: '不了',
            success: async () => {
                let data = {
                    vendorOrderID: orderData.value.vendorOrderID,
                    vendorID: orderData.value.vendorID,
                    tipFee: +orderData.value.waybillTipMoney + 100,
                    isPay: 0,
                }
                let res = await order.update_order_waybill_tip(data)
                if (res.code == 0) {
                    toast('添加成功', 1)
                    allFn()
                } else {
                    uni.jxConfirm({
                        title: '提示',
                        // content: `添加失败：${res.desc || res.data}`,
                        content: `${res.desc || res.data}`,
                        confirmText: '确认添加',
                        cancelText: '取消',
                        success: async () => {
                            let data = {
                                vendorOrderID: orderData.value.vendorOrderID,
                                vendorID: orderData.value.vendorID,
                                tipFee: +orderData.value.waybillTipMoney + 100,
                                isPay: 1,
                            }
                            let res = await order.update_order_waybill_tip(data)
                            if (res.code == 0) {
                                toast('添加成功', 1)
                                allFn()
                            } else {
                                uni.jxAlert({
                                    title: '提示',
                                    content: `添加失败：${res.desc || res.data}`,
                                })
                            }
                        }
                    })
                }
            },
        })
    }

    /*************************************************
     * 自动发单
    */
    interface switchStatusType {
        vendorID: number | string,
        status: number,
        waybillFee: AnyObject,
    }
    async function switchStatus(sendData: switchStatusType) {
        let courier: any = courierMaps.value.find(
            (item: AnyObject) => +item.vendorID === +sendData.vendorID
        )
        let data = {
            storeID: orderData.value.jxStoreID,
            vendorID: sendData.vendorID,
            payload: JSON.stringify({
                status: sendData.status,
                vendorStoreID: courier.vendorStoreID,
            })
        }
        let res = await order.update_store_courier_map(data)
        if (res.code == 0) {
            if (sendData.status == 0) {
                toast('关闭成功', 1)
            } else {
                toast('打开成功', 1)
            }
            await getOrder()
            await getWaybillFee()
        } else {
            uni.jxAlert({
                title: '提示',
                content: `操作失败${res.desc || res.data}`
            })
        }
    }
    // 刷新
    async function refresh() {
        // 获取订单信息
        await getOrder()
        if (orderData.value.status > 20) {
            uni.jxAlert({
                title: '警告',
                content: '订单状态已改变',
                success: () => {
                    uni.navigateBack()
                }
            })
        } else {
            await getWaybillFee()
        }
    }

    const switchActive = ref<boolean>(false) // 配送列表默认关闭

    /*************************************************
     * 取消所有配送
    */
    function cancelAll(isStopSchedule?:Boolean) {
        let data:AnyObject = {
            vendorOrderID: vendorOrderID.value,
            vendorID: orderData.value.vendorID
        }
        console.log('ZSW-res', data);
        if(isStopSchedule) data['isStopSchedule'] = isStopSchedule      // 停止运单调度
        uni.jxConfirm({
            title: '提示',
            content: '是否取消该订单的所有三方配送',
            success: async () => {
                let res = await order.cancel_all_3rd_waybills(data)
                if (res.code == 0) {
                    uni.jxAlert({
                        title: "提示",
                        content: "取消成功",
                        success: () => {
                            allFn()
                        }
                    })
                } else {
                    uni.jxAlert({
                        title: '提示',
                        content: res.desc || res.data
                    })
                }
            }
        })
    }

    /*************************************************
     * 投诉骑手
     */
    async function complainRider() {
        uni.navigateTo({
            url: `/subPages/orderChild/complaint/complaint?vendorOrderID=${orderData.value.vendorOrderID}&orderData=${JSON.stringify(orderData.value)}&type=current`
        })
    }

    /*************************************************
     * 查看地图
     */
    function seeMap() {
        uni.openLocation({
            latitude: orderData.value.consigneeLat / 1000000,
            longitude: orderData.value.consigneeLng / 1000000,
            name: orderData.value.consigneeAddress,
            address: '客户地址',
            scale: 16,
        })
    }

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

    return {
        waitingStatus,                  // 配送状态
        orderData,                      // 订单数据
        createDeliveryType,             // 创建交货类型
        orderStatus,                    // 待配送状态
        deliverList,                    // 获取配送费用
        // isCharge,                    // 判断
        accountBalance,                 // 品牌账户余额
        StoreMoneyBalance,              // 门店账户余额
        feeCall,                        // 召唤骑手费用
        selfDeliveryPrice,              // 平台补贴
        isSelfDeliver,                  // 立即召唤
        chargeMoney,                    // 充值金额
        selfDelivery,                   // 立即自送
        deliveryRider,                  // 抖音自送骑手信息
        dyPopup,                        // 抖音自送 popup 实例
        // dyCancel,                       // 取消抖音自送
        selfDelivering,                 // 取消填写骑手信息 还是进行转自配送
        handleConfirm,                  // 确定骑手信息
        addTipMoney,                    // 加小费
        switchStatus,                   // 自动发单
        refresh,                        // 刷新状态
        switchActive,                   // 切换状态
        seeMap,                         // 查看地图
        handleChargeNow,                // 充值金额
        cancelAll,                      // 一键取消所有配送
        complainRider                   // 投诉骑手
    }
}

export default deliverMangetFn