portalLogin.vue 35.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274

<template>
  <div class="main-h">
    <Header />
    <div class="bg-banner">
      <div id="login-box" >
        <div :class="['login_form', (formType === 'login'||formType === 'beforeLogin'|| formType === 'loginByPassKey'||formType === 'resignByPassKey')  ? 'login-size' : 'register-size']"  :style="formType === 'loginByPassKey'?'height:280px;z-index: 1001':'z-index: 1001'">
          <!-- <img v-if="formType !== 'loginByPassKey'&&formType !== 'resignByPassKey'&&formType !== 'login'" :src="imgSrc" @click="switchHandle" class="login-img"> -->
          <div class="login-title" :style="{ marginBottom: loginTitle == '通行密钥登录' ? '30px' : '0px' }">{{ loginTitle }}</div>
          <!-- 登录密码验证 -->
          <FormItem class="pt-30px" v-if="formType === 'beforeLogin'||formType==='resignByPassKey'" ref="beforeLoginFormRef" :schemaParam="beforeLoginSchema" />
          <!-- 正式登录 -->
          <FormItem class="pt-30px" v-if="formType === 'login'" ref="loginFormRef" :schemaParam="loginSchema" />
          <!-- 注册表单 -->
          <FormItem class="pt-30px" v-if="formType === 'register'" ref="registerForm"
            :schemaParam="registerSchema" />
          <div class="xieyi">
            <el-checkbox v-model="isAgree">我已阅读并同意<span style="color: #4fa1a4"
                  @click.stop.prevent="newOpen(0)">《隐私声明》</span><span style="color: #4fa1a4"
                  @click.stop.prevent="newOpen(1)">《用户协议》</span></el-checkbox>
          </div>
          <!-- before登录 -->
          <div v-if="formType === 'beforeLogin'" class="login-footer">
            <el-button class="loginButton" :loading="loading" :disabled="!isAgree" ref="loginButton" type="primary" size="large" style="width: 100%;" @click.prevent="beforeLogin">
              登录
            </el-button>
            <div class="flex" style="justify-content: space-between;">
              <el-button class="forget-pwd-btn" link size="small" @click.prevent="formType='loginByPassKey'">
                通行密钥登录
              </el-button>
              <el-button class="forget-pwd-btn" link size="small" @click.prevent="retrievePassword">
                忘记密码
              </el-button>
            </div>

          </div>
          <!-- 继续登录 -->
          <div v-if="formType === 'login'" class="login-footer">
            <el-button class="loginButton" :loading="loading" ref="loginButton" type="primary" size="large" style="width: 100%;" @click.prevent="verifyUser">
              继续登录
            </el-button>
            <div class="flex" style="justify-content: space-between;">
              <el-button class="forget-pwd-btn" link size="small" @click.prevent="formType='loginByPassKey'">
                通行密钥登录
              </el-button>
              <el-button class="forget-pwd-btn" link size="small" @click.prevent="retrievePassword">
                忘记密码
              </el-button>
            </div>

          </div>
          <!--通行密钥登录  -->
          <div v-if="formType === 'loginByPassKey'" class="login-footer">
            <el-button class="loginButton" :loading="passKeyLoginloading" ref="loginButton" :disabled="!isAgree" type="primary" size="large" style="width: 100%;" @click.prevent="passKeyLogin">
              登录
            </el-button>
            <div class="flex" style="justify-content: space-between;">
              <el-button class="forget-pwd-btn" link size="small" @click.prevent="formType='beforeLogin'">
                账号密码登录
              </el-button>
              <el-button class="forget-pwd-btn" link size="small" @click.prevent="formType='resignByPassKey'">
                去注册
              </el-button>
            </div>
          </div>
          <!-- 通行密钥登录 -->

          <!--通行密钥注册  -->
          <div v-if="formType === 'resignByPassKey'" class="login-footer" >
            <el-button class="loginButton" :loading="passKeyRegisterloading" ref="loginButton" type="primary" size="large" style="width: 100%;" @click.prevent="passKeySign">
              注册
            </el-button>
            <el-button class="forget-pwd-btn" link size="small" @click.prevent="formType='loginByPassKey'">
              去登录
            </el-button>
          </div>
          <!-- 通行密钥注册 -->

          <!-- <div v-if="formType === 'register'" class="login-footer">
            <el-button :loading="loading" :disabled="!isAgree" type="primary" size="large" style="width: 100%;" @click.prevent="handleRegister">
              注册
            </el-button>
          </div> -->
        </div>
      </div>
      <div class="copyright_text">
        <span>Copyright © 2015-2024</span>
        <a style="color: #4FA1A4;margin: 0 8px;" href="https://beian.miit.gov.cn" target="_blank">京ICP备2024044205号</a>
        <span>北京传世博润科技有限公司</span>
      </div>
    </div>
  </div>
  <!-- <el-dialog v-model="centerDialogVisible" width="360" title="图形验证码" align-center>
    <template #default>
      <div class="img-code">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="demo-ruleForm" @submit.native.prevent>
          <el-form-item>
            <div class="img_code">
              <img :src="imgCodePath" />
              <span>看不清?<span class="text_btn" @click="getImgCode">换一张</span></span>
            </div>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input v-model="ruleForm.captcha" placeholder="请输入图形验证码" clearable @keyup.enter="sendCode" />
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="large" @click="sendCode">确定</el-button>
      </div>
    </template>
  </el-dialog> -->
  <AsyncRetrievepassword :schemaInfo="retrievepassword" :operate="operate"></AsyncRetrievepassword>>
  <!-- 图形验证码 -->
   <!-- <DialogPlus modal-class="auth-user" append-to-body v-model="imgCheckDialog" width="460px"
   maxHeight="150px" :close-on-click-modal="false" title="图形验证">
   <div class="select-tenant">
        <el-form label-position="top" ref="pictureFormRef" :model="pictureFormData"
          :rules="pictureRules" class="login-form" auto-complete="on">
          <el-form-item prop="validateCode" label="图形验证码">
            <el-input class="captcha" v-model.trim="pictureFormData.validateCode" placeholder="请输入图形验证码" tabindex="2"
              autocomplete="on">
              <template #append>
                <img class="h-26px" :src="imgCaptchaBase64" @click="refreshPictureCode" />
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
   <template #footer>
        <el-button @click="()=>{imgCheckDialog=false}">取 消</el-button>
        <el-button :loading="sendCodeLoading" type="primary"
          @click="checkPictureCode">发送验证码至手机</el-button>
          </template>
   </DialogPlus> -->
