import "./index.css";
import _Promise from "@babel/runtime-corejs2/core-js/promise";
import _parseInt from "@babel/runtime-corejs2/core-js/parse-int";
import "core-js/modules/web.dom.iterable";

/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
import { componentMixin, createComponentName } from '../../utils/base';
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 '../../service/request';
import QQ from './qq';
import { UMS_URL } from '../../utils/constant';
const __vue_script__ = {
  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 = '';
      }
    },

    onLogin(code, type) {
      const formData = `code=${code}&last_screen_width=${window.screen.width}&last_screen_height=${window.screen.height}`;
      return request.post('/api/sessions/ums', formData, {
        headers: {
          'Content-type': 'application/x-www-form-urlencoded'
        }
      }).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 = {}) {
      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);
          this.ums.postMessage({
            action,
            data
          }, UMS_URL);
        });
      });
    }

  }
};
/* template */

var __vue_render__ = function () {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c("form", {
    class: _vm.bem([_vm.innerType]),
    on: {
      submit: _vm.submit
    }
  }, [_vm.innerType === "phone" ? _c("Phone", {
    attrs: {
      countries: _vm.countries
    }
  }) : _vm.innerType === "wechat" ? _c("Wechat") : _vm.innerType == "register" ? _c("Register") : _vm.innerType == "resetpwd" ? _c("Resetpwd") : _vm.innerType == "bindphone" ? _c("BindPhone") : _vm.innerType == "qq" ? _c("QQ") : _c("Wechat"), _vm._v(" "), _vm._m(0)], 1);
};

var __vue_staticRenderFns__ = [function () {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c("iframe", {
    ref: "ums",
    class: _vm.bem("ums"),
    attrs: {
      src: _vm.src,
      frameborder: "0"
    },
    on: {
      load: _vm.init
    }
  });
}];
__vue_render__._withStripped = true;
/* style */

const __vue_inject_styles__ = undefined;
/* scoped */

const __vue_scope_id__ = undefined;
/* module identifier */

const __vue_module_identifier__ = undefined;
/* functional template */

const __vue_is_functional_template__ = false;
/* component normalizer */

import __vue_normalize__ from '../../utils/vue-normalize-component.js';
/* style inject */

/* style inject SSR */

export default __vue_normalize__({
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__
}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined);