<template>
  <div
    v-if="!code"
    class="es-login-screen"
    :class="{
      'es-login-medium': size == 'medium',
      'es-login-small': size == 'small',
      'es-login-mini': size == 'mini'
    }"
    :style="getBackground(loginBackgroundImg)"
  >
    <div
      v-if="loginDownloadApp"
      class="es-download-app"
      @click="handleDownLoadApps"
    >
      <i class="el-icon-mobile-phone"></i>下载APP
    </div>
    <img v-if="loginLogoImg" class="es-login-logo" :src="loginLogoImg" />
    <slot></slot>
    <slot name="warning" :contents="warningText"></slot>
    <div
      class="es-login"
      v-loading.fullscreen.lock="submit"
      element-loading-text="登录中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.65)"
      :class="{
        'es-simple': mode == 'simple',
        'es-adaptive': !isScale && !isFixed
      }"
      :style="transform"
    >
      <img v-if="loginNameImg" class="es-login-name" :src="loginNameImg" />
      <div
        class="es-login-main"
        :style="getBackground(loginMainImg)"
        :class="{
          'es-models': modelLength > 2 && mode !== 'complex',
          'es-complex': mode == 'complex'
        }"
      >
        <div class="es-login-complex-title" v-if="mode == 'complex'">
          欢迎登录
        </div>
        <div
          v-if="modelLength > 1 || mode == 'complex'"
          :class="{
            'es-login-models': modelLength > 2 && mode !== 'complex',
            'es-login-model': modelLength == 2 || mode == 'complex'
          }"
        >
          <template v-if="this.mode == 'complex'">
            <template v-if="loginModel.indexOf('3') > -1">
              <template v-for="item in switchs">
                <div
                  v-if="item.tips"
                  v-show="switchActive != item.type"
                  class="es-login-model-tips"
                  :key="item.type + '_0'"
                  :style="getBackground(item.background)"
                >
                  {{ item.tips }}
                </div>
                <span
                  v-show="switchActive != item.type"
                  class="es-icon-box"
                  @click="switchLoginType(item)"
                  :title="modelLength > 2 ? item.name : ''"
                  :key="item.type + '_1'"
                >
                  <i :class="[item.icon, 'es-icon']"></i>
                </span>
              </template>
            </template>
          </template>
          <template v-else>
            <template v-for="item in icons">
              <div
                class="es-login-model-item-tips"
                v-if="modelLength == 2"
                v-show="active != item.type && modelTips"
                :key="item.type"
              >
                {{ item.name }}点这里<i class="es-icon-shoushiyou"></i>
              </div>
              <span
                v-show="modelLength > 2 || active != item.type"
                class="es-icon-box"
                @click="switchLogin(item)"
                :title="item.name"
                :key="item.name"
                :class="[{ 'es-icon-active': active == item.type }]"
              >
                <i :class="[item.icon, 'es-icon']"></i>
              </span>
            </template>
          </template>
        </div>
        <div v-if="loginTitleImg" class="es-login-title-image">
          <img class="es-login-title-img" :src="loginTitleImg" />
        </div>
        <template v-else-if="mode !== 'complex'">
          <slot name="login-title" :type="active">
            <div class="es-login-title">
              <span class="es-login-title-content">{{ title }}</span>
            </div>
          </slot>
        </template>
        <div class="es-login-form-box">
          <div
            v-if="mode == 'complex'"
            class="es-login-complex-models"
            :class="{ 'es-complex-title': active == '3' }"
          >
            <template v-if="active == '3'">
              <div class="es-login-complex-models-item es-active">
                {{ title }}
              </div>
            </template>
            <template v-else>
              <template v-for="item in icons">
                <div
                  v-if="item.type !== '3'"
                  class="es-login-complex-models-item"
                  :class="{ 'es-active': active == item.type }"
                  :key="item.type"
                  @click="switchLogin(item)"
                >
                  {{ item.name }}
                </div>
              </template>
            </template>
          </div>
          <template v-if="isShow(active) && (active == 0 || active == 12)">
            <el-form
              :ref="'login' + active"
              class="es-login-form"
              :model="formData"
            >
              <el-form-item prop="username" :rules="username.rules">
                <es-input
                  v-model="formData.username"
                  type="text"
                  name="username"
                  tabindex="1"
                  exclude
                  :placeholder="username.placeholder"
                  :focusShow="focusShow"
                  :data="users"
                  @select="handleBlur"
                >
                  <template slot="prefix">
                    <i class="es-icon-yonghu es-label-user"></i>
                  </template>
                </es-input>
              </el-form-item>
              <el-form-item prop="password" :rules="password.rules">
                <el-input
                  v-model="formData.password"
                  name="password"
                  tabindex="2"
                  type="password"
                  :placeholder="password.placeholder"
                  autocomplete="off"
                  show-password
                  @paste.native.capture="handlePaste"
                  @copy.native.capture="handlePaste"
                >
                  <template slot="prefix">
                    <i class="es-icon-mima es-label-password"></i>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item
                prop="identifyingCode"
                :rules="[
                  {
                    required: true,
                    message: '验证码不能为空',
                    trigger: 'change'
                  }
                ]"
                v-if="imgCode || showVerifyCode"
              >
                <el-input
                  name="identifyingCode"
                  tabindex="3"
                  type="text"
                  v-model="formData.identifyingCode"
                  placeholder="请输入验证码"
                  autocomplete="off"
                  class="es-label-image-code"
                >
                  <template slot="prefix">
                    <i class="es-icon-yanzhengma es-label-code-image"></i>
                  </template>
                  <template slot="suffix">
                    <img
                      v-show="imgCode && (active == '0' || active == '12')"
                      class="es-img-code"
                      :src="imageCode"
                      @click.stop="getImgCode"
                    />
                  </template>
                </el-input>
              </el-form-item>
              <div>
                <div class="es-password-handle">
                  <el-checkbox
                    v-show="remember && (active == '0' || active == '12')"
                    v-model="checked"
                    >记住密码</el-checkbox
                  >
                  <div v-show="showForget" class="es-password-forget">
                    <span @click="handleForget">忘记密码</span>
                  </div>
                </div>
                <el-button
                  class="es-button-submit"
                  type="primary"
                  @click="handleLogin"
                  >登录</el-button
                >
              </div>
            </el-form>
          </template>
          <template
            v-if="isShow(active) && (active == 3 || active == 7 || active == 9)"
          >
            <div
              class="es-login-qrcode"
              :class="{ 'es-login-qrcode-complex': mode == 'complex' }"
            >
              <div class="es-login-down-app" v-if="mode !== 'complex'">
                打开
                <template v-if="active == 3">
                  <a
                    class="es-login-app-name es-pointer"
                    target="_blank"
                    :href="downloadApp"
                    v-if="downloadApp"
                    >{{ app }}app</a
                  >
                  <span
                    class="es-login-app-name es-pointer"
                    v-else
                    @click="handleDownLoadApp"
                    >{{ app }}app
                  </span>
                </template>
                <span class="es-login-app-name" v-else
                  >{{ active == 7 ? '钉钉' : '微信' }}app </span
                >，扫描二维码
              </div>
              <div class="es-login-qrcode-box">
                <es-qr-code
                  :content="identifyingId"
                  :logo="qrimg"
                  auto
                  v-if="active == 3 && identifyingId"
                ></es-qr-code>
                <div class="es-wx-qrcode-box" v-if="active == 9">
                  <es-wxlogin
                    href="data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7CiAgICB3aWR0aDogMTAwJSAhaW1wb3J0YW50OwogICAgYm94LXNpemluZzogYm9yZGVyLWJveCAhaW1wb3J0YW50OwogICAgbWFyZ2luOiAwICFpbXBvcnRhbnQ7Cn0KCi5pbXBvd2VyQm94IC5pbmZvLAouaW1wb3dlckJveCAudGl0bGUgewogICAgZGlzcGxheTogbm9uZSAhaW1wb3J0YW50Owp9"
                    auto
                    :appid="wechatAppid"
                    :scope="wechatScope"
                    :redirect_uri="redirectUri"
                  ></es-wxlogin>
                </div>
              </div>
              <div
                v-if="active == 3 && mode == 'complex'"
                class="es-login-complex-app"
              >
                <div class="es-login-complex-scan">
                  <i class="es-icon-saoma"></i>
                  <span class="es-login-complex-scan-tips"
                    >打开app<br />扫一扫登录</span
                  >
                </div>
                <div class="es-login-complex-download">
                  <a
                    class="es-login-app-name es-pointer"
                    target="_blank"
                    :href="downloadApp"
                    v-if="downloadApp"
                    >下载app</a
                  >
                  <span
                    class="es-login-app-name es-pointer"
                    v-else
                    @click="handleDownLoadApp"
                    >下载app
                  </span>
                </div>
              </div>
              <div
                v-if="
                  active == 3 &&
                  loginModel.indexOf('0') > -1 &&
                  mode == 'complex'
                "
                class="es-to-login"
              >
                <span class="es-pointer" @click="switchLoginType()"
                  >账号登录<i class="es-icon-shoushiyou"></i
                ></span>
              </div>
            </div>
          </template>
          <template v-if="isShow(active) && (active == 6 || active == 11)">
            <el-form
              :ref="'login' + active"
              class="es-login-form es-login-verify"
              :model="formData"
            >
              <el-form-item
                prop="target"
                :rules="active == 6 ? phone.rules : email.rules"
              >
                <el-input
                  v-model="formData.target"
                  type="text"
                  name="target"
                  tabindex="4"
                  :placeholder="
                    active == 6 ? phone.placeholder : email.placeholder
                  "
                  autocomplete="off"
                >
                  <template slot="prefix">
                    <i class="es-icon-zhanghao es-label-user"></i>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item
                prop="verificationCode"
                :rules="[{ required: true, message: '验证码不能为空' }]"
              >
                <el-input
                  name="verificationCode"
                  type="text"
                  v-model="formData.verificationCode"
                  placeholder="请输入验证码"
                  autocomplete="off"
                  class="es-label-image-code es-label-get-code"
                  tabindex="5"
                >
                  <template slot="prefix">
                    <i class="es-icon-yanzheng es-label-code-image"></i>
                  </template>
                  <template slot="suffix">
                    <el-button
                      class="es-get-code"
                      type="primary"
                      :disabled="disabled"
                      @click.stop="getCode"
                      >{{ btnText }}</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
              <div>
                <div class="es-password-handle">
                  <el-checkbox
                    v-show="remember && active == '0'"
                    v-model="checked"
                    >记住密码</el-checkbox
                  >
                  <div
                    v-show="showForget"
                    class="es-password-forget"
                    @click="handleForget"
                  >
                    忘记密码
                  </div>
                </div>
                <el-button
                  class="es-button-submit"
                  type="primary"
                  @click="handleLogin"
                  >登录</el-button
                >
              </div>
            </el-form>
          </template>
          <div class="es-downloadSetup" v-if="downloadSetup || $slots.button">
            <slot name="button"></slot>
            <span class="es-setup" @click="downloadExe"
              >初次使用请下载一键安装包</span
            >
          </div>
          <div class="es-warning" v-if="showWarnInfo">
            {{ warningText }}
          </div>
        </div>
      </div>
    </div>
    <slot name="footer" :copyright="copyright">
      <div class="es-login-icp">
        <template v-for="item in copyright">
          <a
            v-if="item.url || item.open"
            class="es-login-icp-item"
            :target="item.open ? '_blank' : '_self'"
            :style="{
              color: '#63c2ff',
              ...item.style
            }"
            :key="item.title"
            :href="item.url || item.open"
          >
            {{ item.title }}
          </a>
          <span
            v-else
            class="es-login-icp-item"
            :style="item.style || copyrightStyle"
            :key="item.title"
          >
            {{ item.title }}
          </span>
          <template v-if="item.children && item.children.length">
            <template v-for="child in item.children">
              <a
                v-if="child.url || child.open"
                class="es-login-icp-child-item"
                :target="child.open ? '_blank' : '_self'"
                :style="{
                  color: '#63c2ff',
                  ...child.style
                }"
                :key="child.title"
                :href="child.url || child.open"
              >
                {{ child.title }}
              </a>
              <span
                v-else
                class="es-login-icp-child-item"
                :style="child.style || copyrightStyle"
                :key="child.title"
              >
                {{ child.title }}
              </span>
            </template>
          </template>
        </template>
      </div>
    </slot>
    <es-dialog
      :title="operationCheckCode ? '修改密码' : '密码重置'"
      width="680px"
      height="auto"
      :visible.sync="showResetPassword"
    >
      <slot
        name="resetPassword"
        :secret="secret"
        :is-encrypt="isEncrypt"
        v-if="showResetPassword"
      >
        <reset-password
          :secret="secret"
          :is-encrypt="isEncrypt"
          :type="passModifyModel"
          :username="formData.username"
          :operationCheckCode="operationCheckCode"
          @success="handleSuccess"
        ></reset-password>
      </slot>
    </es-dialog>
    <es-dialog
      title="客户端下载"
      :width="downloadLength == 1 ? '450px' : '80%'"
      :height="downloadLength == 1 ? '500px' : '80%'"
      custom-class="es-clients-dialog"
      :visible.sync="showDownLoadApp"
    >
      <es-clients :downloads="download" :showTips="showIosTips"></es-clients>
    </es-dialog>
    <es-dialog
      title="请进行身份效验"
      width="420px"
      height="380px"
      :show-scale="false"
      :visible.sync="showAssistance"
      @close="closeAssistance"
    >
      <es-qr-code :content="checkCode" v-if="checkCode"></es-qr-code>
    </es-dialog>
    <transition name="launch-fade">
      <div class="es-launch-image" :style="_launchImage" v-show="showLaunch">
        <p class="es-launch-text es-launch-user-name">{{ userName }}，您好！</p>
        <p class="es-launch-text es-launch-system-name">
          欢迎进入{{ welcome || sysName }}
        </p>
      </div>
    </transition>
    <es-ca-login
      v-if="isCaLogin"
      ref="calogin"
      :showSelect="showKeySelect"
      :install-path="installPath"
      :ca-model="caLoginModel"
      :identifyingId="identifyingId"
      :success="caLogin"
      @error="handleError"
    ></es-ca-login>
  </div>
