<template>
  <div class="main login-right-info" ref="login">
    <div class="login-center-form">
      <div class="login-center-box">
        <img
          v-show="loginInfo?.LA_SYSTEM_LOGIN_TITLE_ICAN"
          class="login-top-logo"
          :src="loginInfo?.LA_SYSTEM_LOGIN_TITLE_ICAN"
        />
        <div v-show="loginInfo?.LA_SYSTEM_LOGIN_TITLE_ICAN" class="login-center-top-devider"></div>
        <p class="login-center-title">{{ loginInfo?.LA_SYSTEM_LOGIN_TITLE }}</p>
      </div>

      <login-form
        :loginMode="currentLoginMode"
        :currentLoginMode="currentLoginMode"
        :isLoginError="isLoginError"
        :loginErrorMsg="loginErrorMsg"
        :loginInfo="loginInfo"
        :validateInfos="validateInfos"
        :modelRef="modelRef"
        :tenantOptions="tenantOptions"
        :showCode="showCode"
        :loginCodeInfo="loginCodeInfo"
        :loginBtn="loginBtn"
        :filterOption="filterOption"
        :getLoginCodeData="getLoginCodeData"
        :handleSubmit="handleSubmit"
      ></login-form>
    </div>

    <h-modal
      v-model:visible="orgVisible"
      :title="t('login.selectOrg')"
      :okText="t('platform.common.ok')"
      :cancelText="t('platform.common.cancel')"
      centered
      :maskClosable="false"
      :confirmLoading="orgModalLoading"
      @ok="okEvent"
    >
      <h-form id="formOrg" layout="vertical" class="user-layout-login">
        <h-form-item v-bind="validateInfos.orgId">
          <h-select
            size="large"
            v-model:value="modelRef.orgId"
            :placeholder="t('login.selectOrg')"
            style="width: 100%"
            :options="orgList"
            :getPopupContainer="getPopupContainer"
          ></h-select>
        </h-form-item>
      </h-form>
    </h-modal>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  computed,
  toRefs,
  inject,
  watch,
  getCurrentInstance,
} from 'vue';
import {
  getSmsCaptcha,
  getTenant,
  getLoginCode,
  getOrgByUserName,
  changeOrgIdOfUserInRedis,
  getLoginModeByUserName,
} from '@/api/platform/user/login';
// import { message, notification } from 'ant-design-vue';
import { message, notification } from '@crami/ui';
import { useForm } from 'ant-design-vue/es/form';
import type { AxiosError } from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { LOGIN } from '@/store/modules/user/actions';
import { SET_INFO, SET_ROUTERS } from '@/store/modules/user/mutations';
import md5 from 'js-md5';
import { setI18nLanguage, useI18n } from '@crami/locale';
import { langMap } from '@/locales/index';
// import { stubFalse } from 'lodash-es';
// import Template from '@/views/workflow/workflowconfig/Template.vue';
import Crypto from '@/utils/crypto';
import LoginForm from './LoginForm.vue';
import { SET_SIZE_TYPE } from '@/store/modules/app/mutations';
export default defineComponent({
  name: 'Login',

  setup() {
    const { t } = useI18n();
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    const loginErrorMsg = ref(t('login.loginErrorMsg'));
    const state = reactive({
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,

      time: 60,
      smsSendBtn: false,
    });
    const orgVisible = ref(false);
    // 每次输入都展示验证码
    const showCode = ref(true);
    const loginCodeInfo = reactive({
      key: '',
      image: '',
      src: '',
    });
    const orgList: any = ref([]);

    const loginInfo: any = inject('loginInfo');
    const orgModalLoading = ref(false);

    const handleUsernameOrEmail = (_rule: any, value: any) => {
      return new Promise(resolve => {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if (regex.test(value)) {
          state.loginType = 0;
        } else {
          state.loginType = 1;
        }
        resolve(state.loginType);
      });
    };
    const modelRef = reactive({
      // isValid: false,
      rememberMe: true,
      username: '',
      password: '',
      mobile: '',
      captcha: '',
      tenant: null,
      code: '',
      orgId: null,
    });

    let currentLoginMode = ref();
    const loginModeList = computed(() => {
      return (loginInfo && loginInfo.value && loginInfo.value.LOGIN_MODE) || [];
    });

    watch(
      loginModeList,
      val => {
        if (val && val.length) {
          currentLoginMode.value = val[0].value;
        }
      },
      { immediate: true },
    );

    const changeLoginMode = mode => {
      currentLoginMode.value = mode;
    };

    const valid = () => {
      console.log(modelRef.isValid);
    };

    const rulesRef = reactive({
      isValid: undefined,
      rememberMe: undefined,
      username: [
        { required: true, message: t('login.usernameErrorMsg'), type: 'string' },
        { validator: handleUsernameOrEmail, trigger: 'change' },
      ],
      password: [
        {
          required: true,
          message: t('login.inputUserPwd'),
          type: 'string',
          trigger: ['blur', 'change'],
        },
      ],
      mobile: [
        {
          required: true,
          // pattern: /^1[34578]\d{9}$/,
          message: t('login.mobileErrorMsg'),
          trigger: ['blur', 'change'],
        },
      ],
      captcha: [{ required: true, message: t('login.codeErrorMsg') }],
      code: [{ required: true, message: t('login.codeErrorMsg') }],
      tenant: [{ required: true, message: t('login.tenantErrorMsg') }],
      orgId: [{ required: true, message: t('login.orgErrorMsg') }],
    });
    const { validateInfos, validate, resetFields } = useForm(modelRef, rulesRef);

    const tenantOptions = ref([]);

    onMounted(() => {
      getTenantData();
      getLoginCodeData();
      valid();
    });

    const getTenantData = () => {
      getTenant()
        .then(res => {
          console.log('eeeee', res);
          tenantOptions.value = res.data.map(item => {
            return { label: item.ename ? item.ename : item.title, value: item.value };
          });
          // tenantOptions.push(...results);
        })
        .catch(() => {
          // requestFailed(err);
        })
        .finally(() => {
          // state.loginBtn = false;
        });
    };

    const getLoginCodeData = () => {
      getLoginCode()
        .then(res => {
          console.log('GET_CODE', res);
          loginCodeInfo.src = 'data:image/png;base64,' + res.data.img;
          loginCodeInfo.key = res.data.uuid;
        })
        .catch(() => {
          // requestFailed(err);
          loginCodeInfo.src = 'data:image/png;base64,';
        })
        .finally(() => {
          // state.loginBtn = false;
        });
    };

    const handleTabClick = (key: string) => {
      state.customActiveKey = key;
      resetFields();
    };

    const requestFailed = (err: AxiosError) => {
      console.log('requestFailed', err?.response?.data?.errorMessage);
      state.isLoginError = true;
      notification.error({
        message: t('login.requestErrorTitle'),
        description: ((err.response || {}).data || {}).errorMessage || t('login.requestErrorDesc'),
      });
    };
    const sizeType = computed(() => store.getters['user/info'].CONTROL_STYLE);
    //读取个人的多语言
    const userLang = computed(() => store.getters['user/info'].LANGUAGE);
    const loginSuccess = () => {
      // router.push(decodeURIComponent((route.query?.redirect as string) || '') || '/');
      router.push('/home');
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        // loading状态持续
        state.loginBtn = false;
        state.isLoginError = false;
        orgModalLoading.value = false;
        orgVisible.value = false;
        notification.success({
          message: t('login.loginSuccessTitle'),
          description: t('login.loginSuccessDesc'),
        });
        store.commit(`app/${SET_SIZE_TYPE}`, sizeType.value);
        store.dispatch('app/SET_LANG', userLang.value);
        setI18nLanguage(langMap[userLang.value]);
      }, 1000);
    };

    const loginFailed = errmsg => {
      state.loginBtn = false;
      state.isLoginError = true;
      showCode.value = true;
      loginErrorMsg.value = errmsg;
      getLoginCodeData();
    };

    const getCaptcha = (e: Event) => {
      e.preventDefault();

      validate('mobile')
        .then(values => {
          state.smsSendBtn = true;

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60;
              state.smsSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);

          const hide = message.loading(t('login.codeLoading'), 0);
          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500);
              notification.success({
                message: t('login.tipTitle'),
                description: t('login.getCodeSuccess') + res.captcha,
              });
            })
            .catch(err => {
              setTimeout(hide, 1);
              clearInterval(interval);
              state.time = 60;
              state.smsSendBtn = false;
              requestFailed(err);
            });
        })
        .catch(err => {
          console.log('err', err);
        });
    };

    const formData: any = ref({});
    const handleSubmit = (e: Event, rules: any[]) => {
      e.preventDefault();
      const validateNames = state.customActiveKey === 'tab1' ? rules : ['mobile', 'captcha'];
      state.loginBtn = true;
      validate(validateNames)
        .then(values => {
          // values.isValid = modelRef.isValid;
          const loginParams = { ...values };
          if (showCode.value) {
            loginParams['uuid'] = loginCodeInfo.key;
          }
          if (values.tenant) {
            loginParams['username'] = values.username + '@' + values.tenant;
            delete loginParams['tenant'];
          }
          // if (values.isValid) {
          //   loginParams.validTimes = loginInfo.value?.LA_LOGIN_FREE_DAYS;
          // }

          // 触发登录接口流程
          loginModeList.value.length > 1
            ? getMatchLoginMode(loginParams)
            : (function () {
                loginParams.loginMode = currentLoginMode.value;
                toLogin(loginParams);
              })();
        })
        .catch(err => {
          // 屏蔽错误处理
          // requestFailed(err);
          state.loginBtn = false;
        });
    };

    // 获取当前用户应该使用的默认登录方式
    const getMatchLoginMode = loginParams => {
      getLoginModeByUserName({
        userName: modelRef.username,
        companyId: modelRef.tenant,
      })
        .then(res => {
          if (res.code === 200) {
            loginParams.loginMode = res.data.LOGIN_MODE;
            toLogin(loginParams);
          } else {
            loginFailed(res.msg);
          }
        })
        .catch(() => {
          loginFailed(t('login.requestErrorDesc'));
        });
    };

    const getLoginOrgData = params => {
      modelRef.orgId = null;
      formData.value = params;
      orgList.value = [];
      getOrgByUserName({
        userName: params.username,
        // password: params.password,
        code: params.code,
        uuid: params.uuid,
        validTimes: params.validTimes,
      })
        .then(async res => {
          if (res.code == 200) {
            if (res.data?.length > 1) {
              state.loginBtn = false;
              orgVisible.value = true;
              orgList.value.push(
                ...res?.data?.map(item => {
                  return { label: item.title, value: item.value };
                }),
              );
            } else {
              changeOrgIdOfUser(res.data.length == 1 ? res.data[0].value : '');
            }
          } else {
            loginFailed(res.msg);
          }
        })
        .catch(() => {
          loginFailed(t('login.requestErrorDesc'));
        });
    };

    const toLogin = loginParams => {
      let { loginMode, password } = loginParams;
      loginParams.password =
        loginMode === 'IDM' ? new Crypto('AESNBHB3ZA==HKXt').encrypt(password) : md5(password);

      store
        .dispatch(`user/${LOGIN}`, loginParams)
        .then(() => {
          // 该步骤已确定code为200并设置完token
          getLoginOrgData(loginParams);
        })
        .catch(err => {
          loginFailed(err.msg || t('login.requestErrorDesc'));
        });
    };

    const changeOrgIdOfUser = async orgId => {
      let res = await changeOrgIdOfUserInRedis({ orgId });

      // if (orgVisible.value) {
      //   orgVisible.value = false;
      //   orgModalLoading.value = true;
      // }

      try {
        if (res.code === 200) {
          orgId ? localStorage.setItem('org_data', orgId) : localStorage.removeItem('org_data');
          clearCache();
          loginSuccess();
        } else {
          orgModalLoading.value = false;
          loginFailed(res.msg);
        }
      } catch (err) {
        orgModalLoading.value = false;
        loginFailed(t('login.requestErrorDesc'));
      }

      return res && res.code === 200;
    };

    const clearCache = () => {
      // 登录成功先执行置空个人信息数据，防止登录后遗留上次数据
      store.commit(`user/${SET_INFO}`, {});
      store.commit(`user/${SET_ROUTERS}`, []);
    };

    const okEvent = (e: Event) => {
      e.preventDefault();
      orgModalLoading.value = true;
      validate(['orgId'])
        .then(values => {
          changeOrgIdOfUser(values.orgId);
          // localStorage.setItem('org_data', values.orgId);
          // loginSuccess();
        })
        .catch(err => {
          // 屏蔽错误处理
          orgModalLoading.value = false;
          // requestFailed(err);
        });
    };

    const filterOption = (input: string, option: any) => {
      return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };
    const getPopupContainer = () => {
      return document.body;
    };

    return {
      t,
      ...toRefs(state),
      modelRef,
      validateInfos,
      loginCodeInfo,
      tenantOptions,
      orgVisible,
      orgList,

      valid,
      handleTabClick,
      handleSubmit,
      getCaptcha,
      orgModalLoading,
      okEvent,
      getLoginCodeData,
      loginInfo,
      filterOption,
      getPopupContainer,
      loginErrorMsg,
      // ++
      showCode,

      currentLoginMode,
      loginModeList,
      changeLoginMode,
    };
  },
  components: {
    // UserOutlined,
    // LockOutlined,
    LoginForm,
  },
});
</script>

