<template>
  <div class="full-screen flex flex-center bg flex-col">
    <div class="login white-bg radius" v-loading="loading">
      <div class="flex flex-center flex-child-average">
        <div class="flex left">
          <img
            src="https://wutong-1302848345.cos.ap-chengdu.myqcloud.com/wtzx/373e3ccd35be4ba2a72376050027612e.png"
            style="
              height: 560px;
              object-fit: contain;
              border-bottom-left-radius: 10px;
              border-top-left-radius: 10px;
            "
          />
        </div>

        <div class="right flex flex-col flex-child-average">
          <div class="flex flex-col flex-justify-between" style="height: 560px">
            <div
              class="flex flex-justify-end"
              style="margin-right: 3px; margin-top: 3px"
            >
              <div>
                <img
                  v-if="qrCodeLogin"
                  src="../assets/img/com.png"
                  style="width: 80px"
                  @click="qrCodeLogin = !qrCodeLogin"
                />
                <img
                  v-else
                  src="../assets/img/code.png"
                  style="width: 80px"
                  @click="qrCodeLogin = !qrCodeLogin"
                />
              </div>
            </div>

            <div
              v-if="qrCodeLogin"
              class="flex flex-center flex-col"
              style="height: 500px; margin-top: -20px"
            >
              <span class="font-24 black bold">欢迎来到梧桐树云平台👏</span>
              <div
                class="flex flex-col flex-center"
                style="height: 360px; width: 360px; margin-top: -20px"
              >
                <vue-qr
                  :currentLevel="3"
                  :logoCornerRadius="4"
                  :logoScale="0.25"
                  :logoSrc="logoSrc"
                  :text="qrCodeText"
                  size="260"
                />
              </div>
              <span
                class="mt-10 bold main-color font-16"
                style="margin-top: -20px"
                >打开微信扫描二维码登陆梧桐树云平台</span
              >
            </div>
            <div v-else class="flex flex-col flex-center" style="height: 500px">
              <span class="font-24 black bold">欢迎来到梧桐树云平台👏</span>
              <div
                class="flex flex-col flex-center mt-5"
                style="width: 450px; height: 400px"
              >
                <el-form ref="loginForm" :model="form" :rules="rules">
                  <el-form-item prop="name">
                    <el-input
                      v-model="form.name"
                      placeholder="用户帐号"
                      prefix-icon="Avatar"
                      size="large"
                    />
                  </el-form-item>
                  <el-form-item prop="pass">
                    <el-input
                      v-model="form.pass"
                      :type="flag ? 'text' : 'password'"
                      placeholder="密码"
                      prefix-icon="WalletFilled"
                      size="large"
                    >
                      <template v-slot:suffix>
                        <div class="pointer" @click="flag = !flag">
                          <el-icon v-if="!flag">
                            <Hide />
                          </el-icon>
                          <el-icon v-else>
                            <View />
                          </el-icon>
                        </div>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="code">
                    <el-input
                      v-model="form.code"
                      class="append"
                      placeholder="验证码"
                      prefix-icon="Refresh"
                      size="large"
                      @keyup.enter="submint"
                    >
                      <template v-slot:append>
                        <img
                          :src="code"
                          class="pic"
                          @click="init"
                          style="
                            height: 40px;
                            background-color: red;
                            background-blend-mode: lighten;
                          "
                          alt="code"
                        />
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item>
                    <div
                      class="flex flex-align-center flex-justify-between full-width"
                    >
                      <div></div>
                      <el-link :underline="false" class="font-12" type="primary"
                        >忘记密码?</el-link
                      >
                    </div>
                  </el-form-item>
                </el-form>
                <el-button
                  size="large"
                  style="width: 78%"
                  type="primary"
                  @click="submint"
                  >登录</el-button
                >
                <div class="flex flex-col mt-10 flex-center">
                  <span class="grey-6">由梧桐研究院提供技术支持</span>
                  <span class="grey-6 mt-5">使用问题请咨询：13908866200</span>
                  <el-button
                    color="#558FF1"
                    @click="
                      download(
                        'https://wutong-1302848345.cos.ap-chengdu.myqcloud.com/wtzx/a53cc056c3914ae9884992dafe7a9679.pdf'
                      )
                    "
                    style="width: 160px"
                    plain
                    class="mt-10 blockss"
                  >
                    点击下载用户指南
                  </el-button>
                  <span class="grey-6 mt-5 font-12 mt-20"
                    >为了获得最佳体验，您可以<span
                      class="blue pointer"
                      @click="
                        download('https://www.google.cn/intl/zh-CN/chrome/')
                      "
                      >点击此处</span
                    >获取Chrome 浏览器</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <foolter />
    </div>
  </div>
</template>

<route>
{
meta: {
layout: 'empty',
},
}
</route>

<script>
import md5 from 'js-md5'
import { useStore } from '@/store/user.js'
import { removeToken, setToken } from '../utils/auth.js'
import permissionStore from '@/store/permission.js'
import VueQr from 'vue-qr/src/packages/vue-qr.vue'
import foolter from '@/layout/foolter.vue'