</template>


<script lang="tsx" setup name="portalLogin">
import { defineAsyncComponent } from 'vue';
import Header from './components/Header/index.vue'
import useUserStore from '@/store/modules/user';
import useIdaasStore from '@/store/modules/idaas';
import sysConfigStore from '@/store/modules/sysConfig'
import { useValidator } from '@/hooks/useValidator'
import { FormSchema } from '@/components/FormPlus'
import useCountdown from '@/hooks/useCountdown'
import { ElMessageBox } from 'element-plus'
import {
  checkLoginUser,
  checkDeviceTypeRegist,
  signUp,
} from '@/api/modules/idaas';
import type { FormRules } from 'element-plus'
import { v4 as uuidv4 } from 'uuid';
import Base64url from '@/hooks/base64url'
import md5 from 'md5';
import useLogin from '@/store/modules/login'
import CryptoJS from 'crypto-js'
import { createStateHashCode, getAssetsImages, blobToImageLink, isJsonString } from '@/utils/common';
import {
  getLoginWebAuthn, sendLoginCode, checkImgCode, registWebAuthn, getWebAuth4jLogin
} from '@/api/modules/idaas'

const AsyncPasswordStrengthMeter = defineAsyncComponent(() =>
  import('../../components/PasswordStrengthMeter/index.vue')
);
const AsyncRetrievepassword = defineAsyncComponent(() =>
  import('../../components/Retrievepassword/index.vue')
);
const loginStore = useLogin()
const { required, phone, isUSCCCode } = useValidator();

const { proxy } = getCurrentInstance() as any;
const route = useRoute();

const loginButton = ref()

const isAgree = ref(false);

/** 打开用户阅读协议 */
function newOpen(num) {
  if (num == 0) {
     window.open(window.location.origin + '/userPrivate')
  } else {
    window.open(window.location.origin + '/userAgree')
  }
}

// ! 忘记密码
const retrievepassword = ref({
  visible: false
})
// retrievepassword(忘记密码) modifypassword(修改密码)
const operate = ref('retrievepassword')

/**
 * 去修改密码
 * @param param0 
 */
function changePassword({
  mobileNo,
  logonUser,
  name
}) {
  idaasStore.idaasUserInfo = {
    principal: {
      mobileNo: mobileNo,
      logonUser: logonUser,
      name: name
    }
  }
  // 去修改逻辑
  retrievePwdHanlder('modifypassword')
}

