import http from '../plugins/http';
export default {
    computed: {
        isLogin() {
            return !!this.$store.state.userInfo;
        },
        authStatus() {
            let status = this.$store.state.userInfo?.authStatus;

            return this.AuthStatus.has(status) ? this.AuthStatus.get(status) : '未认证';
        }
    },
    data() {
        return {
            AuthStatus: new Map([
                ['NOT_AUTH', '未认证'],
                ['PENDING', '认证中'],
                ['SUCCESS', '已认证'],
                ['FAIL', '认证失败']
            ]),
            isLoading: true
        };
    },
    methods: {
        updateUser(info, sucess = true) {
            if (info) {
                return this.$http
                    .post(
                        '/user/update',
                        {
                            ...this.$store.state.userInfo,
                            ...info
                        },
                        { body: 'json' }
                    )
                    .then(() => {
                        return this.$store.dispatch('getUserInfo');
                    })
                    .then(() => {
                        if (sucess) {
                            this.$toast.success('更新成功');
                        }
                        return Promise.resolve();
                    })
                    .catch(e => {
                        if (e) {
                            this.$toast(e.error);
                        }
                        return Promise.reject();
                    });
            }
        },
        updateFile(e, type, size = 1000) {
            const formData = new FormData();
            formData.append('file', e.file, e.file.name);
            formData.append('type', type);
            formData.append('width', size);
            formData.append('height', size);
            formData.append('size', size);
            return http.axios.post('/upload/file', formData).then(res => {
                return Promise.resolve(res.data);
            });
        },
        getImg(imgs = '', type = '', size = 800) {
            if (!imgs) {
                imgs = '';
            }
            if (!(imgs instanceof Array)) {
                imgs = imgs.split(',');
            }

            imgs = imgs.filter(item => {
                return !!item;
            });
            if (imgs.length > 0) {
                let img = type ? imgs[0][type] : imgs[0];
                // console.log(img);
                return img + (/\.gif$/i.test(img) ? '' : `?x-oss-process=image/resize,h_${size},m_lfit`);
            } else {
                return '';
            }
        },
        accAdd(arg1, arg2) {
            var r1, r2, m;
            try {
                r1 = arg1.toString().split('.')[1].length;
            } catch (e) {
                r1 = 0;
            }
            try {
                r2 = arg2.toString().split('.')[1].length;
            } catch (e) {
                r2 = 0;
            }
            m = Math.pow(10, Math.max(r1, r2));
            return (arg1 * m + arg2 * m) / m;
        },
        accMul(arg1, arg2) {
            var m = 0,
                s1 = arg1.toString(),
                s2 = arg2.toString();
            try {
                m += s1.split('.')[1].length;
            } catch (e) {}
            try {
                m += s2.split('.')[1].length;
            } catch (e) {}
            return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
        },
        checkBank() {
            // return this.$http
            //     .get('/user/myBankCard')
            //     .then(res => {
            //         if (res.length > 0) {
            //             return Promise.resolve();
            //         } else {
            //             return Promise.reject();
            //         }
            //     })
            //     .catch(() => {
            //         return this.$dialog
            //             .confirm({
            //                 title: '银行卡未绑定',
            //                 message: '您的账户还未绑定银行卡',
            //                 confirmButtonText: '前往绑定'
            //             })
            //             .then(() => {
            //                 this.$router.push('/mineBanks');
            //                 return Promise.reject();
            //             });
            //     });
            return (this.$store.state.userInfo || {}).settleAccountId != undefined
                ? Promise.resolve()
                : this.$dialog
                      .confirm({
                          title: '银行卡未绑定',
                          message: '您的账户还未绑定银行卡',
                          confirmButtonText: '前往绑定'
                      })
                      .then(() => {
                          this.$router.push('/mineBanks');
                          return Promise.reject();
                      })
                      .catch(() => {
                          return Promise.reject();
                      });
        },
        checkAuth() {
            if (this.authStatus === '已认证') {
                return Promise.resolve();
            } else {
                this.$dialog
                    .confirm({
                        title: '实名认证',
                        message: '您的账户还未通过实名认证，认证后可进行添加银行卡',
                        confirmButtonText: '前往认证'
                    })
                    .then(() => {
                        if (this.authStatus === '认证中' || this.authStatus === '认证失败') {
                            this.$router.push('/waiting');
                        } else if (this.authStatus === '未认证') {
                            this.$router.push('/Authentication');
                        }
                    });
                return Promise.reject();
            }
        },
        checkLogin() {
            if (this.isLogin) {
                return Promise.resolve();
            } else {
                this.$dialog
                    .confirm({
                        title: '提示',
                        message: '用户未登录,是否立即登录',
                        confirmButtonText: '立即登录'
                    })
                    .then(() => {
                        this.$router.push('/login');
                    });
                return Promise.reject();
            }
        },
        getLabelName(val = '', list = [], key = 'label') {
            let info = list.find(item => {
                return item.value === val;
            });
            return info ? info[key] : '';
        },
        scrollRefreash() {
            this.$toast.clear();
        },
        wait() {
            this.$toast('敬请期待');
        },
        addClass(elName = '', className = '', show = '', time = 600) {
            this.$refs[elName].className = this.$refs[elName].className + ` ${className}`;
            if (show === true) {
                this.$refs[elName].style.display = 'block';
            }
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (show === false) {
                        this.$refs[elName].style.display = 'none';
                    }
                    resolve();
                }, time);
            });
        },
        backReson(error) {
            if (error && error.indexOf('超过商户单日额度') !== -1) {
                return '绿洲宇宙冷却系统已启动，请稍后支付。';
            } else {
                return error;
            }
        },
        onRefresh() {
            setTimeout(() => {
                this.isLoading = false;
            }, 1000);
        },
        checkWebDriver(e) {
            if (window.navigator.webdriver == true || e.isTrusted == false) {
                return false;
            } else {
                return true;
            }
        },
        goWin(next) {
            window.location.href = next;
        },
        getNum(num = 0) {
            if (num < 10) {
                return '0' + num;
            } else {
                return num;
            }
        },
        openScheme(url) {
            const a = document.createElement('a');
            a.href = url;
            document.body.appendChild(a);
            a.click();
            setTimeout(() => {
                document.body.removeChild(a);
            }, 5000);
        }
    }
};
