import order from "@/api/https/order"
import { store } from '@/store'
import toast from '@/utils/toast'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref, onBeforeUnmount } from 'vue'

/*************************************************
 * 售后-退款
 *@author zhang-shu-wei <2966211270@qq.com>
 *@date 2023-02-02 10:07:00
*/
function createAfterSales() {
    const storeInfo = ref<AnyObject>(store.state.storeInfo.allStoreInfo)
    /*************************************************
     * 接收optios 参数
     * @type {number} 1：部分退款 2：发起售后
     * @data {anyObject} 数据
     */
    const vendorOrderID = ref<string>('')
    const vendorID = ref<number>(0)
    const buyerComment = ref<string>('')
    const skuList = ref<Array<AnyObject>>([])
    const type = ref<number>(1)
    onLoad(async (options) => {
        let data = JSON.parse(options!.data)
        vendorOrderID.value = data.vendorOrderID
        vendorID.value = +data.vendorID
        buyerComment.value = data.buyerComment
        type.value = +options!.type
        // 部分退款
        if (options!.type == 1) {
            let orderSkuInfo = await getSkuList()
            skuList.value = reduceSku(orderSkuInfo, [])
        }

        // 发起售后
        if (options!.type == 2) {
            let orderSkuInfo = await getSkuList()
            let orderAfsSkuInfo = await getAfsOrderSkuInfo()
            skuList.value = reduceSku(orderSkuInfo, orderAfsSkuInfo)
        }
    })


    /*************************************************
     * 获取商品数据
     */
    async function getSkuList() {
        let data = {
            vendorOrderID: vendorOrderID.value,
            vendorID: vendorID.value,
        }
        let res = await order.get_order_sku_info(data)
        if (res.code == 0 && res.data != null) {
            return res.data
        } else {
            return []
        }
    }


    /*************************************************
     * 获取售后单商品
     */
    async function getAfsOrderSkuInfo() {
        let data = {
            vendorOrderID: vendorOrderID.value,
            vendorID: vendorID.value,
        }
        let res = await order.get_afs_order_sku_info(data)
        if (res.code == 0 && res.data != null) {
            return res.data
        } else {
            return []
        }
    }


    /*************************************************
     * 筛选已售后商品
    */
    // 减掉已经售后的商品
    function reduceSku(skuList: Array<AnyObject>, afsSkuList: Array<AnyObject>) {
        if (afsSkuList) {
            afsSkuList.forEach((item) => {
                let findItem: any = skuList.find(
                    (sku) =>
                        sku.jxSkuID === item.jxSkuID && sku.storeSubID === item.storeSubID
                )
                findItem.count = findItem.count - item.count
            })
            return mapData(skuList)
        } else {
            return mapData(skuList)
        }
    }
    // 过滤数据
    const isNewPriceDisplay: any = computed(() => {
        store.getters['storeInfo/isNewPriceDisplay']
    })
    function mapData(dataList: Array<AnyObject>) {
        let data = JSON.parse(JSON.stringify(dataList))
        data.forEach((item: AnyObject) => {
            item.comparePrice = isNewPriceDisplay.value
                ? item.salePrice > item.shopPrice
                    ? (item.shopPrice / 100).toFixed(2)
                    : (item.salePrice / 100).toFixed(2)
                : (item.shopPrice / 100).toFixed(2)
            item.afsCount = 0
        })
        return data
    }



    /*************************************************
     * 退款
     */
    let arrSelectGood: Array<AnyObject> = []
    async function partRefundOrder() {
        skuList.value.forEach((item: AnyObject) => {
            if (item.afsCount) {
                arrSelectGood.push(item)
            }
        })
        if (arrSelectGood.length === 0) {
            uni.jxAlert({
                title: '提示',
                content: '请选择退款商品',
            })
            return
        }
        if(buyerComment.value === '支付方式：扫码枪'){
            let myMap = new Map()
            arrSelectGood.forEach((i => {
                myMap.set(i.jxSkuID,i.afsCount)
            }))
            let  objNew = Object.fromEntries(myMap);
            await order.refund_online_order({vendorOrderID:vendorOrderID.value,skuIds:JSON.stringify(objNew),reason:'协商一致'})
            toast('创建成功', 1)
        }else{
            if (type.value == 1) {
                partialRefund(arrSelectGood)
            }
            if (type.value == 2) {
                createServe(arrSelectGood)
            }
        }
        
    }


    /*************************************************
     * 部分退款
    */
    let partRefundReason = '商品缺货'
    const popup = ref()
    let partialRefundTimer: any = null
    function partialRefund(arr: AnyObject) {
        uni.jxConfirm({
            title: '退款',
            content: '是否对该订单进行调整',
            success: async () => {
                popup.value.open()
                // return
                // arr = arr.map((item: AnyObject) => ({
                //     skuID: item.skuID,
                //     count: item.afsCount,
                //     storeSubID: item.storeSubID
                // }))
                // let data = {
                //     vendorOrderID: vendorOrderID.value,
                //     vendorID: vendorID.value,
                //     removedSkuInfo: JSON.stringify(arr),
                //     reason: '商品缺货'
                // }
                // let res = await order.adjust_order(data)
                // if (res.code == 0) {
                //     toast('部分退款成功', 1)
                //     clearTimeout(partialRefundTimer)
                //     partialRefundTimer = setTimeout(() => {
                //         uni.navigateBack()
                //     }, 800)
                // } else {
                //     uni.jxAlert({
                //         title: '退款失败',
                //         content: res.desc || res.data,
                //     })
                // }
            },
        })
    }


    

    /**
     * 获取输入框的值
     */
     function onKeyInput(event:AnyObject) {
        partRefundReason = event.detail.value
    }


    /**
     * 弹框确认数据
     */
    async function handleConfirm() {
        if(partRefundReason.length===0) return toast('请填写退款理由', 2)
        let arr = arrSelectGood.map((item: AnyObject) => ({
            skuID: item.skuID,
            count: item.afsCount,
            storeSubID: item.storeSubID
        }))
        let data = {
            vendorOrderID: vendorOrderID.value,
            vendorID: vendorID.value,
            removedSkuInfo: JSON.stringify(arr),
            // reason: '商品缺货'
            reason: partRefundReason
        }
        let res = await order.adjust_order(data)
        if (res.code == 0) {
            toast('部分退款成功', 1)
            clearTimeout(partialRefundTimer)
            partialRefundTimer = setTimeout(() => {
                uni.navigateBack()
            }, 800)
        } else {
            uni.jxAlert({
                title: '退款失败',
                content: res.desc || res.data,
            })
        }
        popup.value.close()
    }


    /*************************************************
     * 发起售后
    */
    function createServe(arr: AnyObject) {
        uni.jxConfirm({
            title: '退款',
            content: '是否对该订单创建售后单\r\n进行【退款】处理',
            success: async () => {
                // 全额退款
                if (totalCount.value == 0) {
                    let data = {
                        vendorOrderID: vendorOrderID.value,
                        vendorID: vendorID.value,
                        reason: '商家同意退款',
                    }
                    let res = await order.refund_order(data)
                    if (res.code == 0) {
                        toast('退款成功', 1)
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 800)
                    } else {
                        uni.jxAlert({
                            title: '退款失败',
                            content: res.desc || res.data,
                        })
                    }
                }

                // 部分退款
                if (totalCount.value != 0) {
                    arr = arr.map((item: AnyObject) => ({
                        skuID: item.skuID,
                        count: item.afsCount,
                        storeSubID: item.storeSubID,
                    }))
                    let data = {
                        vendorOrderID: vendorOrderID.value,
                        vendorID: vendorID.value,
                        refundSkuList: JSON.stringify(arr),
                        reason: '商家同意退款',
                    }
                    let res = await order.part_refund_order(data)
                    if (res.code == 0) {
                        toast('售后单创建成功', 1)
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 800)
                    } else {
                        uni.jxAlert({
                            title: '退款失败',
                            content: res.desc || res.data,
                        })
                    }
                }
            },
        })
    }


    /*************************************************
     * 总数量
    */
    const totalCount = computed(() => {
        let count = 0
        skuList.value.forEach((item: AnyObject) => {
            count += parseInt(item.count, 10)
        })
        return count
    })

    const refundMoney = ref<number>(0)
    let obj:AnyObject = {}
    /*************************************************
    //  * 获取当前将要退款金额
    */
    function numChange(e: number, sku: AnyObject) {
        obj[sku.id] = sku.shopPrice * e
        let sum = 0
        for (const key in obj) {
            sum += obj[key]
            refundMoney.value = sum
        }
    }

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


    return {
        skuList,            // 商品数据
        partRefundOrder,    // 退款处理
        isNewPriceDisplay,  // 是否显示新价格
        storeInfo,          // 商户数据
        numChange,          // 获取当前退款金额
        refundMoney,        // 总共退款金额
        partRefundReason,   // 部分退款理由
        handleConfirm,      // 弹框确认
        onKeyInput,
        popup
    }
}

export default createAfterSales