/**
 * 忘记密码
 */
async function retrievePassword() {
  if (logonUser.value) {
    let res: any = await checkLoginUser(logonUser.value);
    if (res?.code == '00000') {
      let checkRes = res.data || {};
      if (checkRes) {
        changePassword({
          mobileNo: checkRes.mobileNo,
          logonUser: checkRes.logonUser,
          name: checkRes.userName
        })
      } else {
        retrievePwdHanlder()
      }
    } else {
      res?.msg && proxy.$ElMessage.error(res.msg);
    }
  } else {  
    let formData = await beforeLoginFormRef.value.getData();
    if (formData.logonUser) {
      logonUser.value = formData.logonUser;
      retrievePassword()
    } else {
      retrievePwdHanlder()
    }
  }
  logonUser.value = ''
}

/**
 * 找回密码处理函数
 * @param type 
 */
function retrievePwdHanlder(type = 'retrievepassword') {
  retrievepassword.value.visible = true;
  operate.value = type
}

const formTypeMap = {
  resignByPassKey: '通行密钥注册',
  loginByPassKey: '通行密钥登录',
  beforeLogin: '手机号登录',
  login: '登录验证',
  // 默认情况(比如 register 或其他)映射到 '注册申请'
};

const loginTitle = computed(() => {
  return formTypeMap[formType.value] || '注册申请';
});

const formType = ref(proxy.$route.query.formType || 'beforeLogin');
const beforeLoginFormRef = ref() // 登录前表单
const loginFormRef = ref() // 登录表单
const registerForm = ref() // 注册表单
const pictureFormRef = ref() //
const pictureFormData = ref<any>({}) // 注册表单
const pictureRules = ref<FormRules>({
  validateCode: [
    { required: true, trigger: 'blur', message: '请输入图形验证码' },
    {
      // 图形验证码校验
      validator: (rule: any, value: any, callback: any) => {
        if (value && vCode.value && value !== vCode.value) {
          callback(new Error('验证失败'));
        } else if (value && vCode.value) {
          callback();
        }
        callback();
      },
      trigger: "change",
    }
  ]
})
/** 图形验证码图片。 */
const imgCaptchaBase64 = ref('');
const vCode = ref(''); // 图片校验的编码
// 登录表单
const beforeLoginSchema = reactive<FormSchema[]>([
  {
    field: 'logonUser',
    label: '请输入手机号/账号',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {},
    formItemProps: {
      rules: [required()], // 校验规则
    }
  },
  {
    field: 'password',
    label: '请输入密码',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      showPassword: true,
      autocomplete: 'current-password'
    },
    formItemProps: {
      rules: [required()], // 校验规则
    }
  },
])
// 登录表单
const loginSchema = reactive<FormSchema[]>([
  {
    field: 'mobileNo',
    label: '验证手机号',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      disabled: true,
      readonly: true,
      formatter: (value: string) => {
         if (!value) return '';
          const str = String(value); // 确保是字符串
          if (str.length < 7) return str; // 长度不够不处理
          return str.substring(0, 3) + '****' + str.substring(7);
      }
    },
    formItemProps: {
      rules: [required()], // 校验规则
    }
  },
  {
    field: 'smsCode',
    label: '短信验证码',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      slots: {
        append: () => {
          return (
            <>
              {
                sendCodeLoading2.value ?
                  <span class="w-80px text-center cursor-not-allowed fontC-4fa1a4">{`重新获取(${timeLeft2.value})s`}</span>
                  :
                  <span class="text-center cursor-pointer fontC-4fa1a4" v-show={!sendCodeLoading2.value} onClick={() => {
                    getLoginSmsCode()
                  }}>{sendCodeText.value}</span>
              }
            </>
          )
        }
      }
    },
    formItemProps: {
      rules: [
        {
          validator: (rule: any, value: any, callback: any) => {
            if (disabledverifyUser.value) {
              callback(new Error('请先获取验证码'));
            }
            callback()
          },
          trigger: ["change","blur"],
        },
        required(),
      ], // 校验规则
    }
  },
])
const switchHandle = () => {
  formType.value = formType.value === 'beforeLogin' ? 'register' : 'beforeLogin';
  clearFormData()
}

// 重置表单
function clearFormData() {
  password.value = ''
  beforeLoginFormRef.value.setValue({}, true);
  registerForm.value.setValue({}, true);
}

/**
 * 校验注册密码
 */