<style lang="less" scoped>
// #formOrg.user-layout-login {
//   height: 240px;
// }
:deep(.user-layout-login) {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    width: 100%;
    height: 40px;
    padding: 0 15px;
    font-size: 16px;
  }

  .user-login-other {
    margin-top: 24px;
    line-height: 22px;
    text-align: left;

    .item-icon {
      margin-left: 16px;
      color: @disabled-color;
      font-size: 24px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }

    .register {
      float: right;
    }
  }
  .prefixIcon {
    color: @primary-color;
    font-size: @font-size-base;
  }

  .ant-tabs {
    .ant-tabs-nav::before {
      border-bottom: none;
    }
  }

  .login-input-user,
  .login-input-password {
    width: 16px;
    height: 16px;
    margin-right: 10px;
  }
  .login-select-creatdown-icon {
    width: 12px;
    height: 5px;
    color: #4e5a70;
  }
  .login-loaclhost {
    position: absolute;
    z-index: 99;
    top: 12px;
    left: 12px;
  }
  .ant-select-show-search.ant-select:not(.ant-select-customize-input) .ant-select-selector {
    // padding-left: 40px;
  }
  .ant-select-single.ant-select-show-arrow .ant-select-selection-search {
    margin-left: 30px;
  }

  //七天免登录的字体样式设置
  .sevenFreeLogin {
    color: #666;
    font-size: 14px;
  }
}

