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: decodeURIComponent(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,
            })
        })

        // 用户积分、会员身份
        api.get('/My/GetMy').then(res => {
            if (res.data) {
                store.commit('user/update', {
                    integral: res.data.pointsInfo.points,
                })
            }
        })
    },

    /**
     * 支付
     * @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,
                            })

                            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)
                },
            })
        })
    },

    // 接口请求前的初始化
    init() {
        return new Promise(resolve => {
            let timer = setInterval(() => {
                if (store.state.user.init) {
                    clearInterval(timer)
                    resolve()
                }
            }, 10)
        })
    },
    
    roleHandle(){
        let user = store.state.user.user;
        if(user){
            // 配送员
            if(user.roleId === '05caf6e0-9069-4da0-9d7e-92d27ce2b7be'){
                uni.hideTabBar({});
            }
        }
    },



    // 获取token
    getToken() {
        return new Promise(resolve => {
            uni.login({
                provider: 'weixin',
                success: async result => {
                    api.post('/Login/Login', {
                        code: result.code,
                        appId: config.appId,
                    },{pass:true}).then(res => {
                        if (res.success) {
                            store.commit("user/login", res.data);
                        }else{
                            router.replace('/pages/index/login');
                            return;
                        }
                        resolve();
                    })
                },
            })
        })
    },

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

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

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