function validatorPassword(rule, value, callback) {
  if (!password.value) {
    callback(new Error('该项为必填项'))
  } else if (loginStore.firstUnmetRequirement) {
    callback(new Error(`需要${loginStore.firstUnmetRequirement}`))
  } else {
    callback();
  }
}

/**
 * 校验确认密码
 */
function validatorConfirmpwd(rule, value, callback) {
  if (value != password.value) {
    callback(new Error('密码不一致,请重新输入'))
  } else {
    callback();
  }
}

// 注册表单
const password = ref('')
const registerSchema = reactive<FormSchema[]>([
  {
    field: 'tenantName',
    label: '企业名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      maxlength: 100,
    },
    formItemProps: {
      rules: [required()], // 校验规则
    }
  },
  {
    field: 'tenantCode',
    label: '统一社会信用代码',
    component: 'Input',
    colProps: {
      span: 12
    },
    componentProps: {
      maxlength: 200,
    },
    formItemProps: {
      rules: [required(), isUSCCCode('统一社会信用代码格式不正确')], // 校验规则
    }
  },
  {
    field: 'userName',
    label: '账号',
    component: 'Input',
    colProps: {
      span: 12
    },
    componentProps: {
      maxlength: 20,
    },
    formItemProps: {
      rules: [required(),phone(), /* beforeRegisterCheck('name')*/], // 校验规则
    }
  },
  {
    field: 'password',
    label: '登录密码',
    component: 'Input',
    colProps: {
      span: 12
    },
    componentProps: {
      maxlength: 20,
      type: 'password',
      showPassword: true,
      autocomplete : 'new-password'
    },
    formItemProps: {
      // 校验规则
      rules: [
        required(),
        { 
          validator: validatorPassword,
          trigger: ['change','blur']
        },
      ], 
      slots: {
        default: () => {
          return (
            <>
               <AsyncPasswordStrengthMeter v-model={password.value} onChange={() => {
                  registerForm.value.setValue({
                    password: password.value
                  })
                  registerForm.value.formValidation(['password'])
                }}/>
            </>
          )
        }
      }
    }
  },
  {
    field: 'confirmpwd',
    label: '确认登录密码',
    component: 'Input',
    colProps: {
      span: 12
    },
    componentProps: {
      placeholder:'请输入密码',
      maxlength: 20,
      type: 'password',
      showPassword: true,
      clearable: false,
      autocomplete : 'new-password'
    },
    formItemProps: {
      // 校验规则
      rules: [
        required(),
        {
          validator: validatorConfirmpwd,
          trigger: ['change','blur']
        },
      ], 
    }
  },
  {
    field: 'mobileNo',
    label: '联系方式',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      maxlength: 20,
    },
    formItemProps: {
      rules: [required(), phone(), /*beforeRegisterCheck('mobileNo')*/], // 校验规则
    }
  },
  {
    field: 'smsCode',
    label: '短信验证码',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      slots: {
        append: () => {
          return (
            <>
              {
                sendCodeLoading.value ?
                  <span class="w-80px text-center fontC-4fa1a4">{`重新获取(${timeLeft.value})s`}</span>
                  :
                  <span class="text-center cursor-pointer fontC-4fa1a4" v-show={!sendCodeLoading.value} onClick={() => {
                  //  getRegisterImgCode()
                  }}>{'获取短信验证码'}</span>
              }
            </>
          )
        }
      }
    },
    formItemProps: {
      rules: [required()], // 校验规则
    }
  },
])

const userStore = useUserStore()
const idaasStore = useIdaasStore();

/** 登录按钮的loading */
const loading = ref(false)
/** 发送短信验证码的loading */
const sendCodeLoading = ref(false);
const sendCodeLoading2 = ref(false);
const sendCodeText = ref('获取短信验证码');
const disabledverifyUser = ref(true)
/** 重置密码保存的loading */
const saveLoading = ref(false);

// ! 图形验证
const centerDialogVisible = ref(false);
const imgCodePath = ref('')
const imgCodeGuid = ref('');
const ruleFormRef = ref();
const ruleForm = ref({
  captcha: ''
})
const rules = ref({
  captcha: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === '') {
          callback(new Error('请填写图形验证码'))
        } else {
          let params: any = {
            captcha: value,
            captchaGuid: imgCodeGuid.value
          };
          checkImgCode(params).then((res: any) => {
            if (res.code == proxy.$passCode) {
              if (!res.data) {
                callback(new Error("验证码错误,请重新填写"));
              } else {
                callback();
              }
            } else {
              callback(new Error(res.msg));
            }
          }).catch((xhr) => {
            callback(new Error(xhr.msg));
          });
        }
      }, trigger: 'blur'
    },
    {
      min: 1,
      message: '请填写图形验证码',
      trigger: 'change',
    },
  ]
})

