<template>
  <common-layout>
    <div class="top">
      <div class="header">
        <img alt="logo" class="logo" :src="Project.project_logo" />

        <div class="title">{{ Project.project_name }}
          <!-- 如果 Project.project_sub_title 不为空，则显示 -->
          <i v-if="Project.project_sub_title"><b>|</b> {{ Project.project_sub_title }}</i>
        </div>
        <!-- <div class="title_en">{{ Project.project_en_name }} <b>|</b> <i>{{ Project.project_en_sub_title }}</i></div> -->
        <div class="desc">
          {{ Project.slogan }}<br />
          <!-- {{ Project.en_slogan }} -->
        </div>
      </div>
    </div>
    <div class="login">
      <a-form @submit="onSubmit" :form="form">
        <a-tabs size="large" :tabBarStyle="{ textAlign: 'center' }" style="padding: 0 2px;">
          <a-tab-pane tab="账户密码登录" key="1">
            <a-alert type="error" :closable="true" v-show="error" :message="error" showIcon
              style="margin-bottom: 24px;" />
            <a-form-item>
              <a-input autocomplete="autocomplete" size="large" placeholder="请输入账户名"
                v-decorator="['name', { rules: [{ required: true, message: '请输入账户名', whitespace: true }] }]">
                <!--  -->
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input size="large" placeholder="请输入密码" autocomplete="autocomplete" type="password"
                v-decorator="['password', { rules: [{ required: true, message: '请输入密码', whitespace: true }] }]">
                <!-- -->
                <a-icon slot="prefix" type="lock" />
              </a-input>
            </a-form-item>





          </a-tab-pane>
          <a-tab-pane tab="手机号登录" key="2" v-if="false">
            <a-form-item>
              <a-input size="large" placeholder="mobile number">
                <a-icon slot="prefix" type="mobile" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-row :gutter="8" style="margin: 0 -4px">
                <a-col :span="16">
                  <a-input size="large" placeholder="captcha">
                    <a-icon slot="prefix" type="mail" />
                  </a-input>
                </a-col>
                <a-col :span="8" style="padding-left: 4px">
                  <a-button style="width: 100%" class="captcha-button" size="large">获取验证码</a-button>
                </a-col>
              </a-row>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
        <div v-if="false">
          <a-checkbox :checked="true">自动登录</a-checkbox>
          <a style="float: right">忘记密码</a>
        </div>
        <a-form-item>
          <a-button :loading="logging" style="width: 100%;margin-top: 24px" size="large" htmlType="submit"
            type="primary">登录</a-button>
        </a-form-item>
        <div v-if="false">
          其他登录方式
          <a-icon class="icon" type="alipay-circle" />
          <a-icon class="icon" type="taobao-circle" />
          <a-icon class="icon" type="weibo-circle" />
          <router-link style="float: right" to="/dashboard/workplace">注册账户</router-link>
        </div>
      </a-form>

      <switch-company v-model="companyShow" :data="companyData" @confirm="companyconfirm"
        ref="switchCompany"></switch-company>


    </div>
    <login-actions ref="loginActions"></login-actions>
  </common-layout>
</template>

<script>
import CommonLayout from '@/layouts/CommonLayout'
import { login, switchCompany, getProject } from '@/services/base/user'
import { setAuthorization } from '@/utils/request'
import { mapMutations } from 'vuex'
import Cookie from 'js-cookie'
import { USER_MODEL } from '@/services/base/api.js';
import LoginActions from '@/components/login/loginActions.vue'




