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

    // 开店申请订阅
    applyShopsubscribe(objId) {
        api.get('/Subscription/GetMsgTpls', {
            type: 7,
        }).then(res => {
            uni.requestSubscribeMessage({
                tmplIds: res.data,
                success: () => {
                    api.post('/Subscription/Subscribe', {
                        type: 7,
                        objectId: objId.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);

                            if (res.data.roleId && res.data.bundleId !== 0) {
                                if (res.data.authStatus === 0) {
                                    // 未注册
                                    router.replace({
                                        path: "/pages/manage/mina/register",
                                    });
                                    return;
                                } else if (res.data.authStatus === 90) {
                                    // 等待注册
                                    router.replace({
                                        path: "/pages/manage/mina/query",
                                    });
                                    return;
                                }
                                // 正常用户
                                store.commit("user/login", res.data);
                                store.commit("common/update", {
                                    curShop: {},
                                });
                                if (!res.data.storeId) {
                                    router.push({
                                        isTabBar: true,
                                        path: "/pages/assistant/index",
                                    });
                                    this.setTabBar([3]);
                                } else {
                                    router.push({
                                        isTabBar: true,
                                        path: "/pages/index/index",
                                    });
                                    this.setTabBar([1, 2]);
                                }
                                this.roleHandle();
                                return;
                            } else {
                                // 正常用户
                                store.commit("user/login", res.data);
                                store.commit("common/update", {
                                    curShop: {},
                                });

                                // this.checkcode(
                                //     {
                                //         // code: "hht2120201",
                                //         platform: res.data.fromPlatform,
                                //     },
                                //     res
                                // );
                                router.push({
                                    isTabBar: true,
                                    path: "/pages/index/index",
                                });
                            }
                        } else {
                            router.push({
                                path: '/pages/index/login',
                                isTabBar: true
                            });
                            return;
                        }
                        resolve();
                    })
                },
            })
        })
    },

    checkcode(data, res) {
        api
            .get("/Group/CheckCode", data, { pass: true })
            .then((res) => {
                if (res.success) {
                    if (res.data.verified) {
                        if (!res.data.storeId) {
                            router.push({
                                isTabBar: true,
                                path: "/pages/assistant/index",
                            });
                            this.setTabBar([3]);
                        } else {
                            router.push({
                                isTabBar: true,
                                path: "/pages/index/index",
                            });
                            this.setTabBar([1, 2]);
                        }
                    } else {
                        router.push({
                            path: "/pages/index/register",
                            query: {
                                pidCode: res.data.code,
                                step: 3,
                            },
                        });
                        this.setTabBar([3]);
                    }
                } else {
                    router.push({
                        path: "/pages/index/register",
                        query: {
                            step: 2,
                        },
                    });
                    this.setTabBar([3]);
                }
            });
    },

    setTabBar(arr) {
        let tabList = store.state.common.tabList;
        tabList = JSON.parse(JSON.stringify(tabList));
        for (let item of tabList) {
            if (arr.indexOf(item.id) !== -1) {
                item.hide = false;
            } else {
                item.hide = true;
            }
        }
        store.commit('common/update', {
            tabList
        })
    },

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

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

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


    /**
     * 转化为指定格式日期
     * @param date
     * @param format
     * @returns {string}
     */
    dateFormat(date, format = 'yyyy-MM-dd') {
        if (date) {
            date = date.replace(/-/g, '/')
            date = new Date(Date.parse(date))

            let o = {
                'M+': date.getMonth() + 1, //月份
                'd+': date.getDate(), //日
                'h+': date.getHours(), //小时
                'm+': date.getMinutes(), //分
                's+': date.getSeconds(), //秒
                'S': date.getMilliseconds(), //毫秒
                'q+': Math.floor((date.getMonth() + 3) / 3), //季度
            }

            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
            }
            for (let k in o) {
                if (new RegExp('(' + k + ')').test(format)) {
                    format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                }
            }
            return format
        } else {
            return ''
        }
    }
}