// const getImgCode = () => {
//   getImgCodeSrc({ width: 180, height: 40 }).then((res) => {
//     imgCodeGuid.value = res.data.data?.guid || '';
//     imgCodePath.value = res.data.data?.imageBase64 || '';
//     if (!centerDialogVisible.value) {
//       ruleForm.value.captcha = '';
//       centerDialogVisible.value = true;
//       nextTick(() => {
//         ruleFormRef.value.clearValidate();
//       })
//     }
//   })
// }

const { timeLeft, minutes, seconds, start, stop, reset } = useCountdown(60);

watchEffect(() => {
  if (timeLeft.value == 0) {
    reset()
    sendCodeLoading.value = false
  }
})


// 身份验证短信获取倒计时
const { timeLeft:timeLeft2, start:start2, reset:reset2 } = useCountdown(60);
watchEffect(() => {
  if (timeLeft2.value == 0) {
    reset2()
    sendCodeText.value = '再次发送'
    sendCodeLoading2.value = false
  }
})
/**
 * 手机号身份验证
 */
async function getLoginSmsCode() {
  let validate = await loginFormRef.value.formValidation(['mobileNo']);
  if (validate) {
    let params = await loginFormRef.value.getData()
    sendLoginCode(params.mobileNo).then(res=>{
      if (res.data.code == proxy.$passCode) {
        sendCodeLoading2.value = true;
        disabledverifyUser.value = false;
        loginFormRef.value.formValidation(['smsCode']);
        start2()
      }
    });
  }
}

// // 获取注册的图片验证
// const getRegisterImgCode = async () => {
//   let validate = await registerForm.value.formValidation(['mobileNo'])
//   if (validate) {
//     imgCheckDialog.value = true;
//     pictureFormData.value.validateCode = null;
//     await nextTick();
//     getCommoncheckImgCode()
//   }
// }

// function getCommoncheckImgCode() {
//   commoncheckImgCode().then(async (res) => {
//     if (res.status == 200) {
//       vCode.value = res.headers['v-code'] || ''
//       imgCaptchaBase64.value = await blobToImageLink(res.data)
//       console.log(imgCaptchaBase64.value, vCode.value, 'imgCaptchaBase64');
//     } else {
//       vCode.value = ''
//       imgCaptchaBase64.value = ''
//     }
//   })
// }

// async function refreshPictureCode() {
//   getCommoncheckImgCode()
// }

// async function checkPictureCode() {
//   let validate = await pictureFormRef.value.validate()
//   if (validate) {
//     await getSmsCode2();
//     imgCheckDialog.value = false;
//   }
// }

// const getSmsCode2 = async () => {
//   let validate = await registerForm.value.formValidation(['mobileNo'])
//   if (validate) {
//     let params = await registerForm.value.getData()
//     userApi.sendRegisterCode(params.mobileNo);
//     sendCodeLoading.value = true;
//     start()
//   }
// }

// const sendCode = () => {
//   const formEl = ruleFormRef.value;
//   if (!formEl) return;
//   formEl.validate((valid, fields) => {
//     if (valid) {
//       centerDialogVisible.value = false;
//       handleRegister();
//     }
//   })
// }

// ! 图形验证弹框
const imgCheckDialog = ref(false)

let LOGINCODE = {
  grant_type: 'authorization_code',
  response_type: 'code',
  client_id: sysConfigStore().getConfig('appKey'),
  scope: 'other',
  state: 'authorization-life',
  loginRedirectUrl: window.location.origin // 登录重定向域名
}


const mobileNo = ref('')
const logonUser = ref('')
/**
 * 登录前置处理(密码90天验证)
 */
