<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/8471f31e2e0d4bf4a560887500d74aa0.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 v-if="!dev">
                <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.2"
                  :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 v-if="dev" class="flex flex-center full-width">
                        <el-button type="primary" plain @click="loginTest(1)"
                          >测试管理员001
                        </el-button>
                        <el-button type="primary" plain @click="loginTest(2)"
                          >测试用户001
                        </el-button>
                      </div>
                    </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 mt-5"
                    >开通账号及使用问题请咨询：15587166921</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.checkLogin()
        }
      },
      immediate: true
    },
    qrCodeText: {
      handler(val) {
        if (val.length === 0) {
          this.qrCode()
        }
      },
      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: 16, message: '长度在 3 到 16 个字符', 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 环境暂时开启账号登录功能
    removeToken()
    this.init()
  },
  unmounted() {
    clearInterval(this.time)
  },
  methods: {
    init() {
      this.dev =
        window.location.href.indexOf('https://test.wutongshucloud.com/') > -1 ||
        window.location.href.indexOf('192.168.31') > -1
      sessionStorage.setItem('dev', this.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()
              this.menus()
            }
          })
        } else {
          return false
        }
      })
    },
    download(url) {
      window.open(
        url,
        '_blank' // <- This is what makes it open in a new window.
      )
    },
    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)
        }
      })
    },
    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.menus()
              }
            })
          }
        }
      })
    },
    menus() {
      this.$api.common.getMenus().then(res => {
        if (res.code === 200 && res.data.length > 0) {
          const first = res.data[0]
          if (first.children && first.children.length > 0) {
            this.$router.replace(first.children[0].path)
            localStorage.setItem(
              'data-type',
              first.children[0].remark ? first.children[0].remark : 'project'
            )
          } else {
            this.$router.replace(first.path)
            localStorage.setItem(
              'data-type',
              first.remark ? first.remark : 'project'
            )
          }
        }
      })
    },
    loginTest(type) {
      if (type === 1) {
        this.form.name = 'admin001'
        this.form.pass = 'admin123456'
      } else if (type === 2) {
        this.form.name = 'user001'
        this.form.pass = 'admin123456'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
//noinspection ALL
.bg {
  background-image: url('https://wutong-1302848345.cos.ap-chengdu.myqcloud.com/wtzx/7667edec62f44063a50c66e8654eaa87.png');
  background-size: cover;
  background-repeat: no-repeat;

  .footer {
    position: fixed;
    bottom: 10px;
    color: #eeeeee;
  }
}

.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;
  }
}

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

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