export default {
  name: 'Login',
  components: { CommonLayout, LoginActions },
  data() {
    return {
      logging: false,
      error: '',
      form: this.$form.createForm(this),
      mobileTest: "",
      user: {
        mobile: '',
        password: ''
      },
      Project: [],
      companyShow: false,
      companyData: [],
      company: Cookie.get('company'),
      loginResult: null
    }
  },
  computed: {
  },
  beforeMount() {

    getProject().then(result => { // 获取项目信息
      this.Project = result.data.data
      const project = result.data.data
      this.setProject(project) // 将项目信息存入vuex
    })

    // 设置界面设置 的默认值
    Cookie.set(process.env.VUE_APP_LAYOUT_KEY, 'side')
    Cookie.set(process.env.VUE_APP_THEME_MODE_KEY, 'dark')
    Cookie.set(process.env.VUE_APP_THEME_COLOR_KEY, '#fa541c')

  },
  created() {
    if (this.company != []) {
      // console.log("company:",this.company)
    }
    this.$nextTick(() => {
      setTimeout(() => {
        if (!this.isMiddleAdmin()) {
          this.user.mobile = this.mobileTest;
        }
        this.form.setFieldsValue({
          name: this.user.mobile,
          password: this.user.password
        });

        this.$refs.loginActions.initRoutes({  }); 
 
      }, 1000)
    })  // loadsh的pick方法


  },
  methods: {
    ...mapMutations('account', ['setUid', 'setUser', 'setPermissions', 'setRoutesConfig', 'setSettings', 'setCompany', 'setProject']),


    companyconfirm({ row }) {
      this.companyShow = false;
      //没有选择公司，或者选择了第一个公司，直接登录
      if (!row || row.id == this.companyData[0].id) {
        this.afterLoginSuccess({
          token: this.loginResult.data.access_token,
          access_expire: this.loginResult.data.access_expire,
          uid: this.loginResult.data.uid,
          loginResMsg: this.loginResult.msg
        });
      }
      //选择了其他公司
      else {

        setAuthorization({
          token: this.loginResult.data.access_token,
          expireAt: new Date(this.loginResult.data.access_expire * 1000)
        })

        switchCompany(row.id).then(result => {
          result = result.data;
          this.afterLoginSuccess({
            token: result.data.access_token,
            access_expire: result.data.access_expire,
            uid: result.data.uid,
            loginResMsg: this.loginResult.msg
          });

        })
      }


    },
    isMiddleAdmin() {
      return USER_MODEL == "AdminUser";
    },
    onSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err) => {
        if (!err) {
          this.logging = true
          const name = this.form.getFieldValue('name')
          const password = this.form.getFieldValue('password')
          login(name, password).then(this.afterLogin)
        }
      })
    },
    afterLogin(res) {
      console.log(res)
      this.logging = false
      const loginRes = res.data
      if (loginRes.code == 200) {
        if (!this.isMiddleAdmin()) {



          this.companyData = loginRes.data.company_switch;
          this.loginResult = loginRes;


          if (!this.companyData || !this.companyData.length) {

            this.afterLoginSuccess({
              token: this.loginResult.data.access_token,
              access_expire: this.loginResult.data.access_expire,
              uid: this.loginResult.data.uid,
              loginResMsg: this.loginResult.msg
            });
          } else {

            this.companyShow = true;
          }


          return;
        }

        this.afterLoginSuccess({
          token: loginRes.data.access_token,
          access_expire: loginRes.data.access_expire,
          uid: loginRes.data.uid,
          loginResMsg: loginRes.msg
        });


      } else {
        console.log("登录失败")
        this.error = loginRes.message || loginRes.msg
      }
    },

    afterLoginSuccess({ token, access_expire, uid, loginResMsg }) {


      this.$refs.loginActions.afterLoginSuccess({ token, access_expire, uid, msg: loginResMsg });

    }
  }
}
</script>

<style lang="less" scoped>
.common-layout {
  .top {
    text-align: center;

    .header {
      min-height: 44px;
      width: 30%;
      padding: auto;
      margin: auto;
      position: relative;
      // border: 1px solid black;

      a {
        text-decoration: none;
      }

      .logo {
        height: 80px;
        vertical-align: top;
        margin-bottom: 10px;
        // border: 1px solid black;
      }

      .title {
        font-size: 40px;
        color: @title-color;
        font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
        font-weight: 600;
        position: relative;
        // margin-left: 25%;
        // border: 1px solid black;
        position: relative;
        margin-bottom: 10px;

        i {
          font-size: 16px;
          margin-right: 4px;
          position: absolute;
          right: 0px;
          color: rgb(194, 194, 194);

          b {
            font-weight: 10;
          }

        }
      }

      .title_en {
        color: @title-color;
        font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
        // margin-left: 25%;
        position: relative;

      }
    }

    .desc {
      font-size: 14px;
      color: @text-color-second;
      margin-top: 5px;
      font-size: 20px;
      margin-bottom: 40px;
      // margin-left: 25%;
      // border: 1px solid black;
    }
  }

  .login {
    width: 368px;
    margin: 0 auto;

    @media screen and (max-width: 576px) {
      width: 95%;
    }

    @media screen and (max-width: 320px) {
      .captcha-button {
        font-size: 14px;
      }
    }

    .icon {
      font-size: 24px;
      color: @text-color-second;
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }
  }
}
</style>