async function beforeLogin() {
  let validate = await beforeLoginFormRef.value.formValidation();
  if (!validate) return
  let formData = await beforeLoginFormRef.value.getData();
  debugger
  let _logonUser = formData.logonUser;
  let password = formData.password;
  loginStore.encodePwd = CryptoJS.AES.encrypt(password, sysConfigStore().getConfig('appKey')).toString();
  let loginRes = await idaasStore.login(formData);
  if (!loginRes) return
  let res: any = await checkLoginUser(_logonUser)
  if (res?.code != '00000') {
     res?.msg && proxy.$message.error(res?.msg);
     return;
  }
  let checkRes = res.data || {};
  mobileNo.value = checkRes.mobileNo; // 当前用户的手机号
  logonUser.value = checkRes.logonUser; // 当前用户的手机号
  // console.log(checkRes, 'checkLoginUser');
  // 继续登录逻辑
  function continueLogin() {
    if (import.meta.env.VITE_verify === 'false' || !checkRes.isCheckSmsValidateCode) {
      handleLogin({
        logonUser: logonUser.value,
        password: password
      })
      return
    }
    formType.value = 'login';
    nextTick(() => {
      loginFormRef.value.setValue({
        logonUser: logonUser.value,
        mobileNo: mobileNo.value,
        password: password
      })
    })
  }
  // 未到90天校验 pwdValidityDateSurplusDays密码有效期剩余天数
  if (checkRes && checkRes.pwdValidityDateSurplusDays > 0) {
    continueLogin()
  } else {
    ElMessageBox.confirm("您的密码已超过90天未修改", "提示", {
      confirmButtonText: "去修改",
      cancelButtonText: "继续登录",
      type: "warning",
      showCancelButton:false,
      closeOnClickModal: false, // 禁止点击模态框背景关闭
      closeOnPressEscape: false, // 禁止按下ESC键关闭
      showClose: false // 可选:隐藏右上角的关闭按钮
    }).then(() => {
      changePassword({
        mobileNo: mobileNo.value,
        logonUser: logonUser.value,
        name: checkRes.userName
      })
    }).catch(() => {
      continueLogin()
    })
  }
}

/**
 * 验证用户身份
 */
 async function verifyUser() {
  let validate = await loginFormRef.value.submitForm();
  if (validate) {
    let params = await loginFormRef.value.getData();
    handleLogin(params)
  }
}

/**
 * 触发登录服务
 * @param params 
 */
async function handleLogin(params) {
  loading.value = true
  let client_id = params.client_id = proxy.$route.query.client_id;
  let redirect_uri = params.redirect_uri = proxy.$route.query.redirect_uri;
  loginStore.smsValidateCode = params.smsCode
  idaasStore.login(params).then((res: any) => {
    loading.value = false
    const result = isJsonString(res) ? JSON.parse(res) : res;
    let scope = result.data.authorities?.map(a => a.authority).join(' ');
    if (!client_id) {
      client_id = sysConfigStore().getConfig('appKey');
    }
    let hrefOrigin = window.location.origin;
    if (!redirect_uri) {
      redirect_uri = hrefOrigin + '/login';
    }
    let state = createStateHashCode();
    let url = `${hrefOrigin}/idaas/oauth2/authorize?response_type=${LOGINCODE.response_type}&client_id=${client_id}&scope=other&state=${state}&redirect_uri=${encodeURIComponent(redirect_uri)}`
    localStorage.setItem('idaas_code_url', url)
    window.location.href = url
  }).catch(() => {
    loading.value = false
  })
}

// !注册前的校验
// function beforeRegisterCheck(fieldName: string, errMsg?: string) {
//   return {
//     validator: (rule: any, value: any, callback: any) => {
//       if (value && formType.value == 'register') {
//         userApi.checkUser({ [fieldName]: value }).then(res => {
//           res ? callback(errMsg ? new Error(errMsg) : new Error(res)) : callback()
//         })
//       } else {
//         callback();
//       }
//     },
//     trigger: 'blur'
//   }
// }

// async function handleRegister() {
//   let validate = await registerForm.value.submitForm()
//   if (!validate) return
//   let formData = await registerForm.value.getData(false)
//   userApi.registerTenant(formData).then((res: any) => {
//     if (res.data.code == proxy.$passCode) {
//       proxy.$message.success('注册成功')
//       registerForm.value.setValue({})
//     }
//   })
// }

//const logout = ref(proxy.$route.query.logout);

// // 存储跳转其他系统的url参数
// function saveQueryParams() {
//   let query = proxy.$route.query;
//   routeStore.fromUrl = query.fromUrl
//   routeStore.toUrl = query.toUrl
//   routeStore.backUrl = query.backUrl
//   console.log(routeStore, 'routeStore');
// }

function setKeyUp() {
  if (loginButton) {
    document.onkeyup = event => {
      console.log(event);
      if (event.key === 'Enter') {
        beforeLogin()
      }
    }
  }
}
const passKeyRegisterloading = ref(false);
const passKeyLoginloading = ref(false);