</template>
<script>
import { debounce } from 'throttle-debounce';
import resetPassword from './resetPassword.vue';
import store from 'eoss-ui/src/utils/store';
import util from 'eoss-ui/src/utils/util';
import rules from 'eoss-ui/src/utils/rules.js';
import {
  initLogin,
  changeImg,
  doUserLogin,
  doQrLogin,
  getLoginCode,
  doCodeLogin,
  getTwoFactorLoginCode,
  doTwoFactorLogin,
  doWechatQrLogin,
  doCaLogin,
  doAssistanceQrLogin
} from 'eoss-ui/src/config/api.js';
const params = util.getParams();
import { dayImg, nightImg } from 'eoss-ui/src/config/image';
export default {
  name: 'EsLogin',
  inheritAttrs: false,
  components: {
    resetPassword
  },
  props: {
    ceshi: String,
    //初始登录配置接口地址
    initLogin: {
      type: String,
      default: initLogin
    },
    size: String,
    mode: {
      type: String,
      default: 'default'
    },
    switchs: {
      type: Array,
      default() {
        return [
          {
            type: '0',
            icon: 'es-icon-zhuomian'
          },
          {
            type: '3',
            name: '手机扫码登录',
            icon: 'es-icon-qrcode',
            tips: '扫码登录在这里',
            background:
              'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAAAoCAYAAAA2cfJIAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDYuMC1jMDA2IDc5LmRhYmFjYmIsIDIwMjEvMDQvMTQtMDA6Mzk6NDQgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCAyMi40IChNYWNpbnRvc2gpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjZFRTVERTUxQzRDMzExRUY4NkFGQ0U2RDY3NEFERkI0IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjZFRTVERTUyQzRDMzExRUY4NkFGQ0U2RDY3NEFERkI0Ij4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NkVFNURFNEZDNEMzMTFFRjg2QUZDRTZENjc0QURGQjQiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NkVFNURFNTBDNEMzMTFFRjg2QUZDRTZENjc0QURGQjQiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz64XoEfAAAB/UlEQVR42uycOUsDQRiG99vdHJ4JHhFN1EhEQkBsRVACghBbKytBf4OiNrZipQHtRLASsbJIQDQGBVHBysIDAxIvPBCCGpO4ZvwWrCT+gZ33gWV2mam+95mZPWDpcGZYCYQjY4oQs0Y+lxDF4qcCLAFpWrVud/QqRJOpZHy55Jjn3dUODv/oJXU+krm9vkPZrIXL29JU2x5aIaIeluDyb7/KxyDP/C2Eb00yd+l7znfHzLlUvymAk5f9LEplXYRhPHHT8J8AQGIgAAQAEABAAAABAAQAEABAAAABAAQAEABYAiGKBW66A+FIGQSQkIfTk3UjnzM/+G2zBDUQQDK+C3kjfZic+cp+XPHlPkvQCgGk2waESB/vRfNvmdivBJ0QQEJuTw7Wsq/PS7/bQRgCSEjh4/2GlwTNXAAggGS4m9uaXT7/vEI0mkrGExBAIqoafZ6ato5FIprg8DdxDyAR5bUed317KEqqusDhr+ApQCLsFZXOhlDXPGnaBoc/h/cAkuEJdg2pmp7i0+m/fRBAAnjPt3FzxrNfQAAAAQAEABAAQAAAASAAgAAAAgAIAGQVIEeqWo5SWBfSdQ83j/8JENMdzgGXz+9FqayH+ZMozrefT+Ol+nXzz1GBcGS8LhBcdvv8iaJhPKJsFlnebTavbnf0KURTnPNFqTE/AgwAPZCY5D/YjJ4AAAAASUVORK5CYII='
          }
        ];
      }
    },
    switchsActive: {
      type: String,
      default: '0'
    },
    launch: Boolean,
    param: {
      type: Object,
      default() {
        return {};
      }
    },
    loginBackground: [String, Array, Object],
    loginImage: [String, Array, Object],
    loginLogo: String,
    loginTitle: String,
    loginName: String,
    type: {
      type: String,
      default: '0'
    },
    firstLoginModel: String,
    //是否加密传输
    isEncrypt: {
      type: Boolean,
      default: true
    },
    modelTips: Boolean,
    model: {
      type: Object,
      default() {
        return {};
      }
    },
    username: {
      type: Object,
      default: () => {
        return {
          placeholder: '请输入账号',
          rules: [
            { required: true, message: '账号不能为空', trigger: 'change' }
          ]
        };
      }
    },
    phone: {
      type: Object,
      default: () => {
        return {
          placeholder: '请输入手机号',
          rules: [
            { required: true, message: '手机号不能为空', trigger: 'change' },
            {
              ...rules.phone,
              trigger: 'change'
            }
          ]
        };
      }
    },
    email: {
      type: Object,
      default: () => {
        return {
          placeholder: '请输入邮箱地址',
          rules: [
            {
              required: true,
              message: '请输入邮箱地址',
              trigger: 'change'
            },
            {
              type: 'email',
              message: '请输入正确的邮箱地址',
              trigger: 'blur'
            }
          ]
        };
      }
    },
    password: {
      type: Object,
      default: () => {
        return {
          placeholder: '请输入密码',
          rules: [
            { required: true, message: '密码不能为空', trigger: 'change' }
          ]
        };
      }
    },
    toUrl: String,
    //账号登录接口地址
    action: {
      type: String,
      default: doUserLogin
    },
    //ca登录地址
    caAction: {
      type: String,
      default: doCaLogin
    },
    //扫码登录接口地址
    scanAction: {
      type: String,
      default: doQrLogin
    },
    //图片验证码接口地址
    codeAction: {
      type: String,
      default: changeImg
    },
    getLoginCode: {
      type: String,
      default: getLoginCode
    },
    doCodeLogin: {
      type: String,
      default: doCodeLogin
    },
    getTwoFactorLoginCode: {
      type: String,
      default: getTwoFactorLoginCode
    },
    doTwoFactorLogin: {
      type: String,
      default: doTwoFactorLogin
    },
    doWechatQrLogin: {
      type: String,
      default: doWechatQrLogin
    },
    imgCode: {
      type: [Boolean, Object],
      default: true
    },
    onLogin: Function,
    onSuccess: Function,
    onError: {
      type: Function,
      default: () => {}
    },
    doorIndex: {
      type: Boolean,
      default: true
    },
    storage: String,
    warning: String,
    copyrightStyle: {
      type: Object,
      default() {
        return {
          color: '#fff'
        };
      }
    },
    appName: String,
    qrImage: String,
    forget: {
      type: [Boolean, String],
      default: true
    },
    remember: {
      type: Boolean,
      default: true
    },
    downloadApp: String,
    downLoadUrls: {
      type: Object,
      default() {
        return {};
      }
    },
    onDownLoadApp: [Function, Boolean],
    redirect_uri: String,
    position: {
      type: String,
      default: 'center'
    },
    translate: String,
    useResults: {
      type: Boolean,
      default: true
    },
    scanIntervalTime: {
      type: Number,
      default: 1500
    },
    isScale: Boolean,
    isFixed: Boolean,
    showIosTips: Boolean,
    safe: Boolean,
    launchImage: {
      type: [String, Object],
      default() {
        return {
          day: dayImg,
          night: nightImg
        };
      }
    },
    loginDownloadApps: Boolean,
    copyrights: {
      type: Array,
      default() {
        return [];
      }
    },
    caModel: String,
    caInstallPath: String,
    showKeySelect: Boolean,
    alertCallback: {
      type: Function,
      default: () => {}
    }
  },
  computed: {
    downloadLength() {
      return this.download ? Object.keys(this.download).length : 0;
    },
    transform() {
      let translate = this.translate
        ? this.translate
        : this.align === 'center'
        ? '-50%, -51%'
        : '-51%';
      if (this.align.indexOf('%') > -1) {
        return {
          left: this.align,
          top: '50%',
          transform: `translateY(${translate})`
        };
      }
      if (this.align === 'left') {
        return {
          left: '30%',
          top: '50%',
          transform: `translateY(${translate})`
        };
      }
      if (this.align === 'right') {
        return {
          left: '70%',
          top: '50%',
          transform: `translateY(${translate})`
        };
      }
      return {
        left: '50%',
        top: '50%',
        transform: `translate(${translate})`
      };
    },
    redirectUri() {
      if (this.redirect_uri) {
        return this.redirect_uri;
      } else {
        return window.location.href || window.href;
      }
    },
    showWarnInfo() {
      return this.$slots.warning || this.$scopedSlots.warning
        ? false
        : this.warningText
        ? true
        : false;
    },
    modelLength() {
      return Array.isArray(this.loginModel)
        ? this.loginModel.length
        : this.loginModel.split(',').length;
    },
    iconfonts() {
      const types = this.loginModel.split(',');
      return types.length > 2
        ? {
            0: {
              type: '0',
              icon: 'es-icon-jianpan',
              icon2: '',
              name: '账号登录'
            },
            1: { type: '1', icon: 'es-icon-upan', name: '证书登录' },
            3: {
              type: '3',
              icon: 'es-icon-saoma1',
              icon2: '',
              name: '扫码登录'
            },
            6: { type: '6', icon: 'es-icon-solid-duanxin', name: '短信登录' },
            7: { type: '7', icon: 'es-icon-dingding1', name: '钉钉扫码登录' },
            9: { type: '9', icon: 'es-icon-weixin1', name: '微信扫码登录' },
            11: { type: '11', icon: 'es-icon-youjian', name: '邮箱登录' },
            12: { type: '12', icon: 'es-icon-jianpan', name: '账号登录' } //双因素
          }
        : {
            0: { type: '0', icon: 'es-icon-solid-monitor', name: '账号登录' },
            1: {
              type: '1',
              icon: 'es-icon-solid-cashenfenrenzheng',
              name: '证书登录'
            },
            3: { type: '3', icon: 'es-icon-qrcode', name: '扫码登录' },
            6: { type: '6', icon: 'es-icon-solid-duanxin', name: '短信登录' },
            7: { type: '7', icon: 'es-icon-dingding', name: '钉钉扫码登录' },
            9: { type: '9', icon: 'es-icon-weixin', name: '微信扫码登录' },
            11: {
              type: '11',
              icon: 'es-icon-youjian',
              name: '邮箱登录'
            },
            12: { type: '12', icon: 'es-icon-solid-monitor', name: '账号登录' } //双因素
          };
    },
    icons() {
      let icon = [];
      const types = this.loginModel.split(',');
      types.forEach((item) => {
        icon.push(this.iconfonts[item]);
      });
      return icon;
    },
    isCaLogin() {
      return this.loginModel.indexOf('1') > -1;
    },
    showVerifyCode() {
      return (
        this.passModifyModel &&
        (this.passModifyModel.indexOf('6') > -1 ||
          this.passModifyModel.indexOf('11') > -1)
      );
    },
    _launchImage() {
      let img = util.isObject(this.launchImages)
        ? this.launchImages[this.launchKey]
        : this.launchImages;
      return { 'background-image': `url(${img})` };
    },
    showForget() {
      return this.forgetUrl && typeof this.forgetUrl === 'string'
        ? true
        : this.forgetUrl === true &&
            this.loginModel.indexOf('0') > -1 &&
            this.showVerifyCode;
    },
    isCeshi() {
      return this.ceshi ? params[this.ceshi] : false;
    }
  },
  watch: {
    loginModel: {
      immediate: true,
      handler(val) {
        this.active = val.split(',')[0];
        this.title = this.iconfonts[this.active].name;
        this.switchs.forEach((item) => {
          if (item.type == this.active) {
            this.switchActive = item.type;
            return;
          }
        });
      }
    },
    active: {
      immediate: true,
      handler(val) {
        this.loginInfo(val == 3);
      }
    },
    identifyingId(val) {
      if (val) {
        this.loginInfo(this.active == 3);
      }
    },
    appName: {
      immediate: true,
      handler(val) {
        if (val) {
          this.app = val;
        }
      }
    },
    qrImage: {
      immediate: true,
      handler(val) {
        if (val) {
          this.qrimg = val;
        }
      }
    },
    checked(val) {
      if (!val) {
        localStorage.removeItem('unpd');
        //localStorage.removeItem('remember');
      }
    }
    // secret: {
    //   immediate: true,
    //   handler(val) {
    //     if (val) {
    //       if (this.storage) {
    //         localStorage.setItem('secret', val);
    //       } else {
    //         sessionStorage.setItem('secret', val);
    //       }
    //     }
    //   }
    // }
  },
  data() {
    return {
      title: '',
      align: this.position,
      loginBackgroundImg: this.loginBackground,
      loginMainImg: this.loginImage,
      loginNameImg: this.loginName,
      loginTitleImg: this.loginTitle,
      loginLogoImg: this.loginLogo,
      loginModel: this.type,
      caLoginModel: this.caModel,
      passModifyModel: null,
      active: 0,
      submit: false,
      checked: false,
      formData: this.model,
      focusShow: false,
      users: [],
      imageCode: '',
      secret: null,
      identifyingId: undefined,
      download: {},
      setup: '',
      sysName: '',
      copyright: this.copyrights,
      forgetUrl: this.forget,
      actionUrl: this.action,
      downloadSetup: '',
      app: '',
      qrimg: '',
      interval: null,
      showResetPassword: false,
      operationCheckCode: '',
      showDownLoadApp: false,
      wechatAppid: null,
      wechatScope: null,
      disabled: false,
      btnText: '获取验证码',
      timer: null,
      countdown: 0,
      code: null,
      defaultModel: JSON.parse(JSON.stringify(this.model)),
      checkCode: '',
      showAssistance: false,
      doAssistance: null,
      warningText: this.warning,
      safes: {
        paste: (event) => {
          event.preventDefault();
          return false;
        },
        contextmenu: (event) => {
          event.preventDefault();
          return false;
        },
        copy: (event) => {
          event.preventDefault();
          return false;
        },
        cut: (event) => {
          event.preventDefault();
          return false;
        }
      },
      userName: '',
      launchShow: this.launch,
      showLaunch: false,
      launchImages: this.launchImage,
      launchKey: 'day',
      launchTime: 2000,
      switchActive: this.switchsActive,
      loginDownloadApp: this.loginDownloadApps,
      installPath: this.caInstallPath,
      storageType: this.storage,
      welcome: ''
    };
  },
  beforeCreate() {
    this.setScale = debounce(300, () => {
      util.setScale();
    });
    util.removeStorage([
      'remind',
      'ssId',
      'token',
      'Authorization',
      'deviceUnique',
      'userId',
      'userName',
      'useCaseCodes'
    ]);
  },
  created() {
    this.launchKey = 5 < new Date().getHours() < 18 ? 'day' : 'night';
    if (this.isCeshi) {
      this.loginModel =
        this.isCeshi == 'true' || this.isCeshi == true ? '0' : this.isCeshi;
    }
    if (this.isScale || util.getParams('scale')) {
      util.setScale();
      window.addEventListener('resize', this.setScale);
    }
    this.code = util.getParams('code');
    if (this.code) {
      this.doWechatLogin(this.code);
    } else {
      this.getLogin();
      document.addEventListener('keyup', this.doLogin);
      document.addEventListener('keydown', this.forbiddenTab);
    }
    this.init();
  },
  mounted() {
    this.getRemember();
    //delete util.win.websocket;
  },
  methods: {
    init() {
      let loginBoxAlign = localStorage.getItem('loginBoxAlign');
      loginBoxAlign && (this.align = loginBoxAlign);
    },
    doWechatLogin(code) {
      util
        .ajax({
          method: 'post',
          url: this.doWechatQrLogin,
          data: { code: code }
        })
        .then((res) => {
          if (res.rCode == 0) {
            const results = res.results;
            this.handleResults(results);
          } else {
            const msg =
              res.results && res.results.msg ? res.results.msg : res.msg;
            this.$message({
              message: msg || '系统错误，请联系管理员！',
              type: 'error',
              onClose: () => {
                window.location.href = util.delUrlParam({ key: 'code' });
                if (window.location.hash) {
                  location.reload();
                }
              }
            });
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    getBackground(res) {
      let style = {};
      if (!res || (Array.isArray(res) && !res.length)) {
        return style;
      }
      if (Array.isArray(res)) {
        let url = [];
        let image = [];
        res.forEach((item) => {
          if (item.indexOf('url(') > -1) {
            url.push(item);
          } else {
            image.push(`url(${item})`);
          }
        });
        if (url.length == res.length) {
          style = { background: url.join(',') };
        } else if (image.length == res.length) {
          style = { 'background-image': image.join(',') };
        } else {
          console.error('设置的样式不一致！');
        }
      } else if (util.isObject(res)) {
        style = res;
      } else if (res.indexOf('url(') > -1) {
        style = { background: res };
      } else {
        style = { 'background-image': `url(${res})` };
      }
      return style;
    },
    getRemember(user) {
      let values = localStorage.getItem('unpd');
      let value = {};
      if (values) {
        try {
          values = JSON.parse(values);
          let users = [];
          for (let i in values) {
            let k = util.esDecode(i);
            value[k] = util.esDecode(values[i]);
            users.push({ value: k });
          }
          this.users = users;
          let keys = Object.keys(value);
          if (keys.length) {
            this.checked = true;
          }
          if (!user && keys.length == 1) {
            user = keys[0];
            // user = localStorage.getItem('remember');
            // if (user) {
            //   user = util.esDecode(user);
            // } else {
            //   user = keys[0];
            // }
          }
          if (keys.length > 1) {
            this.focusShow = true;
          }
          if (user) {
            this.$set(this.formData, 'username', user);
            this.$set(this.formData, 'password', value[user]);
          }
        } catch (error) {
          localStorage.removeItem('unpd');
        }
      }
    },
    handleBlur(res) {
      this.getRemember(res.value);
    },
    handleRemember() {
      let values = localStorage.getItem('unpd');
      let value = {};
      if (values) {
        values = JSON.parse(values);
        for (let i in values) {
          value[util.esDecode(i)] = util.esDecode(values[i]);
        }
      }
      if (this.checked) {
        //localStorage.setItem('remember', util.esEncode(this.formData.username));
        value[this.formData.username] = this.formData.password;
        let data = {};
        for (let i in value) {
          data[util.esEncode(i)] = util.esEncode(value[i]);
        }
        localStorage.setItem('unpd', JSON.stringify(data));
      } else {
        delete value[this.formData.username];
        if (Object.keys(value)) {
          let data = {};
          for (let i in value) {
            data[util.esEncode(i)] = util.esEncode(value[i]);
          }
          localStorage.setItem('unpd', JSON.stringify(data));
        } else {
          localStorage.removeItem('unpd');
        }
        //localStorage.removeItem('remember');
      }
    },
    // 下载app的弹窗
    handleDownLoadApp() {
      if (this.onDownLoadApp) {
        if (typeof this.onDownLoadApp === 'function') {
          this.onDownLoadApp();
        } else {
          this.$emit('handleDownLoadApp');
          this.$emit('handle-down-load-app');
        }
      } else {
        this.showDownLoadApp = true;
      }
    },
    handleDownLoadApps() {
      if (this.downloadApp) {
        window.open(this.downloadApp);
      } else {
        this.handleDownLoadApp();
      }
    },
    switchLogin(res) {
      if (res.type != '1') {
        this.active = res.type;
        this.title = res.name;
        Object.keys(this.defaultModel).length &&
          (this.formData = JSON.parse(JSON.stringify(this.defaultModel)));
        this.$emit('change-type', res, this.identifyingId);
        this.$nextTick(() => {
          let ref = 'login' + this.active;
          this.$refs[ref] && this.$refs[ref].clearValidate();
        });
      } else {
        this.submit = true;
        this.$refs.calogin && this.$refs.calogin.getCertificate();
      }
      this.countdown = 0;
    },
    switchLoginType(res) {
      this.countdown = 0;
      if (res) {
        this.switchActive = res.type;
        this.title = res.name || '';
        if (this.loginModel.indexOf(res.type) > -1) {
          this.active = res.type;
        } else {
          let other = this.switchs.filter((item) => {
            return item.type != res.type;
          })[0];
          let model = this.loginModel.split(',').filter((item) => {
            return item != res.type && item != other.type;
          })[0];
          if (model) {
            this.active = model;
            this.title = this.iconfonts[model].name;
          } else {
            console.error('complex风格的登录方式，loginModel配置错误！');
          }
        }
      } else {
        this.active = this.switchs[0].type;
        this.title = '';
        this.switchActive = this.switchs[0].type;
      }
      this.$emit('change-type', res, this.identifyingId);
      this.$nextTick(() => {
        let ref = 'login' + this.active;
        this.$refs[ref] && this.$refs[ref].clearValidate();
      });
    },
    isShow(res) {
      return this.loginModel.indexOf(res) > -1;
    },
    async getLogin() {
      const config = util.getStorage('initLogin');
      if (config) {
        this.setConfig(JSON.parse(config));
      }
      await util
        .ajax({ url: this.initLogin })
        .then((res) => {
          if (res && res.rCode === 0) {
            store.set('initLogin', res.results);
            util.setStorage({
              type: 'localStorage',
              key: 'initLogin',
              value: JSON.stringify(res.results)
            });
            this.$emit('initLogin', res.results);
            this.setConfig(res.results, true);
          } else {
            this.$message({
              message: res.msg || '系统错误，请联系管理员！',
              type: 'error'
            });
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    setConfig(res, ajax) {
      const isLogined = localStorage.getItem('isLogined');
      this.identifyingId = res.identifyingId || '';
      this.getImgCode();
      let downloads = {};
      if (res.androidDownloadUrl) {
        downloads['android'] = res.androidDownloadUrl;
      }
      if (res.iosDownloadUrl) {
        downloads['ios'] = res.iosDownloadUrl;
      }
      if (res.iosDownloadUrl2) {
        downloads['pad'] = res.iosDownloadUrl2;
      }
      if (res.macDownloadUrl) {
        downloads['mac'] = res.macDownloadUrl;
      }
      if (res.winDownloadUrl) {
        downloads['win'] = res.winDownloadUrl;
      }
      if (res.linuxDownloadUrl) {
        downloads['linux'] = res.linuxDownloadUrl;
      }
      if (res.harmonyDownloadUrl) {
        downloads['harmony'] = res.harmonyDownloadUrl;
      }
      this.sysName = res.subsystemName;
      this.secret = res.secret;
      this.setup = res.setup;
      this.downloadSetup = res.downloadSetup;
      if (res.subsystemName) {
        document.title = res.subsystemName;
      }
      this.app = res.appName || res.subsystemName;
      if (res.loginModel && !this.isCeshi) {
        this.loginModel =
          (res.firstLoginModel || this.firstLoginModel) && !isLogined
            ? res.firstLoginModel || this.firstLoginModel
            : res.loginModel;
      }

      if (res.loginBackgroundUrl) {
        this.loginBackgroundImg = res.loginBackgroundUrl.split(',');
      }
      if (res.loginLogoUrl) {
        this.loginLogoImg = res.loginLogoUrl;
      }
      if (res.caModel) {
        this.caLoginModel = res.caModel;
      }
      res.loginPage && sessionStorage.setItem('loginPage', res.loginPage);
      if (res.subsystemExtend && Object.keys(res.subsystemExtend).length) {
        this.welcome = res.subsystemExtend.welcome || '';
        if(res.subsystemExtend.appName){
          this.app = res.subsystemExtend.appName;
        }
        if (
          res.subsystemExtend.copyright &&
          res.subsystemExtend.copyright.length
        ) {
          this.copyright = JSON.parse(res.subsystemExtend.copyright);
        }
        if (res.subsystemExtend.qrimg || res.subsystemExtend.qrImg) {
          this.qrimg = res.subsystemExtend.qrimg || res.subsystemExtend.qrImg;
        }
        //忘记密码地址
        if (
          res.subsystemExtend.forgetPassUrl ||
          res.subsystemExtend.look_pass_url
        ) {
          this.forgetUrl =
            res.subsystemExtend.forgetPassUrl ||
            res.subsystemExtend.look_pass_url;
        }
        res.subsystemExtend.loginPage &&
          sessionStorage.setItem('loginPage', res.subsystemExtend.loginPage);
        if (res.subsystemExtend.login_url) {
          this.actionUrl = res.subsystemExtend.login_url;
        }
        if (res.subsystemExtend.loginModel) {
          this.loginModel = res.subsystemExtend.loginModel;
        }
        if (res.subsystemExtend.firstLoginModel && !isLogined) {
          this.loginModel = res.subsystemExtend.firstLoginModel;
        }
        if (res.subsystemExtend.caModel) {
          this.caLoginModel = res.subsystemExtend.caModel;
        }
        if (res.subsystemExtend.applicationName) {
          localStorage.setItem('appcode', res.subsystemExtend.applicationName);
        }
        if (res.subsystemExtend.loginBoxBackgroun) {
          this.loginMainImg = res.subsystemExtend.loginBoxBackground.split(',');
        }
        if (res.subsystemExtend.loginBoxTitle) {
          this.loginTitleImg = res.subsystemExtend.loginBoxTitle;
        }
        if (res.subsystemExtend.loginBoxName) {
          this.loginNameImg = res.subsystemExtend.loginBoxName;
        }
        if (res.subsystemExtend.loginBoxAlign && this.useResults) {
          localStorage.setItem(
            'loginBoxAlign',
            res.subsystemExtend.loginBoxAlign
          );
          this.align = res.subsystemExtend.loginBoxAlign;
        }
        if (res.subsystemExtend.themeColor) {
          util.updateTheme(res.subsystemExtend.themeColor);
          localStorage.setItem('theme', res.subsystemExtend.themeColor);
        }
        if (res.subsystemExtend.macDownloadUrl) {
          downloads.mac = res.subsystemExtend.macDownloadUrl;
        }
        if (res.subsystemExtend.winDownloadUrl) {
          downloads.win = res.subsystemExtend.winDownloadUrl;
        }
        if (res.subsystemExtend.linuxDownloadUrl) {
          downloads.linux = res.subsystemExtend.linuxDownloadUrl;
        }
        if (res.subsystemExtend.uosDownloadUrl) {
          downloads.uos = res.subsystemExtend.uosDownloadUrl;
        }

        if (res.subsystemExtend.harmonyDownloadUrl) {
          downloads.harmony = res.subsystemExtend.harmonyDownloadUrl;
        }
        if (res.subsystemExtend.warningText) {
          this.warningText = res.subsystemExtend.warningText;
        }
        if (res.subsystemExtend.launchTime) {
          this.launchTime = parseInt(res.subsystemExtend.launchTime, 10);
        }
        if (res.subsystemExtend.launchImage) {
          if (!this.launchShow) {
            this.launchShow = true;
          }
          if (
            res.subsystemExtend.launchImage != 'true' &&
            res.subsystemExtend.launchImage != true
          ) {
            this.launchImages =
              res.subsystemExtend.launchImage.indexOf('{') > -1 &&
              res.subsystemExtend.launchImage.indexOf('}') > -1
                ? JSON.parse(res.subsystemExtend.launchImage)
                : res.subsystemExtend.launchImage;
          }
        }
        if (res.subsystemExtend.loginDownloadApp) {
          this.loginDownloadApp = res.subsystemExtend.loginDownloadApp;
        }
        if (res.subsystemExtend.caInstallPath) {
          this.installPath = res.subsystemExtend.caInstallPath;
        }
        if (res.subsystemExtend.storageType) {
          this.storageType = res.subsystemExtend.storageType;
        }
        if (res.subsystemExtend.alertContent) {
          ajax && this.alertContent(res.subsystemExtend.alertContent);
        }
      }
      this.passModifyModel = res.passModifyModel;
      this.wechatAppid = res.wechatAppid;
      this.wechatScope = res.wechatScope;
      this.download = { ...this.downLoadUrls, ...downloads };
      if (res.sysLogoIco) {
        localStorage.setItem('sysLogoIco', res.sysLogoIco);
        util.setFavicon(res.sysLogoIco);
      }
    },
    async alertContent(contents) {
      let { content, title, ...config } = JSON.parse(contents);
      const regex = /\.md$/;
      let isMarkdown = regex.test(content);
      if (isMarkdown) {
        content = await util.ajax({ url: content });
        console.log(content);
        content = content ? this.renderMarkdown(content) : content;
      }
      this.$alert(content, title, {
        dangerouslyUseHTMLString: isMarkdown,
        setHeight: isMarkdown,
        customClass: 'es-login-alert',
        ...config
      })
        .then(() => {
          this.alertCallback(1, { content, title, ...config });
        })
        .catch(() => {
          this.alertCallback(0, { content, title, ...config });
        });
    },
    async downloadMdFile(url) {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(`下载失败: ${response.statusText}`);
        }
        return await response.text();
      } catch (error) {
        console.error('MD文件下载出错:', error);
        throw error; // 抛出错错误供调用者处理
      }
    },
    renderMarkdown(content) {
      // 这里使用简单的正则替换示例，实际项目建议使用成熟库如marked、markdown-it等
      // 生产环境推荐: npm install marked 后引入使用
      let html = content
        // 处理标题
        .replace(/^#{1,6}\s+(.*?)$/gm, (match, text, level) => {
          const hLevel = match.indexOf('#');
          return `<h${hLevel}>${text}</h${hLevel}>`;
        })
        // 处理粗体
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        // 处理斜体
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        // 处理链接
        .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>')
        // 处理换行
        .replace(/\n/g, '<br>');
      return html;
    },
    getImgCode() {
      if (this.identifyingId === '') {
        return;
      }
      this.imageCode =
        util.getStorage('host') +
        this.codeAction +
        '?identifyingId=' +
        this.identifyingId +
        (this.imgCode && typeof this.imgCode == 'object'
          ? '&' + util.queryParams(this.imgCode)
          : '') +
        '&heightflag=' +
        Math.random().toString().split('.')[1];
      delete this.formData.identifyingCode;
      delete this.formData.verificationCode;
      return this.imageCode;
    },
    getCode() {
      if (this.countdown) {
        return false;
      }
      let data = {};
      let flag = false;
      let ref = 'login' + this.active;
      if (this.active == 12) {
        if (!this.formData.username) {
          this.$refs[ref].validateField('username');
          return false;
        }
        this.$refs[ref].validateField('username', (res) => {
          flag = res != '';
        });
        if (flag) {
          return false;
        }
        data = {
          username: this.formData.username,
          targetType: this.passModifyModel.indexOf('11') > -1 ? 'EMAIL' : 'SMS'
          // targetType: 'SMS'
        };
      } else {
        if (!this.formData.target) {
          this.$refs[ref].validateField('target');
          return false;
        }
        this.$refs[ref].validateField('target', (res) => {
          flag = res != '';
        });
        if (flag) {
          return false;
        }
        data = {
          target: this.formData.target,
          targetType: this.active == '6' ? 'SMS' : 'EMAIL'
        };
      }
      this.countdown = 60;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
          this.disabled = true;
          this.btnText = '重新获取' + this.countdown + 's';
        } else {
          this.btnText = '重新获取';
          this.disabled = false;
          this.submit = false;
        }
      }, 1000);
      util
        .ajax({
          method: 'post',
          url:
            this.active == 12 ? this.getTwoFactorLoginCode : this.getLoginCode,
          data: data
        })
        .then((res) => {
          this.$message({
            message: res.msg,
            duration: res.rCode == 0 ? 2000 : 3000,
            type: res.rCode == 0 ? 'success' : 'error'
          });

          if (res.rCode === 2) {
            this.btnText = '获取验证码';
            this.disabled = false;
            this.countdown = 0;
            clearInterval(this.timer);
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    handleLogin() {
      if (this.submit) {
        return false;
      }
      let ref = 'login' + this.active;
      this.$refs[ref].validate((valid) => {
        if (valid) {
          this.submit = true;
          let param = util.getParams() || {};
          const data =
            this.active == '0'
              ? {
                  username: this.formData.username,
                  password:
                    this.secret && this.isEncrypt
                      ? util.esmEncrypt({
                          data: this.formData.password,
                          key: this.secret
                        })
                      : this.formData.password,
                  identifyingCode: this.formData.identifyingCode,
                  identifyingId: this.identifyingId
                }
              : this.active == '12'
              ? {
                  username: this.formData.username,
                  password:
                    this.secret && this.isEncrypt
                      ? util.esmEncrypt({
                          data: this.formData.password,
                          key: this.secret
                        })
                      : this.formData.password,
                  targetType:
                    this.passModifyModel.indexOf('11') > -1 ? 'EMAIL' : 'SMS',
                  verificationCode: this.formData.identifyingCode
                }
              : {
                  target: this.formData.target,
                  verificationCode: this.formData.verificationCode,
                  targetType: this.active == '6' ? 'SMS' : 'EMAIL'
                };
          if (this.onLogin) {
            if (this.active == '0') {
              this.onLogin(
                { ...param, ...data },
                this.getImgCode,
                this.handleRemember
              );
            } else {
              this.onLogin({ ...param, ...data });
            }
          } else {
            this.handleUserLogin({ ...param, ...this.param, ...data });
          }
        } else {
          this.submit = false;
          return false;
        }
      });
    },
    doLogin(e) {
      if (util.win.event == undefined) {
        var key = e.keyCode;
      } else {
        var key = util.win.event.keyCode;
      }
      if (key == 13) {
        this.handleLogin();
      }
    },
    handleUserLogin(data) {
      let extUserBindHandleId = sessionStorage.getItem('extUserBindHandleId');
      util
        .ajax({
          method: 'post',
          url:
            this.active == '0'
              ? this.actionUrl
              : this.active == '12'
              ? this.doTwoFactorLogin
              : this.doCodeLogin,
          data: extUserBindHandleId
            ? { ...data, extUserBindHandleId: extUserBindHandleId }
            : data
        })
        .then((res) => {
          this.submit = false;
          if (res.rCode == 0) {
            util.removeStorage('extUserBindHandleId');
            this.handleRemember();
            const results = res.results;
            this.handleResults(results);
            if (this.onSuccess) {
              this.onSuccess(res);
            }
          } else {
            const msg =
              res.results && res.results.msg ? res.results.msg : res.msg;
            this.$message({
              message: msg || '系统错误，请联系管理员！',
              type: 'error',
              onClose: () => {
                this.btnText = '获取验证码';
                this.disabled = false;
                this.countdown = 0;
                clearInterval(this.timer);
                this.getImgCode();
              }
            });
            this.onError(res);
          }
        })
        .catch((err) => {
          this.submit = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    caLogin(signedData) {
      this.loginInfo(false);
      util
        .ajax({
          method: 'post',
          url: this.caAction,
          data:
            typeof signedData === 'string'
              ? { identifyingId: this.identifyingId, signedData: signedData }
              : signedData
        })
        .then((res) => {
          this.submit = false;
          if (res.rCode == 0) {
            const results = res.results;
            this.handleResults(results);
            if (this.onSuccess) {
              this.onSuccess(res);
            }
          } else {
            const msg =
              res.results && res.results.msg ? res.results.msg : res.msg;
            this.$message({
              message: msg || '系统错误，请联系管理员！',
              type: 'error',
              onClose: () => {
                this.getImgCode();
                this.loginInfo(this.active == 3);
              }
            });
            this.onError(res);
          }
        })
        .catch((err) => {
          this.submit = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    handleForget() {
      if (typeof this.forgetUrl === 'string') {
        util.win.open(this.forgetUrl);
      } else {
        this.showResetPassword = true;
      }
    },
    downloadExe() {
      util.win.open(this.downloadSetup);
    },
    //获取app登录信息
    loginInfo(res) {
      clearTimeout(this.interval);
      if (res) {
        this.interval = setTimeout(() => {
          this.initRequestLoginInfo();
        }, this.scanIntervalTime);
      }
    },
    initRequestLoginInfo() {
      if (this.identifyingId == '') {
        return false;
      }
      util
        .ajax({
          method: 'post',
          url: this.scanAction,
          data: {
            identifyingId: this.identifyingId
          }
        })
        .then((res) => {
          if (res.rCode === 0) {
            const results = res.results;
            if (results.statusCode === 0 || results.statusCode === 2) {
              // statusCode为2时 代表密码过期，也应执行handleResults
              clearTimeout(this.interval);
              if (results.statusCode === 2) {
                this.$alert(
                  results.msg
                    ? results.msg
                    : '您的初始密码已过期，请及时修改！',
                  '提示',
                  {
                    confirmButtonText: '确定',
                    type: 'warning'
                  }
                )
                  .then(() => {
                    this.handleResults(results, 3);
                  })
                  .catch((e) => {});
              } else {
                this.handleResults(results, 3);
              }
            } else {
              this.loginInfo(true);
            }
          }
        })
        .catch((err) => {
          clearTimeout(this.interval);
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    handleResults(results, type) {
      switch (results.statusCode) {
        case 0:
          this.userName = results.userName;
          util.setStorage({
            type: this.storageType,
            key: {
              ssId: results.ssId,
              token: results.token,
              Authorization: results.token,
              deviceUnique: results.deviceUnique,
              userId: results.userId,
              userName: results.userName,
              useCaseCodes: results.resourceCodes
            }
          });
          if (this.launchShow) {
            this.$message({
              message: '登录成功!',
              type: 'success',
              duration: 1000
            });
            this.showLaunch = true;
            setTimeout(() => {
              if (this.toUrl) {
                window.location.href = this.toUrl;
              } else if (results.doorIndex && this.doorIndex) {
                sessionStorage.setItem('doorIndex', results.doorIndex);
                localStorage.setItem('isLogined', true);
                window.location.href = results.doorIndex;
              } else {
                if (window.location.href.indexOf('login.html') > -1) {
                  window.location.href = './main.html';
                } else {
                  this.$router.push({ name: 'main' });
                  this.$nextTick(() => {
                    this.showLaunch = false;
                  });
                }
              }
            }, this.launchTime);
          } else {
            this.$message({
              message: '登录成功!',
              type: 'success',
              duration: 1500,
              onClose: () => {
                if (this.toUrl) {
                  window.location.href = this.toUrl;
                } else if (results.doorIndex && this.doorIndex) {
                  sessionStorage.setItem('doorIndex', results.doorIndex);
                  localStorage.setItem('isLogined', true);
                  window.location.href = results.doorIndex;
                } else {
                  if (window.location.href.indexOf('login.html') > -1) {
                    window.location.href = './main.html';
                  } else {
                    this.$router.push({ name: 'main' });
                  }
                }
              }
            });
          }
          break;
        case 2:
          this.$confirm(
            results.msg ? results.msg : '密码太简单了, 请修改密码?',
            '提示',
            {
              confirmButtonText: '确定',
              //cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              this.operationCheckCode = results.checkCode;
              if (typeof this.forgetUrl === 'string') {
                util.win.open(this.forgetUrl);
              } else {
                this.showResetPassword = true;
              }
            })
            .catch((e) => {});
          break;
        case 3:
          let url =
            results.doorIndex && this.doorIndex
              ? results.doorIndex
              : window.location.href.indexOf('main.html') > -1
              ? './login.html'
              : window.location.hash
              ? window.location.href.replace('login', 'main')
              : window.location.href;
          const href = results.authorizeUrl.replace(
            '{redirectUri}',
            encodeURIComponent(url)
          );
          window.location.href = href;
          // window.location.href =
          //   results.authorizeUrl.indexOf('?') > -1
          //     ? results.authorizeUrl + '&token=' + results.token
          //     : results.authorizeUrl + '?token=' + results.token;
          break;
        case 4:
          this.$alert(
            results.msg ? results.msg : '账号未绑定，账号密码登录后自动绑定！',
            '提示',
            {
              confirmButtonText: '确定',
              type: 'error'
            }
          )
            .then(() => {
              sessionStorage.setItem(
                'extUserBindHandleId',
                results.extUserBindHandleId
              );
              window.location.href = util.delUrlParam({ key: 'code' });
              if (window.location.hash) {
                location.reload();
              }
            })
            .catch((e) => {});
          break;
        case 102:
          this.checkCode = results.checkCode;
          this.showAssistance = true;
          let { operationCheckCode } = JSON.parse(results.checkCode);
          this.handleAssistance({ operationCheckCode });
          break;
        default:
          if (type !== 3) {
            this.$message({
              message: results.msg,
              type: 'error',
              onClose: () => {
                if (this.code) {
                  window.location.href = util.delUrlParam({ key: 'code' });
                  if (window.location.hash) {
                    location.reload();
                  }
                } else {
                  this.getImgCode();
                }
              }
            });
          } else if (this.active == 3) {
            this.loginInfo(true);
          }
      }
    },
    handleAssistance(data) {
      clearTimeout(this.doAssistance);
      this.doAssistance = setTimeout(() => {
        this.doAssistanceLogin(data);
      }, this.scanIntervalTime);
    },
    doAssistanceLogin(data) {
      util
        .ajax({
          method: 'post',
          url: doAssistanceQrLogin,
          data: data
        })
        .then((res) => {
          if (res.rCode === 0) {
            const results = res.results;
            if (results.statusCode === 0) {
              clearTimeout(this.doAssistance);
              this.handleResults(results, 3);
            } else {
              this.handleAssistance(data);
            }
          } else {
            clearTimeout(this.doAssistance);
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          clearTimeout(this.doAssistance);
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    closeAssistance() {
      clearTimeout(this.doAssistance);
    },
    handleSuccess() {
      this.showResetPassword = false;
    },
    forbiddenTab(e) {
      if (e.keyCode == 9) {
        return false;
      }
    },
    handlePaste(event) {
      this.safe && event.preventDefault();
    },
    handleError() {
      this.submit = false;
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setScale);
    document.removeEventListener('keyup', this.doLogin);
    document.removeEventListener('keydown', this.forbiddenTab);
  }
};
</script>
