<template xmlns="">
  <div>
    <top-menu :methodType="1"></top-menu>
    <div>
      <div class="container" style="overflow: hidden">
        <!-- <div class="logo"></div> -->
        <div class="processPic">
          <img
              src="@/assets/images/process.gif"
              style="width: 95%; height: 100%"
          />
        </div>
        <!-- 登录区域 -->
        <!-- <div class="content" style="margin-top: 1%; margin-left: 4%"></div> -->
        <div class="content" style="margin-left: 6%; z-index: 1">
          <div class="loginLeft">
            <div style="width: 100%; height: 100%">
              <h1 style="font-size: 32px; text-align: center; margin: 0 auto">
                扫码登录
              </h1>
              <div style="width: 70%; height: 70%; margin: 15px auto 0 auto">
                <img
                    :src="imgData"
                    style="width: 100%; height: 100%"
                    @click="reflushFlag && reflushErWei()"
                />
              </div>
              <div style="width: 100%;height: 25%;text-align: center;margin-top: 10px;">
                <p style="margin-bottom: 0px">
                  请使用"会助理"小程序扫描二维码进入平台
                </p>
                <p style="margin-bottom: 0px">
                  二维码剩余有效时间:
                  <span style="color: red">{{ effectiveTime }}</span> s
                </p>
                <!-- <el-button @click="testLogin">测试登录</el-button> -->
              </div>
            </div>
          </div>
          <div class="loginRight">
            <div style="width: 80%; height: 100%; margin: 60px auto">
              <h1 style="font-size: 32px; text-align: center; margin: 0 auto">
                手机号登录
              </h1>
              <el-form
                  ref="loginForm"
                  :model="loginForm"
                  :rules="LoginRules"
                  style="margin-left: 10px; margin-top: 20px"
              >
                <!-- 账号密码登录 -->
                <div v-if="loginForm.loginType === 'uname'">
                  <el-form-item prop="mobile">
                    <el-input
                        v-model="loginForm.mobile"
                        type="text"
                        auto-complete="off"
                        placeholder="请输入手机号"
                        @blur="moblieBlur()"
                        resize="vertical"
                        oninput="if(value.length>11)value=value.slice(0,11)"
                    >
                      <svg-icon
                          slot="prefix"
                          icon-class="phone"
                          class="el-input__icon input-icon"
                      />
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="password">
                    <el-input
                        v-model="loginForm.password"
                        type="password"
                        auto-complete="off"
                        placeholder="请输入密码"
                        @keyup.enter.native="getCode"
                    >
                      <svg-icon
                          slot="prefix"
                          icon-class="password"
                          class="el-input__icon input-icon"
                      />
                      <el-checkbox
                          slot="suffix"
                          v-model="loginForm.rememberMe"
                          style="float: right; right: 0px; color: #999999"
                      >记住密码
                      </el-checkbox>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="tenantName" v-if="tenantEnable">
                    <el-select
                        v-model="loginForm.tenantName"
                        placeholder="请选择机构名称"
                    >
                      <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      >
                      </el-option>
                    </el-select>
                    <!-- <el-select
                      v-model="loginForm.tenantName"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入机构名称"
                      :remote-method="remoteMethod"
                      :loading="loadingTenant"
                    >
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                      <svg-icon
                        slot="prefix"
                        icon-class="tree"
                        class="el-input__icon input-icon"
                      />
                    </el-select> -->
                    <!-- <el-input v-model="loginForm.tenantName" type="text" auto-complete="off" placeholder="请输入机构名称">
                    <svg-icon slot="prefix" icon-class="tree" class="el-input__icon input-icon" />
                  </el-input> -->
                  </el-form-item>
                  <el-form-item prop="verifyInCode">
                    <el-input
                        v-model="loginForm.verifyInCode"
                        type="text"
                        auto-complete="off"
                        placeholder="请输入验证码"
                        style="width: 60%"
                        @keyup.enter.native="getCode"
                    >
                      <svg-icon
                          slot="prefix"
                          icon-class="question"
                          class="el-input__icon input-icon"
                      />
                    </el-input>
                    <img
                        :src="verifyCode"
                        style="width: 40%"
                        @click="refreshVerifyCode()"
                        alt="验证码"
                    />
                  </el-form-item>
                </div>
                <!-- 下方的登录按钮 -->
                <el-form-item style="width: 100%; margin-top: 30px">
                  <el-button
                      :loading="loading"
                      size="medium"
                      type="primary"
                      style="width: 100%;height: 40px"
                      @click.native.prevent="getCode"
                  >
                    <span v-if="!loading">登 录</span>
                    <span v-else>登 录 中...</span>
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <!-- 注册 -->
          <!-- <div class="rightUp">
            <img
              src="../assets/images/upRight1.png"
              style="width: 100%; height: 100%"
            />
          </div> -->
        </div>
        <div class="loginTitle">
          <span class="loginTitleStr">赋 予 装 备 智 慧 动 能 · 构 建 场 景 数 字 脉 络</span>
        </div>
        <!-- 图形验证码 -->
        <Verify
            ref="verify"
            :captcha-type="'blockPuzzle'"
            :img-size="{ width: '400px', height: '200px' }"
            @success="handleLogin"
        />

      </div>
      <div style="margin: 0 auto;width: 75%;padding: 3% 0" ref="sortableContainer">
        <!--        <div shadow="hover" v-for="(item,index) in [1,2,3,4,5,6]" :key="index"-->
        <div style="padding: 1.2%;display: inline-block;width: 33.3333%;"  v-for="(item,index1) in loginModuleData" :key="index1">
          <div
               class="module-item"
               :style="{height: vModuleHeight +'px'}"
          >
            <div style="height: 10%;padding: 10px 10px 5px"
                 :style="{fontSize: vModuleFontSize1 +'px'}"
            >
              {{ item.name }}
            </div>
            <div style="height: 80%;padding:10px 10px 10px">
              <div style="height: 85%">
                <img :src="item.imgUrls" width="100%" height="100%">
              </div>
              <div style="height: 15%;text-align: center;margin: 10px 0"
                   :style="{fontSize: vModuleFontSize2 +'px'}"
              >
                {{ item.digest }}
              </div>
            </div>
            <div style="text-align: center;height: 10%;margin-top: 5px">
              <el-button size="mini" style="background: rgb(228,241,255);color: rgb(24,144,255);border: none;font-weight: 500">了解详情<i class="el-icon-arrow-right"></i></el-button>
            </div>
          </div>
        </div>
      </div>
      <div style="margin: 0 auto;width: 75%;padding: 0.8%">
        <div v-html="bottomModData.pageContent"></div>
      </div>
      <!-- footer class="footer"-->
      <div style="margin: 50px;text-align: center;font-size: 20px"
           :style="{fontSize: bottomFontSize +'px'}"
      >
        <div style="margin: 10px 0">
          <a style="margin: 0 15px">会山科技</a> |
          <a style="margin: 0 15px">版权所有</a> |
          <a style="margin: 0 15px">市场合作</a> |
          <a style="margin: 0 15px">关于会助理</a> |
          <a style="margin: 0 15px">使用协议</a> |
          <a style="margin: 0 15px">隐私条款</a>
        </div>
        <div style="margin: 20px 0">
          {{ version }} <span style="margin-left: 30px">开发者：会山科技</span>
        </div>
        <div style="margin: 10px 0">
          沪 I C P 备 1 9 0 0 7 0 6 1 号 - 1
        </div>
        Copyright © 2023-2024 willalp.com All Rights Reserved.
      </div>
    </div>
  </div>