const createCredential =  async () => {
  let resignForm = await beforeLoginFormRef.value.getData()
  return registWebAuthn().then((res: any) => {
    let options = res.data
    let publicKeyCredentialCreationOptions = {
      rp: {
        id: options.rp.id,
        name: options.rp.name
      },
      user: {
        id: Base64url.decodeBase64url(uuidv4()),
        name: resignForm.logonUser,
        displayName: resignForm.logonUser,
      },
      challenge: Base64url.decodeBase64url(options.challenge),
      pubKeyCredParams: options.pubKeyCredParams,
      timeout: options.timeout,
      excludeCredentials: options.excludeCredentials.map(credential => {
        return {
          type: credential.type,
          id: Base64url.decodeBase64url(credential.id)
        }
      }),
      authenticatorSelection: {
        requireResidentKey: false,
        residentKey: "preferred"
      },
      attestation: options.attestation,
      extensions: options.extensions
    };

    let credentialCreationOptions = {
      publicKey: publicKeyCredentialCreationOptions
    };
    console.log(credentialCreationOptions)
    return navigator.credentials.create(credentialCreationOptions);
  })
}
const passKeySign = async () => {
  let validate = await beforeLoginFormRef.value.submitForm()
  if (validate) {
    let params = await beforeLoginFormRef.value.getData()
    checkDeviceTypeRegist({
      logonUser: params.logonUser,
      platform: navigator.userAgentData.platform
    }).then((response: any) => {
      console.log(response)
      if (response.data.code === '00000') {
        createCredential().then((credential: any) => {
          console.log(credential)
          let userRQVO = {
            logonUser: params.logonUser,
            password: md5(params.password),
            authenticator: {
              clientDataJSON: Base64url.encodeBase64url(credential.response.clientDataJSON),
              attestationObject: Base64url.encodeBase64url(credential.response.attestationObject),
              clientExtensions: JSON.stringify(credential.getClientExtensionResults()),
              deviceType: navigator.userAgentData.platform
            }
          }
          passKeyRegisterloading.value = true;
          signUp(userRQVO).then((result: any) => {
            passKeyRegisterloading.value = false;
            if (result?.code === '00000') {
              formType.value = 'loginByPassKey'
              proxy.$message.success('注册成功!');
            } else {
              result?.msg && proxy.$message.error(result.msg);
            }
          }).catch(error => {
            console.log(error)
            passKeyRegisterloading.value = false;
          })
        })
      }
    })
  }
}
const loginWebAuthn = () => {
  return getLoginWebAuthn().then((res: any) => {
    let options = res.data
    let publicKeyCredentialRequestOptions = {
      challenge: Base64url.decodeBase64url(options.challenge),
      timeout: options.timeout,
      rpId: options.rpId,
      allowCredentials: options.allowCredentials.map(credential => {
        return {
          type: credential.type,
          id: Base64url.decodeBase64url(credential.id)
        }
      }),
      userVerification: "required",
      extensions: options.extensions
    };

    let credentialRequestOptions: any = {
      publicKey: publicKeyCredentialRequestOptions
    };

    return navigator.credentials.get(credentialRequestOptions);
  });
}
const passKeyLogin = () => {
  loginWebAuthn().then((credential: any) => {
    let userRQVO = {
      clientDataJSON: Base64url.encodeBase64url(credential.response.clientDataJSON),
      credentialId: credential.id,
      authenticatorData: Base64url.encodeBase64url(credential.response.authenticatorData),
      signature: Base64url.encodeBase64url(credential.response.signature),
      clientExtensionsJSON: JSON.stringify(credential.getClientExtensionResults()),
    }
    passKeyLoginloading.value = true;
    getWebAuth4jLogin(userRQVO).then(res => {
      console.log(res)
      passKeyLoginloading.value = false;
      const result = typeof res.data == 'string' ? JSON.parse(res.data) : res.data;
      if (result.code == '00000') {//第一次初始化登录。
        let client_id = proxy.$route.query.client_id;
        let redirect_uri = proxy.$route.query.redirect_uri;
        if (!client_id) {
          client_id = sysConfigStore().getConfig('appKey');
        }
         let hrefOrigin = window.location.origin;
        if (!redirect_uri) {
          //redirect_uri = import.meta.env.VITE_redirectUrl
          redirect_uri = hrefOrigin + '/login';
        }
        let state = createStateHashCode();
        let url = `${hrefOrigin}/idaas/oauth2/authorize?response_type=${LOGINCODE.response_type}&client_id=${client_id}&scope=other&state=${state}&redirect_uri=${encodeURIComponent(redirect_uri)}`
        localStorage.setItem('idaas_code_url', url)
        window.location.href = url
      }
    }).catch(error=>{
      console.log(error)
      passKeyLoginloading.value = false;
    })
  });

}

