import api from '../api/index'
import store from '../store/index'
import router from './router'
import config from './config'
import qs from 'qs'

export default {
    /**
     * 消息提示
     * @param title
     */
    showToast(title = '') {
        let config = {}

        if (typeof title === 'string') {
            config.title = title
        } else {
            config = title
        }

        uni.showToast({
            title: config.title || '',
            icon: 'none',
            duration: 2000,
        })
    },

    /**
     *  显示模态弹窗
     * @param config
     * @returns {Promise<any>}
     */
    showModal(config = {}) {
        return new Promise(resolve => {
            uni.showModal({
                title: config.title || '温馨提示', //标题
                content: config.content || '', //内容
                showCancel: config.showCancel === false ? config.showCancel : true, //是否显示取消按钮
                cancelText: config.cancelText || '取消', //取消按钮的文字
                cancelColor: config.cancelColor || '#000', //取消按钮的文字颜色
                confirmText: config.confirmText || '确定', //确定按钮的文字
                confirmColor: config.confirmColor || '#000', //确定按钮的文字颜色
                success: res => {
                    resolve(res)
                },
                fail: res => {
                    resolve(res)
                },
            })
        })
    },

    /**
     * ​显示操作菜单
     * @param list
     * @returns {Promise<any>}
     */
    showActionSheet(list = []) {
        if (list.length) {
            return new Promise(resolve => {
                uni.showActionSheet({
                    itemList: list,
                    success: res => {
                        resolve(res.tapIndex)
                    },
                    fail: () => {
                        console.log('取消选择')
                    },
                })
            })
        } else {
            console.log('至少需要一个元素')
        }
    },

    /**
     * 设置标题
     * @param title
     */
    setTitle(title) {
        if (title) {
            uni.setNavigationBarTitle({
                title: title,
            })
        }
    },

    /**
     * 打开分享菜单
     * @param config
     */
    shareMenu(config) {
        // #ifdef MP-WEIXIN
        uni.showShareMenu({
            withShareTicket: true,
            ...config,
        })
        // #endif
    },

    /**
     * 更新用户信息
     */
    updateUserInfo() {
        // 用户微信信息
        api.get('/User/GerUserInfo').then(res => {
            store.commit('user/update', {
                userInfo: res.data,
            })
        })
    },

    /**
     * 支付
     * @param orderId
     * @param price
     */
    pay(orderId, price, jump = false) {
        const self = this

        return new Promise(resolve => {
            if (store.state.common.payStatus) {
                console.log('支付中...')

                // 改为支付中的状态
                store.commit('common/update', {
                    payStatus: false,
                })

                api.post('/Order/Pay', {
                    payMethod: 'WeiXin',
                    orderId: orderId,
                }).then(res => {
                    let options = res.data

                    uni.requestPayment({
                        timeStamp: options.timeStamp,
                        nonceStr: options.nonceStr,
                        package: options.package,
                        signType: options.signType,
                        paySign: options.paySign,
                        success: function () {
                            console.log('支付成功')

                            // 改为可以支付的状态
                            store.commit('common/update', {
                                payStatus: true,
                            })

                            // self.orderTake(orderId, 2)
                            api.post('/Order/Query', {
                                orderId: orderId,
                            }, { pass: true })

                            router.replace({
                                path: '/pages/pay/result',
                                query: {
                                    orderId: orderId,
                                    price: price,
                                    type: 'success',
                                },
                            })
                        },
                        fail: function () {
                            console.log('支付失败')

                            // 改为可以支付的状态
                            store.commit('common/update', {
                                payStatus: true,
                            })

                            if (jump) {
                                // self.orderTake(orderId, 1)
                                router.replace({
                                    path: '/pages/pay/result',
                                    query: {
                                        orderId: orderId,
                                        price: price,
                                        type: 'fail',
                                    },
                                })
                            }
                        },
                        complete: function () {
                            resolve()
                        },
                    })
                })
            }
        })
    },

    // 订单订阅
    orderTake(orderId, type) {
        api.get('/Subscription/GetMsgTpls', {
            type: type,
        }).then(res => {
            uni.requestSubscribeMessage({
                tmplIds: res.data,
                success: () => {
                    api.post('/Subscription/Subscribe', {
                        type: 4,
                        objectId: orderId.toString(),
                    }).then(() => {
                        console.log('订阅成功')
                    })
                },
                fail: err => {
                    console.log(err)
                },
            })
        })
    },

    // 订阅订阅消息类型，1-订单未支付，2-订单支付成功，3-直播订阅，4-售后退货/退款订阅消息，5-售后退款订阅消息，6-优惠券订阅消息
    getMsgTpls(objId, type,callback) {
        api.get('/Subscription/GetMsgTpls', {
            type: type,
        }).then(res => {
            uni.requestSubscribeMessage({
                tmplIds: res.data,
                success: () => {
                    api.post('/Subscription/Subscribe', {
                        type: type,
                        objectId: objId.toString(),
                    }).then(() => {
                        console.log('订阅成功')
                        if(callback){
                            callback();
                        }
                    })
                },
                fail: err => {
                    console.log(err)
                    if(callback){
                        callback();
                    }
                },
            })
        })
    },

    // 接口请求前的初始化
    init() {
        return new Promise(resolve => {
            let timer = setInterval(() => {
                if (store.state.user.init) {
                    clearInterval(timer)
                    resolve()
                }
            }, 10)
        })
    },


    // 登录处理
    login(option) {
        const self = this
        return new Promise(resolve => {
            uni.showLoading({
                title: '登录中...',
                mask: true,
            });
            uni.login({
                provider: 'weixin',
                success: async result => {
                    console.log(result)
                    api.post('/Login/Login', {
                        code: result.code,
                        appId: config.appId,
                        boxId: option.query.bid,
                        shopId: option.query.shopId,
                        fromUserId: option.query.uid,
                        sId: option.query.sId,
                        fromScene: option.scene,
                        fromUrl: option.path + '?' + qs.stringify(option.query),
                        fromExtra: JSON.stringify(option),
                        storeId: option.query.storeId || store.state.common.storeId
                    }).then(res => {
                        store.commit('user/login', res.data);
                        self.updateUserInfo();
                        if (option.query.shopId) {
                            this.updateShop(option.query.shopId, () => {
                                store.commit('user/init');
                                uni.hideLoading();
                                resolve()
                            })
                        } else if (option.query.shareId) {
                            api.get('/Share/GetSharePath', {
                                id: option.query.shareId,
                            }).then(res => {
                                let data = JSON.parse(res.data.parameters);
                                if (data.shopId) {

                                    this.updateShop(data.shopId, () => {
                                        store.commit('user/init');
                                        uni.hideLoading();
                                        resolve()
                                    })
                                } else {
                                    store.commit('user/init');
                                    uni.hideLoading();
                                    resolve()
                                }
                            })
                        } else {
                            store.commit('user/init');
                            uni.hideLoading();
                            resolve()
                        }

                    })
                    // resolve()
                },
            })
        })
    },
    // 修改配置
    setConfig() {
        api.get('/Shop/GetConfig').then(res => {
            let data = JSON.parse(res.data)

            store.commit('common/update', data)
        })
    },

    // 打开设置
    openSetting() {
        uni.openSetting()
    },

    // 更新 门店
    updateShop(shopId, callback) {
        api.get("/Shop/Detail", { id: shopId })
            .then((res) => {
                if (!store.state.common.activeUpShop || store.state.common.activeUpShop.id !== store.state.common.activeShop.id) {

                    store.commit("common/update", {
                        activeUpShop: store.state.common.activeShop,
                    });
                }
                store.commit("common/update", {
                    activeShop: res.data,
                });
                store.commit("user/update", {
                    uvId: res.data.uvId,
                });
                api.get('/shop/GetStoreConfig', { storeId: res.data.store.id })
                    .then(configRes => {
                        if (configRes.data.deliveryConfig) {
                            configRes.data.deliveryConfig.deliveryFee /= 100;
                            configRes.data.deliveryConfig.deliveryMinAmount /= 100;
                            configRes.data.deliveryConfig.packageFee /= 100;
                            configRes.data.deliveryConfig.pickupMinAmount /= 100;
                        }
                        store.commit("common/update", {
                            storeConfig: configRes.data,
                        });
                        // 是否显示优选
                        let tabList = store.state.common.tabList;
                        if (configRes.data.enableYouXuan) {
                            for (let item of tabList) {
                                if (item.id === 3) {
                                    item.hide = false;
                                }
                            }
                        } else {
                            for (let item of tabList) {
                                if (item.id === 3) {
                                    item.hide = true;
                                }
                            }
                        } store.commit("common/update", {
                            tabList: tabList,
                        });
                        if (callback) {
                            callback();
                        }
                    })
            });
    }
}
