
<template>
    <form :class="bem([innerType])" @submit="submit">
        <Phone v-if="innerType === 'phone'" :countries="countries"/>
        <Wechat v-else-if="innerType === 'wechat'"/>
        <Register v-else-if="innerType == 'register'"/>
        <Resetpwd v-else-if="innerType == 'resetpwd'"/>
        <BindPhone v-else-if="innerType == 'bindphone'"/>
        <QQ v-else-if="innerType == 'qq'"/>
        <Wechat v-else/>
        <iframe
            :class="bem('ums')"
            ref="ums"
            v-once
            :src="src"
            frameborder="0"
            @load="init"/>
    </form>
</template>

<script>
import { componentMixin, createComponentName } from '../_utils/component';
import Phone from './Phone';
import Wechat from './Wechat';
import Register from './Register';
import Resetpwd from './Resetpwd';
import BindPhone from './Bindphone';
import Tips from '../Tips';
import request from '../request';
import QQ from './QQ';
import { UMS_URL } from '../_utils/constant';
import { getQueryParams } from '../_utils/url';
import guestUser from '../guestUser';

export default {
    name: createComponentName('auth'),
    components: {
        Phone,
        Register,
        Wechat,
        Resetpwd,
        QQ,
        BindPhone
    },
    mixins: [componentMixin],

    provide() {
        return {
            vm: this
        };
    },
    props: {
        type: {
            type: String
        },
        defaultType: {
            type: String,
            default: 'login'
        },
        // 游客标识
        guestFinger: {
            type: String
        }
    },
    data() {
        let type = 'login';
        if (this.$hasProp('type')) type = this.type;
        else if (this.$hasProp('defaultType')) type = this.defaultType;

        if (!type) throw new Error('无效的type属性');

        return {
            loading: true,
            countries: [
                {
                    name: '中国',
                    code: 86
                },
                {
                    name: '中国香港',
                    code: 852
                },
                {
                    name: '中国澳门',
                    code: 853
                },
                {
                    name: '中国台湾地区',
                    code: 886
                }
            ],
            form: {
                phone: {
                    number: '',
                    code: 86
                },
                password: '',
                verifyCode: ''
            },
            innerType: type,
            bindphoneType: ''
        };
    },
    watch: {
        type(value) {
            this.innerType = value;
            this.form.password = '';
            this.form.verifyCode = '';
        }
    },
    created() {
        this.src = `${UMS_URL}?client_id=gaodingx&client_secret=7da458070e57b98e11d00d9286f23537&redirect_uri=${UMS_URL}/api/oauth/redirect`;
    },
    mounted() {
        this.ums = this.$refs.ums.contentWindow;
    },
    methods: {
        submit(e) {
            e.preventDefault();
        },
        init() {
            this.loading = false;
            this.requestUms('getCountries').then(data => {
                let list = this.countries;
                data.forEach(c => {
                    list = list.concat(c.list.filter(n => !n.name.includes('中国')));
                });

                list.forEach(c => {
                    c.code = parseInt(c.code);
                });

                this.countries = list;
            });
        },
        switchType(type) {
            if (type === this.innerType) return;
            this.lastType = this.innerType;

            if (this.$hasProp('type')) {
                this.$emit('update:type', type);
            }
            else {
                this.innerType = type;
                this.form.password = '';
                this.form.verifyCode = '';
            }
        },
        async onLogin(code, type) {
            const query = getQueryParams(location.href) || {};
            let formData = `code=${code}&last_screen_width=${
                window.screen.width
            }&last_screen_height=${window.screen.height}`;

            if (query && query.hmsr) {
                formData += `&source=${query.hmsr}`;
            }

            const guest = await guestUser.login();
            const XGuestToken = guest.guest_finger && guest.guest_finger !== '' ? {
                'X-Guest-Token': guest.guest_finger
            } : {};

            return request
                .post('/api/sessions/ums', formData, {
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded',
                        ...XGuestToken
                    }
                })
                .then(res => {
                    Tips('登录成功');
                    // submit 成功
                    // @arg action 操作类型 'login' 'register' 'resetpwd' 等
                    this.$emit('success', {
                        action: 'login',
                        type,
                        data: res.data
                    });
                })
                .catch(error => {
                    Tips(error);
                    // submit 失败
                    // @arg action 操作类型 'login' 'register' 'resetpwd' 等
                    // @arg error 失败信息
                    this.$emit('error', {
                        action: 'login',
                        type,
                        error: error
                    });
                });
        },
        requestUms(action, data = {}, headers) {
            return new Promise(resolve => {
                if (this.loading) {
                    const unwatch = this.$watch('loading', () => {
                        unwatch();
                        resolve();
                    });
                }
                else {
                    resolve();
                }
            }).then(() => {
                let timer = null;
                return new Promise((resolve, reject) => {
                    const callback = event => {
                        if (event.origin !== UMS_URL) {
                            return false;
                        }

                        if (
                            event.data.action !== action + '.success' &&
              event.data.action !== action + '.error'
                        ) {
                            return false;
                        }

                        if (event.data.action === action + '.success') {
                            resolve(event.data.data);
                        }
                        else {
                            const error = new Error(event.data.data.message);
                            if (event.data.data.status) error.status = event.data.data.status;
                            reject(error);
                        }
                        clearTimeout(timer);
                        window.removeEventListener('message', callback);
                    };

                    timer = setTimeout(() => {
                        reject(new Error('网络超时'));
                        window.removeEventListener('message', callback);
                    }, 20000);

                    window.addEventListener('message', callback);
                    const guestToken = headers ? { guestToken: headers['X-Guest-Token'] } : {};
                    Object.assign(data, {}, guestToken);
                    // TODO ums 需要处理
                    this.ums.postMessage({ action, data }, UMS_URL);
                });
            });
        }
    }
};
</script>

<style lang="less">
@import "../_styles/base.less";

.@{auth} {
  position: relative;
  width: 367px;
  box-sizing: border-box;
  height: 437px;
  background: #fff;
  box-shadow: 0 0 15px rgba(11, 3, 6, 0.2);
  padding: 43px 43px 48px 43px;

  &&--wechat {
    padding: 43px 59px 48px 59px;
  }

  * {
    box-sizing: border-box;
  }

  & &--qq {
    display: none;
  }

  & &__ums {
    display: none;
  }
}
</style>
