import api from '../request'
import { json2query, mapData } from '@/utils'
import { formatDate } from '@/utils/assist.js'
import { store } from '@/store'
export default {
    /**
     * 创建订单
     */
    createOrder: async (json = {}) => {
        try {
            let res = await api('v2/jxorder/CreateOrder', {
                method: 'POST',
                data: json2query(json)
            })
            return res
        } catch (e) {
            console.error('createOrder', e)
            throw (e)
        }
    },

    /**
     * 查询订单 通过vendorOrderID
     */ 
    getOrderInfo:async (json,dns = 'wxC4') => {
        try {
            let res = await api('v2/order/GetOrders', {
                data: json,
            },dns)
            return res
          } catch (e) {
            throw e
          }
    },

    /**
     * 查询订单数量
     * @param {String} fromDate 开始日期 2019-12-12
     * @param {String} toDate 结束日期
     * @param {String} statuss 订单状态列表 [1,2,3]
     */
    getOrderCount: async () => {
        try {
            let res = await api('v2/jxorder/GetMyOrderCountInfo', {
                data: {
                    fromDate: formatDate(new Date() - 6 * 24 * 3600 * 1000, 'YYYY-MM-DD'),
                    toDate: formatDate(null, 'YYYY-MM-DD'),
                    statuss: JSON.stringify([2, 5, 10, 15, 17, 18, 20])
                }
            })
            let orderInfo = res || []
            let waitCount = orderInfo.find(item => item.status === 2)    // 计算数量
            let deliverCount = orderInfo.reduce((prev, next) => {
                if (next.status >= 5 && next.status <= 20) {
                    return prev + next.count
                } else {
                    return prev
                }
            }, 0)
            return {
                waitCount: waitCount ? waitCount.count : 0,
                deliverCount
            }
        } catch (e) {
            console.error('getMyOrderCountInfo', e)
            throw (e)
        }
    },

    /**
     * 获取支付信息 Pay4Order
     * @param {String} vendorOrderID 订单号
     * @param {Number} payType 支付类型 PayTypeWX = 1 // 微信支付
     * @param {String} vendorPayType 平台支付类型
     */
    pay4Order: async (json,dns="wxC4") => {
        try {
            let res = await api('v2/jxorder/Pay4Order', {
                method: 'POST',
                data: json
            },dns ? dns : 'wxC4')
            return res
        } catch (e) {
            console.error('pay4Order', e)
            throw {
                errKey: 'pay4Order',
                err: e
            }
            // throw (e)
        }
    },

    /**
     * @param {String} id 会员折扣id
     * @param {Number} payType 支付类型 PayTypeWX = 1 // 微信支付
     * @param {String} vendorPayType 平台支付类型
     */
    pay4User: async (json) => {
        try {
            let res = await api('v2/jxorder/Pay4User', {
                method: 'POST',
                data: json
            })
            return res
        } catch (e) {
            console.error('pay4User', e)
            throw (e)
        }
        // orderPage.pay4User
    },

    /**
     * 获取我的订单
     * @param {String} vendorOrderID 订单号
     * @param {String} keyword 关键字
     * @param {String} fromDate 开始日期 2006-01-02
     * @param {String} fromDate 结束日期 2006-01-02
     * @param {String} statuss 状态，缺省不限制
     * @param {Number} offset 序号
     * @param {Number} pageSize 页大小
     */
    getMyOrders: async (json) => {
        try {
            let res = await api('v2/jxorder/GetMyOrders', {
                data: {
                    ...json,
                    fromDate: formatDate(new Date() - 364 * 24 * 3600 * 1000, 'YYYY-MM-DD'),
                    toDate: formatDate(null, 'YYYY-MM-DD'),
                    offset: 0,
                    pageSize: 10,
                }
            })
            return {
                totalCount: res.totalCount,
                data: mapData(res.data)
            }
        } catch (e) {
            console.error('getMyOrders', e)
            throw (e)
        }
    },

    /**
     * 获取订单商品信息
     * @param {String} vendorOrderID 订单号
     * @param {Number} vendorID 厂商
     */
    getOrderSkuInfo: async (vendorOrderID, vendorID) => {
        try {
            let res = await api('v2/order/GetOrderSkuInfo', {
                data: {
                    vendorOrderID,
                    vendorID
                }
            })
            return res
        } catch (e) {
            console.error('getOrderSkuInfo', e)
            throw (e)
        }
    },

    /**
     * 获取订单状态
     * @param {String} vendorOrderID 订单号
     * @param {Number} vendorID 厂商
     * @param {Number} orderType 订单：1；运单：2；订单+运单：-1
     */
    getOrderStatus: async (vendorOrderID, vendorID) => {
        try {
            let res = await api('v2/order/GetOrderStatusList', {
                data: {
                    vendorOrderID,
                    vendorID,
                    orderType: 1
                }
            })
            if (res) {
                return res.map(item => ({
                    id: item.id,
                    statusText: store.getters['login/cms'].orderStatus[item.status],
                    statusTime: formatDate(item.statusTime, 'YYYY-MM-DD hh:mm:ss'),
                    remark: item.remark
                })).sort((n1, n2) => (new Date(n2.statusTime) - new Date(n1.statusTime)))
            } else {
                return []
            }
            // return res
        } catch (e) {
            console.error('getOrderStatus', e)
            throw (e)
        }
    },

    /**
     * 查询物料订单状态
     * @param {*} json 
     */
    getMatterOrderStatus: async (json) => {
        try {
            let res = await api('v2/jxorder/GetMatterOrderStatus', {
                data: json
            })
            if (res) {
                return res.map(item => ({
                    id: parseInt(Math.random() * 2000) + 1,
                    statusText: item.status,
                    statusTime: formatDate(item.time, 'YYYY-MM-DD hh:mm:ss'),
                    remark: item.name
                })).sort((n1, n2) => (new Date(n2.statusTime) - new Date(n1.statusTime)))
            } else {
                return []
            }
        } catch (e) {
            console.error('getMatterOrderStatus', e)
            throw (e)
        }
    },

    /**
     * 买家取消订单
     * @param {*} vendorOrderID 订单号
     * @param {*} reason 原因
     */
    buyerCancelOrder: async (json) => {
        // try {
        //   await api('v2/jxorder/BuyerCancelOrder', {
        //     method: 'POST',
        //     data: json
        //   })
        // } catch (e) {
        //   console.error('BuyerCancelOrder', e)
        //   throw e
        // }
        try {
            let res = await api('v2/order/CancelOrder', {
                method: 'PUT',
                data: json
            })
            return res
        } catch (e) {
            console.error('buyerCancelOrder', e)
            throw (e)
        }
    },

    /**
     * 获取售后单
     * @param {*} afsOrderID 售后单号
     * @param {*} vendorOrderID 订单号
     * @param {*} fromTime 开始时间
     * @param {*} toTime 结束时间
     * @param {*} offset 起始序号
     * @param {*} pageSize 页大小
     */
    getAfsOrders: async (json) => {
        try {
            let res = await api('v2/jxorder/GetMyAfsOrders', {
                data: json
            })
            return res
        } catch (e) {
            console.error('getAfsOrders', e)
            throw (e)
        }
    },

    /**
     * 获取售后单商品
     * @param {*} afsOrderID 售后单号
     * @param {*} vendorID 厂商ID
     */
    getAfsOrderSkuInfo: async (json) => {
        try {
            let data = {}
            if (json.afsOrderID) data.afsOrderID = json.afsOrderID
            if (json.vendorOrderID) data.vendorOrderID = json.vendorOrderID
            data.vendorID = json.vendorID
            data.isNotFaild = json.isNotFaild ? true : false

            let res = await api('v2/order/GetAfsOrderSkuInfo', {
                data
            })
            return res
        } catch (e) {
            console.error('getAfsOrderSkuInfo', e)
            throw (e)
        }
    },

    // /**
    //  * 发起售后退款 ，该接口直接退款，并没有审核这一步，故取消使用该接口发起售后，修改为v2/jxshop/JxMsg
    //  * @param {*} vendorOrderID 订单号
    //  * @param {*} vendorID 厂商ID
    //  * @param {*} refundSkuList [{skuID, count, storeSubID}]
    //  * @param {*} reason 原因
    //  */
    // partRefundOrder: async (vendorOrderID, vendorID, refundSkuList, reason) => {
    //     try {
    //         let res = await api('v2/order/PartRefundOrder', {
    //             method: 'PUT',
    //             data: {
    //                 vendorOrderID,
    //                 vendorID,
    //                 refundSkuList,
    //                 reason
    //             }
    //         })
    //         return res
    //     } catch (e) {
    //         console.error('partRefundOrder', e)
    //         throw (e)
    //     }
    // }

    /**
     * 申请售后
     * 该接口存在问题，需后端优化
     * 目前只能进行部分商品售后退款申请
     * 问题1：全部商品申请退款，失败
     * 问题2：每次只申请退款一个商品，直至退到最后一个，运费，退不回来
     */
    applyAfterSale: async (data) => {
        try {
            let res = await api('v2/jxshop/JxMsg', {
                method: 'POST',
                data
            })
            return res
        } catch (e) {
            console.error('applyAfterSale', e)
            throw (e)
        }
    },

    /**
     * 自定义金额支付（接口已经调通，后端待优化）京西支付
     */
    pay4StoreMyselfDeliverOrder: async (json) => {
        try {
            if (!store.getters['login/isLogin']) return

            let res = await api('v2/jxorder/Pay4StoreMyselfDeliverOrder', {
                method: 'POST',
                data: json
            })
            return res
        } catch (e) {
            console.error('pay4StoreMyselfDeliverOrder', e)
            throw (e)
        }
    },

    /**
     * 订单拣货完成 扫码支付 到店消费
     */
    finishedPickup:async (json,dns='wxC4') => {
        try {
            let res = await api('v2/order/FinishedPickup', {
                method: 'POST',
                data: json
            },dns)
            return res
        } catch (error) {
            console.error('finishedPickup', error)
            throw (error)
        }
    },

    /**
     * 订单送达
     */
    selfDelivered:async (json,dns='wxC4') => {
        try {
            let res = await api('v2/order/SelfDelivered', {
                method: 'POST',
                data: json
            },dns)
            return res
        } catch (error) {
            console.error('selfDelivered', error)
            throw (error)
        }
    },

    /**
     * 修改订单信息
     */
    updateOrderInfo:async (json,dns='wxC4') => {
        try {
            let res = await api('v2/order/UpdateOrderInfo', {
                method: 'POST',
                // headers: {
                //     'Content-Type': 'application/x-www-form-urlencoded'
                //   },
                data: json
            },dns)
            return res
        } catch (error) {
            console.error('updateOrderInfo', error)
            throw (error)
        }
    }


}