</template>

<script>
import {
  sendSmsCode,
  socialAuthRedirect,
  createLoginQrcode,
  getQrcodeId,
  checkScanStatus,
  loginScan,
  loginScanResult,
  getVerify
} from '@/api/login'
import {
  getTenantIdByName,
  getAllTenantList,
  getAllTenantListByPhone
} from '@/api/system/tenant'
import { SystemUserSocialTypeEnum } from '@/utils/constants'
import { getCaptchaEnable, getTenantEnable } from '@/utils/ruoyi'
import {
  getPassword,
  getRememberMe,
  getTenantName,
  getUsername,
  getMobile,
  removePassword,
  removeRememberMe,
  removeTenantName,
  removeUsername,
  setPassword,
  setRememberMe,
  setTenantId,
  setTenantName,
  setUsername,
  setMobile,
  setVerifyInCode,
  setCaptchaKey
} from '@/utils/auth'

import Verify from '@/components/Verifition/Verify'
import { resetUserPwd, getUsernameByMobile } from '@/api/system/user'
import topMenu from './components/login/topMenu.vue'
import { getConfigData } from '@/api/infra/config'
import { getLoginPagePopularizeModuleConfigPage } from '@/api/supplier/loginPagePopularizeModuleConfig'

export default {
  name: 'Login',
  components: {
    Verify,
    topMenu
  },
  data() {
    return {
      bottomModData: '',
      loginModuleData: [],
      vModuleHeight: window.innerHeight * 0.45,
      vModuleFontSize1: window.innerHeight * 0.022,
      vModuleFontSize2: window.innerHeight * 0.015,
      bottomFontSize: window.innerHeight * 0.018,
      version: '会助理平台 v2.0.2 版',
      options: [],
      states: [],
      list: [],
      loadingTenant: false,
      verifyKey: '',
      verifyCode: '',
      reflushFlag: false,
      qrcodeId: '',
      effectiveTime: 0,
      imgData: null,
      loginT: 1,
      codeUrl: '',
      captchaEnable: true,
      tenantEnable: true,
      mobileCodeTimer: 0,
      loginForm: {
        loginType: 'uname',
        mobile: '',
        password: '',
        captchaVerification: '',
        mobileCode: '',
        rememberMe: false,
        tenantName: '',
        timer: null
      },
      scene: 21,

      LoginRules: {
        // username: [
        //   { required: true, trigger: "blur", message: "用户名不能为空" },
        // ],
        verifyInCode: [
          { required: true, trigger: 'blur', message: '验证码不能为空' }
        ],
        password: [
          { required: true, trigger: 'blur', message: '密码不能为空' }
        ],
        mobile: [
          { required: true, trigger: 'blur', message: '手机号不能为空' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              if (/^1(2|3|4|5|7|8|9)\d{9}$/.test(value) === false) {
                callback(new Error('手机号格式错误'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        tenantName: [
          { required: true, trigger: 'blur', message: '机构不能为空' },
          {
            validator: (rule, value, callback) => {
              // debugger
              getTenantIdByName(value).then((res) => {
                const tenantId = res.data
                if (tenantId && tenantId >= 0) {
                  // 设置机构
                  setTenantId(tenantId)
                  callback()
                } else {
                  callback('机构不存在')
                }
              })
            },
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      redirect: undefined,
      // 枚举
      SysUserSocialTypeEnum: SystemUserSocialTypeEnum
    }
  },
  beforeCreate() {
    sessionStorage.clear()
  },
  created() {
    //监听窗口大小变化
    window.addEventListener('resize', this.adVModuleHeightHeight)
    getVerify().then((res) => {
      this.verifyCode = res.captchaImg
      this.verifyKey = res.captchaKey
    })
    getConfigData('login_module').then(res => {
      if (res.data) {
        this.loginModuleData = JSON.parse(res.data.value)
      }
    })
    // 机构开关
    this.tenantEnable = getTenantEnable()
    if (this.tenantEnable) {
      getTenantIdByName(this.loginForm.tenantName).then((res) => {
        // 设置机构
        const tenantId = res.data
        if (tenantId && tenantId >= 0) {
          setTenantId(tenantId)
        }
      })
    }

    // 验证码开关
    this.captchaEnable = getCaptchaEnable()
    // 重定向地址
    this.redirect = this.$route.query.redirect
        ? decodeURIComponent(this.$route.query.redirect)
        : undefined
    this.getCookie()
    this.generateErWeima()
    this.getLoginPageData('bottomMod', 3, this.bottomModData)
  },
  methods: {
    /** 查询列表 */
    getLoginPageData(parentId, type, data) {
      let queryParams = {
        type: type,
        parentId: parentId,
        status: 1
      }
      // 执行查询
      getLoginPagePopularizeModuleConfigPage(queryParams).then(response => {
        if (response.data) {
          switch (parentId) {
            case 'aboutHZL':
              this.aboutHZLData = response.data.list[0]
              break
            case 'bottomMod':
              this.bottomModData = response.data.list[0]
              if (this.bottomModData) {
                this.bottomModData.pageContent = this.bottomModData.pageContent.replace(/<img/g,
                    '<img style=\'width:100%;height:auto;\'')
              }
              break
            default:
              response.data.list.forEach(item => {
                data.data.push(item)
              })
          }
        }
      })
    },
    adVModuleHeightHeight() {
      this.vModuleHeight = window.innerHeight * 0.45
    },
    moblieBlur() {
      getAllTenantListByPhone(this.loginForm.mobile).then((response) => {
        this.states = response.data
        this.list = this.states.map((item) => {
          return {
            value: `${item.name}`,
            label: `${item.name}`
          }
        })
        this.options = this.list
        // this.loginForm.tenantName = this.list[0].value;
        this.$set(this.loginForm, 'tenantName', this.list[0].value)
      })
    },
    /** 机构输入搜索 */
    remoteMethod(query) {
      getAllTenantListByPhone(this.loginForm.mobile).then((response) => {
        this.states = response.data
        this.list = this.states.map((item) => {
          return {
            value: `${item.name}`,
            label: `${item.name}`
          }
        })
      })
      if (query !== '') {
        this.loadingTenant = true
        setTimeout(() => {
          this.loadingTenant = false
          this.options = this.list.filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    refreshVerifyCode() {
      getVerify().then((res) => {
        this.verifyCode = res.captchaImg
        this.verifyKey = res.captchaKey
      })
    },
    testLogin() {
      var testForm = {
        code: '0f1Qg62w3EKP313My74w3sHBVk1Qg62q',
        loginType: 0,
        mobile: '15612345678',
        password: 'admin123',
        tenantId: 1,
        qrcode: this.qrcodeId
      }
      loginScan(testForm).then((res) => {
        console.log(res.data)
      })
    },
    reflushErWei() {
      this.generateErWeima()
    },
    generateErWeima() {
      getQrcodeId().then((res) => {
        this.qrcodeId = res.data
        createLoginQrcode(this.qrcodeId).then((res) => {
          let blob = new Blob([res], {
            type: 'image/png'
          })
          let url = window.URL.createObjectURL(blob)
          // 将图片转换成img标签可以识别的url
          this.imgData = url
          //开始倒计时
          this.effectiveTime = 120
          this.timer = setInterval(() => {
            if (this.effectiveTime > 0) {
              //检查扫码登录状态
              checkScanStatus(this.qrcodeId).then((res) => {
                let scanState = res.data
                if (scanState == null) {
                  this.imgData = require('@/assets/images/reflushErWei.png')
                  this.reflushFlag = true
                  clearInterval(this.timer)
                  this.$modal.msgError('二维码已过期，请刷新二维码后重试')
                  return
                } else if (scanState == 'yesLogin') {
                  //获取登录信息信息后跳转页面
                  loginScanResult(this.qrcodeId)
                      .then((res) => {
                        const data = res.data
                        localStorage.clear()
                        localStorage.setItem('ACCESS_TOKEN', data.accessToken)
                        localStorage.setItem('REFRESH_TOKEN', data.refreshToken)
                        localStorage.setItem('USER_ID', data.userId)
                        localStorage.setItem('EXPIRES_TIME', data.expiresTime)
                        this.$router.push({ path: '/' })
                        this.effectiveTime = 0
                        clearInterval(this.timer)
                      })
                      .catch(() => {
                        this.loading = false
                      })
                }
              })

              this.effectiveTime--
            } else {
              clearInterval(this.timer)
              this.imgData = require('@/assets/images/reflushErWei.png')
              this.reflushFlag = true
            }
          }, 1000)
        })
      })
    },
    getCode() {
      // 情况一，未开启：则直接登录
      if (!this.captchaEnable) {
        this.handleLogin({})
        return
      }

      // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
      // 弹出验证码
      this.$refs.verify.show()
    },
    getCookie() {
      const username = getUsername()
      const password = getPassword()
      const rememberMe = getRememberMe()
      const tenantName = getTenantName()
      const mobile = getMobile()
      this.loginForm = {
        ...this.loginForm,
        username: username ? username : '',
        mobile: mobile ? mobile : this.loginForm.mobile,
        password: password ? password : this.loginForm.password,
        rememberMe: rememberMe ? getRememberMe() : false,
        tenantName: tenantName ? tenantName : this.loginForm.tenantName
      }
    },
    handleLogin(captchaParams) {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          // 设置 Cookie
          if (this.loginForm.rememberMe) {
            getUsernameByMobile(this.loginForm.mobile).then((res) => {
              if (res.data != null) {
                setUsername(res.data.username)
              }
            })
            setMobile(this.loginForm.mobile)
            setPassword(this.loginForm.password)
            setRememberMe(this.loginForm.rememberMe)
            setTenantName(this.loginForm.tenantName)
            // setVerifyInCode(this.loginForm.verifyInCode);
            // setCaptchaKey(this.captchaKey);
          } else {
            removeUsername()
            removePassword()
            removeRememberMe()
            removeTenantName()
          }
          this.loginForm.captchaKey = this.verifyKey
          this.loginForm.captchaVerification =
              captchaParams.captchaVerification
          this.$store
              .dispatch(
                  this.loginForm.loginType === 'sms' ? 'SmsLogin' : 'Login',
                  this.loginForm
              )
              .then(() => {
                this.$router.push({ path: this.redirect || '/' }).catch(() => {
                })
              })
              .catch(() => {
                console.log('登陆失败！！！！！！！！！！！')
                this.refreshVerifyCode()
                this.loading = false
              })
        }
      })
    },
    async doSocialLogin(socialTypeEnum) {
      // 设置登录中
      this.loading = true
      let tenant = false
      if (this.tenantEnable) {
        await this.$prompt('请输入机构名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
            .then(async({ value }) => {
              await getTenantIdByName(value).then((res) => {
                const tenantId = res.data
                tenant = true
                if (tenantId && tenantId >= 0) {
                  setTenantId(tenantId)
                }
              })
            })
            .catch(() => {
              // 取消登录按钮 loading状态
              this.loading = false

              return false
            })
      } else {
        tenant = true
      }
      if (tenant) {
        // 计算 redirectUri
        const redirectUri =
            location.origin +
            '/social-login?' +
            encodeURIComponent(
                'type=' +
                socialTypeEnum.type +
                '&redirect=' +
                (this.redirect || '/')
            ) // 重定向不能丢
        // const redirectUri = 'http://127.0.0.1:48080/api/gitee/callback';
        // const redirectUri = 'http://127.0.0.1:48080/api/dingtalk/callback';
        // 进行跳转
        socialAuthRedirect(
            socialTypeEnum.type,
            encodeURIComponent(redirectUri)
        ).then((res) => {
          // console.log(res.url);
          window.location.href = res.data
        })
      }
    },
    /** ========== 以下为升级短信登录 ========== */
    getSmsCode() {
      if (this.mobileCodeTimer > 0) return
      this.$refs.loginForm.validate((valid) => {
        if (!valid) return
        sendSmsCode(
            this.loginForm.mobile,
            this.scene,
            this.loginForm.uuid,
            this.loginForm.code
        ).then((res) => {
          this.$modal.msgSuccess('获取验证码成功')
          this.mobileCodeTimer = 60
          let msgTimer = setInterval(() => {
            this.mobileCodeTimer = this.mobileCodeTimer - 1
            if (this.mobileCodeTimer <= 0) {
              clearInterval(msgTimer)
            }
          }, 1000)
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/login.scss";

//.el-form-item {
//  margin-bottom: 20px !important;
//}

.module-item {
  border-radius: 10px;
  box-shadow: 0 0 10px #c0cfe2;
  /*transition: transform 0.1s ease;*/
}

.loginTitle {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.loginTitleStr {
  position: absolute;
  color: #4588f6;
  font-size: 28px;
  bottom: 12%;
  right: 9%;
}

::v-deep .el-input__inner {
  border-radius: 0px;
  border-top-width: 0px;
  border-left-width: 0px;
  border-right-width: 0px;
  border-bottom-width: 1px;
  /*outline: medium;*/
}

.rightUp {
  width: 12.3%;
  height: 20%;
  background-color: yellow;
  right: 0px;
  // z-index: 9999;
  position: absolute;
}

.loginLeft {
  width: 45%;
  height: 80%;
  margin: 6% 1%;
  float: left;
  // z-index: 1;
  border-width: 0 4px 0 0;
  border-style: solid;
  border-color: #c4cbd7;
}

.loginRight {
  width: 50%;
  height: 100%;
  margin: 1% 0;
  float: left;
  // z-index: 1;
}

.processPic {
  //margin-top: 1%;
  // margin-left: 3%;
  width: 35%;
}

.oauth-login {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.oauth-login-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.oauth-login-item img {
  height: 25px;
  width: 25px;
}

.oauth-login-item span:hover {
  text-decoration: underline red;
  color: red;
}

.sms-login-mobile-code-prefix {
  :deep(.el-input__prefix) {
    top: 22%;
  }
}

.dropdown-link-text {
  font-size: 20px;
  font-weight: bold;
}
</style>