/**
 * 直接去获取验证码表单
 */
function toCheckSmsCode() {
  let isCheckSms = loginStore.isCheckSms;
  if (isCheckSms) {
    let password = CryptoJS.AES.decrypt(loginStore.encodePwd || '', sysConfigStore().getConfig('appKey')).toString(CryptoJS.enc.Utf8)
    let principal = idaasStore.idaasUserInfo.principal
    formType.value = 'login';
    nextTick(()=>{
      loginFormRef.value.setValue({
        logonUser: principal?.logonUser,
        mobileNo: principal?.mobileNo,
        password: password
      })
      loginStore.isCheckSms = false // 重置状态
    })
  }
}


onBeforeMount(() => {
  // 子系统退出不需要清除门户的token
  // if (logout.value && logout.value == '1') {
  //   userStore.logout({
  //         logMessage:'logout-正常触发退出登录'
  //       });
  // }
 /// saveQueryParams();
  toCheckSmsCode();
});

onMounted(()=>{
//  new DevicePixelRatio().init();
 setKeyUp()
})

onBeforeUnmount(()=>{
  document.onkeyup = null
})


</script>

<style lang="scss" scoped>

.main-h {
  height: 100%;
}

.login_form {
  position: relative;
  background: #FFFFFF;
  box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.2);
  border-radius: 2px;
}

.login-size {
  padding: 60px 50px;
  width: 440px;
  height: 430px;
}

.register-size {
  padding: 40px 32px;
  width: 548px;
  height: 580px;
}

.login-footer {
  display: flex;
  flex-direction: column;
}

:deep(.el-button--primary) {
  background-image: linear-gradient(116deg, #0C48F5 0%, #23D6D1 95%);

  &.is-disabled {
    background-image: none;
  }
}

.login-img {
  cursor: pointer;
  width: 72px;
  height: 72px;
  position: absolute;
  top: 0;
  right: 0;
}

.login-title {
  font-family: PingFangSC-Semibold;
  font-size: 24px;
  color: #212121;
  letter-spacing: 0;
  line-height: 36px;
  font-weight: 600;
}

:deep(.xieyi) {
  margin-bottom: 10px;

  .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #666;
  }
}

.bg-banner {
  // position: fixed;
  // z-index: 1001;
  width: 100%;
  height: 90%;
  background-image: url('../../assets/images/login-bg.png');
  background-size: cover;
  /* 背景图覆盖整个元素 */
  background-position: center;
  /* 背景图居中 */
  background-repeat: no-repeat;
  /* 防止背景图重复 */
}

#login-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  // position: absolute;
  // top: 50%;
  // left: 50%;
  // transform: translateX(-50%) translateY(-51%);
  // background-color: #fff;

  .login-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 500px;
    width: 368px;
    overflow: hidden;

    .title-container {
      position: relative;

      .title {
        font-size: 28px;
        color: #212121;
        letter-spacing: 0;
        text-align: center;
        line-height: 42px;
        font-weight: 600;
        margin-bottom: 32px;
      }
    }
  }

  :deep(.el-input) {
    height: 36px;
  }

}

.copyright_text {
  width: 100%;
  font-size: 12px;
  color: #2c3e50;
  line-height: 18px;
  text-align: center;
  font-weight: 400;
  position: absolute;
  bottom: 2px;
  left: 50%;
  transform: translateX(-50%);
}


.forget-pwd-btn {
  cursor: pointer;
  margin-top: 12px;
  font-size: 14px;
  color: #999999;
  line-height: 21px;
  font-weight: 400;
}

.code-desc {
  font-size: 12px;
  color: #999999;
  letter-spacing: 0;
  line-height: 17px;
  font-weight: 400;
  margin-top: 8px;
}

.pb-22px {
  padding-bottom: 22px;
}

.overflow-auto {
  overflow: auto;
}

.pt-30px {
  padding-top: 30px;
}

.flex {
  display: flex;
}

.loginButton.is-disabled {
  background: rgb(159.5, 206.5, 255);
  color: #fff;
}
.el-button.is-link:hover {
  color: inherit;
}
</style>