export default {
  name: 'login',
  components: { VueQr, foolter },
  watch: {
    qrCodeLogin: {
      handler(val) {
        if (val) {
          this.qrCode()
          this.checkLogin()
        }
      },
      immediate: true
    }
  },
  setup() {
    const user = useStore()
    const permission = permissionStore()
    return { user, permission }
  },
  data() {
    return {
      flag: false,
      form: {
        name: '',
        pass: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入用户帐号', trigger: 'blur' }
          // { min: 11, max: 11, message: '请输入11位手机号', trigger: 'blur' }
        ],
        pass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 5, max: 5, message: '验证码不正确', trigger: 'blur' }
        ]
      },
      code: '',
      header: '',
      qrCodeLogin: false,
      time: null,
      qrCodeText: '',
      sessionId: '',
      logoSrc: new URL('../assets/img/logo.png', import.meta.url).href,
      dev: true,
      loading: false
    }
  },
  created() {
    this.permission.cleanPermission()
    // fixme prod 环境暂时开启账号登录功能
    // this.dev = window.location.href.indexOf('localhost') > -1 || window.location.href.indexOf('https://dev.wutongshucloud.com/') > -1 || window.location.href.indexOf('192.168.31') > -1
    this.dev =
      window.location.href.indexOf('localhost') > -1 ||
      window.location.href.indexOf('192.168.31') > -1
    removeToken()
    this.init()
  },
  unmounted() {
    clearInterval(this.time)
  },
  methods: {
    init() {
      const dev =
        window.location.href.indexOf('dash.wutongshucloud.com') > -1 ||
        window.location.href.indexOf('localhost') > -1
      sessionStorage.setItem('dev', dev)
      this.$api.login.captcha().then(res => {
        this.code = res.image
        this.header = res.key
      })
      const menu = { active: 0, subActive: 0 }
      localStorage.setItem('index', JSON.stringify(menu))
      localStorage.removeItem('data-type')
    },
    submint() {
      this.$refs.loginForm.validate(res => {
        if (res) {
          const params = {
            tenantId: '000000',
            username: this.form.name,
            password: md5(this.form.pass),
            grant_type: 'captcha',
            scope: 'all',
            type: 'account'
          }
          const header = {
            captchaKey: this.header,
            captchaCode: this.form.code
          }
          this.loading = true
          this.$api.login.login(params, header).then(res => {
            this.loading = false
            if (res.error_description) {
              this.$message.error(res.error_description)
              this.init()
            } else {
              setToken(res.access_token)
              this.user.setUserInfo({ name: res.real_name })
              this.getInfo()
            }
          })
        } else {
          return false
        }
      })
    },
    download(url) {
      window.open(
        url,
        '_blank' // <- This is what makes it open in a new window.
      )
    },
    loginAdmin() {
      this.form.name = '15587166921'
      this.form.pass = 'wtkj@123'
    },
    loginOther() {
      this.form.name = '15587160283'
      this.form.pass = 'wtkj@123'
    },
    getInfo() {
      this.$api.login.getUserInfo().then(res => {
        if (res.code === 200) {
          // 保存信息
          if (res.data.type === 3) {
            res.data.typeName = '机构'
          } else {
            res.data.typeName = '服务商'
          }
          this.user.setUserInfo(res.data)
          this.$router.replace('/')
        }
      })
    },
    checkLogin() {
      let count = 0
      this.time = setInterval(() => {
        count = count + 1
        if (this.qrCodeLogin === false) {
          clearInterval(this.time)
        }
        if (count === 60) {
          this.qrCode()
          count = 0
        }
        if (this.sessionId) {
          this.codeLogin()
        } else {
          this.codeLogin()
        }
      }, 1000)
    },
    qrCode() {
      this.$api.login.qrCode().then(res => {
        if (res.code === 200) {
          this.sessionId = res.data
          this.qrCodeText =
            'https://prod.wutongshucloud.com/login?id=' + this.sessionId
        }
      })
    },
    codeLogin() {
      this.$api.login.qrCodeLogin({ sessionId: this.sessionId }).then(res => {
        if (res.code === 200) {
          const tmp = res.data
          if (Object.prototype.hasOwnProperty.call(tmp, 'phone')) {
            const params = {
              tenantId: '000000',
              phone: res.data.phone,
              openId: res.data.openId,
              grant_type: 'qrcode',
              scope: 'all',
              type: 'account'
            }
            this.$api.login.loginByCode(params).then(res => {
              if (res.error_description) {
                this.$message.error(res.error_description)
              } else {
                clearInterval(this.time)
                setToken(res.access_token)
                this.getInfo()
                this.$router.replace('/')
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
//noinspection ALL
.bg {
  background-image: url('https://wutong-1302848345.cos.ap-chengdu.myqcloud.com/wtzx/7667edec62f44063a50c66e8654eaa87.png');
  .footer {
    position: fixed;
    bottom: 50px;
    color: white;
  }
}

.login {
  box-shadow: 5px 10px 10px 5px rgba(0, 0, 0, 0.28);

  .left {
    height: auto;

    .logo-main {
      width: 80%;
    }
  }

  .right {
    width: 560px;
    height: auto;

    .form {
    }
  }
}

.append {
  :deep(.el-input-group__append) {
    background-color: white;
  }

  .pic {
    border-top: #dddfe5 1px solid;
    border-bottom: #dddfe5 1px solid;
  }
}
</style>