// 公共输入框样式
.login-center-form {
  width: 440px;
  height: auto;
  opacity: 1;
  background: #fff;
  border-radius: 4px;
  padding: 40px 62px 31px 62px;
  box-shadow: 0 12px 11px 0 rgba(0, 0, 0, 0.1), 0 -8px 11px 0 rgba(0, 0, 0, 0.1);
  .login-center-box {
    // background-color: red;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 36px;
    .login-center-top-devider {
      background-color: #e0e0e0;
      width: 1px;
      height: 24px;
      margin-left: 15px;
    }
    // 登录标题
    .login-center-title {
      margin-left: 15px;
      height: 30px;
      opacity: 1;
      font-size: 20px;
      font-family: PingFangSC, sans-serif;
      font-weight: 600;
      // text-align: center;
      color: #4a556b;
      line-height: 30px;
      // background-color: yellow;
      margin-bottom: 0px;
    }
  }

  // 登录输入框
  .login-center-content {
    .ant-form-item {
      margin: 0;

      .ant-form-item-label {
        label {
          opacity: 1;
          font-size: 14px;
          font-family: PingFangSC, sans-serif;
          font-weight: 400;
          text-align: left;
          color: #636363;
          line-height: 21px;
        }
      }

      .ant-form-item-control {
        .h-input {
          opacity: 1;
          height: 42px;
          background: #fff;
          border: 1px solid #e1e1e1;
          border-radius: 4px;
          box-shadow: 0 1px 2px 0 rgba(184, 200, 224, 0.22);
        }

        .h-input-password {
          opacity: 1;
          height: 42px;
          background: #fff;
          border: 1px solid #e1e1e1;
          border-radius: 4px;
          box-shadow: 0 1px 2px 0 rgba(184, 200, 224, 0.22);
        }

        .ant-select-selector {
          opacity: 1;
          height: 42px;
          background: #fff;
          border: 1px solid #e1e1e1;
          border-radius: 4px;
          box-shadow: 0 1px 2px 0 rgba(184, 200, 224, 0.22);
          .ant-select-selection-item {
            line-height: 42px;
          }
          .ant-select-selection-placeholder {
            line-height: 42px;
          }
        }
      }
    }
    // 验证码
    .login-center-code {
      position: relative;
      overflow: hidden;
      width: 100%;

      .code-input-box {
        width: calc(100% - 124px);
        margin-right: 20px;
        float: left;
      }

      .code-img-box {
        float: left;

        #code-image {
          width: 100%;
          cursor: pointer;

          .ant-image {
            line-height: 42px;

            .ant-image-img {
              width: 100%;
              height: 100%;
            }
          }
        }
      }
    }
    //   登录按钮
    #loginButton {
      height: 42px;
      opacity: 1;
      background: #2c87ff;
      border-radius: 4px;
      margin: 20px 0 15px 0;
      box-shadow: 0 6px 12px 0 rgba(63, 140, 255, 0.26);
      font-size: 16px;
      font-family: PingFangSC, sans-serif;
      font-weight: 500;
      color: #fff;
    }
    // 登录方式设置
    .login-way-setting {
      display: flex;
      justify-content: space-between;

      span {
        font-size: 12px;
        font-family: PingFangSC, sans-serif;
        font-weight: 400;
        color: #666666;
      }

      .forget-password {
        cursor: pointer;
        font-size: 12px;
        font-family: PingFangSC, sans-serif;
        font-weight: 400;
        color: #666666;
      }
    }

    // 三方登录
    .three-part-login {
      #three-part-login-title {
        cursor: default;
        margin: 28px 0 20px 0;
        font-size: 14px;
        font-family: PingFangSC, sans-serif;
        font-weight: 400;
        color: #636363;
      }

      .three-part-mode {
        text-align: center;

        .three-login-type {
          cursor: pointer;
          margin: 0 17.5px;
        }
      }
    }
  }
}

.login-top-logo {
  width: 18px;
  height: 26px;
}
</style>
