<template>
  <div class="main">
    <h-form id="formLogin" layout="vertical" class="user-layout-login">
      <h-tabs centered :active-key="customActiveKey" @change="handleTabClick">
        <h-tab-pane key="tab1" tab="账号密码登录">
          <h-alert
            v-if="isLoginError"
            type="error"
            show-icon
            style="margin-bottom: 24px"
            message="账户或密码错误"
          />
          <h-form-item v-bind="validateInfos.tenant">
            <h-select
              size="large"
              v-model:value="modelRef.tenant"
              placeholder="选择租户"
              style="width: 100%"
              :options="tenantOptions"
            ></h-select>
          </h-form-item>
          <h-form-item v-bind="validateInfos.username">
            <h-input
              size="large"
              v-model:value="modelRef.username"
              placeholder="请输入账号"
              style="width: 100%"
            >
              <template #prefix>
                <user-outlined class="prefixIcon" />
              </template>
            </h-input>
          </h-form-item>

          <h-form-item v-bind="validateInfos.password">
            <h-input-password
              v-model:value="modelRef.password"
              size="large"
              placeholder="请输入密码"
              style="width: 100%"
            >
              <template #prefix>
                <lock-outlined class="prefixIcon" />
              </template>
            </h-input-password>
          </h-form-item>
          <h-row :gutter="16">
            <h-col class="gutter-row" :span="16">
              <h-form-item v-bind="validateInfos.code">
                <h-input
                  v-model:value="modelRef.code"
                  size="large"
                  type="text"
                  placeholder="请输入验证码"
                ></h-input>
              </h-form-item>
            </h-col>
            <h-col class="gutter-row" :span="8">
              <h-image
                :width="104"
                :height="42"
                :preview="false"
                :src="loginCodeInfo.src"
                @click="getLoginCodeData"
              />
            </h-col>
          </h-row>
        </h-tab-pane>

        <h-tab-pane key="tab2" tab="手机号登录">
          <h-form-item v-bind="validateInfos.mobile">
            <h-input v-model:value="modelRef.mobile" size="large" type="text" placeholder="手机号">
              <template #prefix>
                <mobile-outlined class="prefixIcon" />
              </template>
            </h-input>
          </h-form-item>

          <h-row :gutter="16">
            <h-col class="gutter-row" :span="16">
              <h-form-item v-bind="validateInfos.captcha">
                <h-input
                  v-model:value="modelRef.captcha"
                  size="large"
                  type="text"
                  placeholder="验证码"
                >
                  <template #prefix>
                    <mail-outlined class="prefixIcon" />
                  </template>
                </h-input>
              </h-form-item>
            </h-col>
            <h-col class="gutter-row" :span="8">
              <h-button
                class="getCaptcha"
                tabindex="-1"
                :disabled="smsSendBtn"
                @click.stop.prevent="getCaptcha"
              >
                {{ (!smsSendBtn && '获取验证码') || time + ' s' }}
              </h-button>
            </h-col>
          </h-row>
        </h-tab-pane>
      </h-tabs>

      <h-form-item>
        <h-checkbox v-model:cheched="modelRef.rememberMe">自动登录</h-checkbox>
        <router-link to="/user/recover" class="forge-password" style="float: right">
          忘记密码
        </router-link>
      </h-form-item>

      <h-form-item style="margin-top: 24px">
        <h-button
          size="large"
          type="primary"
          html-type="submit"
          class="login-button"
          :loading="loginBtn"
          @click="handleSubmit"
        >
          确定
        </h-button>
      </h-form-item>

      <div class="user-login-other">
        <span>其他登录方式</span>
        <a>
          <alipay-circle-outlined class="item-icon" />
        </a>
        <a>
          <taobao-circle-outlined class="item-icon" />
        </a>
        <a>
          <weibo-circle-outlined class="item-icon" />
        </a>
        <router-link class="register" to="/user/register">注册账户</router-link>
      </div>
    </h-form>
    <h-modal v-model:visible="orgVisible" title="选择组织" centered @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="选择组织"
            style="width: 100%"
            :options="orgList"
          ></h-select>
        </h-form-item>
      </h-form>
    </h-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs } from 'vue';
import { getSmsCaptcha, getTenant, getLoginCode, getLoginOrg } from '@/api/platform/user/login';
import { message, notification } from '@crami/ui';
// import { message, notification } from 'ant-design-vue';
import { useForm } from 'ant-design-vue/es/form';
import {
  UserOutlined,
  LockOutlined,
  MobileOutlined,
  MailOutlined,
  AlipayCircleOutlined,
  TaobaoCircleOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons-vue';
import type { AxiosError } from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { LOGIN } from '@/store/modules/user/actions';
import md5 from 'js-md5';

export default defineComponent({
  name: 'Login',
  setup() {
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    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 loginCodeInfo = reactive({
      key: '',
      image: '',
      src: '',
    });
    const orgList = reactive([]);

    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({
      rememberMe: true,
      username: '',
      password: '',
      mobile: '',
      captcha: '',
      tenant: null,
      code: '',
      orgId: null,
    });
    const rulesRef = reactive({
      rememberMe: undefined,
      username: [
        { required: true, message: '请输入帐户名或邮箱地址', type: 'string' },
        { validator: handleUsernameOrEmail, trigger: 'change' },
      ],
      password: [
        { required: true, message: '请输入密码', type: 'string', trigger: ['blur', 'change'] },
      ],
      mobile: [
        {
          required: true,
          // pattern: /^1[34578]\d{9}$/,
          message: '请输入正确的手机号',
          trigger: ['blur', 'change'],
        },
      ],
      captcha: [{ required: true, message: '请输入验证码' }],
      code: [{ required: true, message: '请输入验证码' }],
      tenant: [{ required: true, message: '请选择租户' }],
      orgId: [{ required: true, message: '请选择组织' }],
    });
    const { validateInfos, validate, resetFields } = useForm(modelRef, rulesRef);

    const tenantOptions = reactive([]);

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

    const getTenantData = () => {
      getTenant()
        .then(res => {
          console.log('eeeee', res);
          const results = res.data.map(item => {
            return { label: item.ename ? item.ename : item.title, value: item.value };
          });
          tenantOptions.push(...results);
        })
        .catch(err => {
          // 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(err => {
          // requestFailed(err);
          loginCodeInfo.src = 'data:image/png;base64,';
        })
        .finally(() => {
          // state.loginBtn = false;
        });
    };

    const getLoginOrgData = () => {
      modelRef.orgId = null;
      getLoginOrg()
        .then(res => {
          console.log('GET_ORG', res);
          const itemList: any[] = res.data || [];
          orgList.length = 0;
          if (itemList.length == 0) {
            localStorage.removeItem('org_data');
            loginSuccess();
          } else if (itemList.length == 1) {
            localStorage.setItem('org_data', itemList[0].value);
            loginSuccess();
          } else {
            orgVisible.value = true;
            orgList.push(
              ...itemList.map(item => {
                return { label: item.title, value: item.value };
              }),
            );
          }
        })
        .catch(err => {
          // requestFailed(err);
        })
        .finally(() => {});
    };

    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: '错误',
        description: ((err.response || {}).data || {}).errorMessage || '请求出现错误，请稍后再试',
      });
    };

    const loginSuccess = () => {
      router.push(decodeURIComponent((route.query?.redirect as string) || '') || '/');
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        notification.success({
          message: '欢迎',
          description: '欢迎回来',
        });
      }, 1000);
      state.isLoginError = false;
    };

    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('验证码发送中..', 0);
          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500);
              notification.success({
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.captcha,
              });
            })
            .catch(err => {
              setTimeout(hide, 1);
              clearInterval(interval);
              state.time = 60;
              state.smsSendBtn = false;
              requestFailed(err);
            });
        })
        .catch(err => {
          console.log('err', err);
        });
    };

    const handleSubmit = (e: Event) => {
      e.preventDefault();
      const validateNames =
        state.customActiveKey === 'tab1'
          ? ['tenant', 'username', 'password', 'code']
          : ['mobile', 'captcha'];
      state.loginBtn = true;
      validate(validateNames)
        .then(values => {
          console.log('values', values);
          const loginParams = { ...values };
          loginParams['uuid'] = loginCodeInfo.key;
          loginParams.password = md5(values.password);
          if (values.tenant) {
            loginParams['username'] = values.username + '@' + values.tenant;
            delete loginParams['tenant'];
          }

          store
            .dispatch(`user/${LOGIN}`, loginParams)
            .then(() => {
              getLoginOrgData();
            })
            .catch(err => {
              requestFailed(err);
            })
            .finally(() => {
              state.loginBtn = false;
              getLoginCodeData();
            });
        })
        .catch((/*err*/) => {
          // 屏蔽错误处理
          // requestFailed(err);
          state.loginBtn = false;
        });
    };
    const okEvent = (e: Event) => {
      e.preventDefault();
      validate(['orgId'])
        .then(values => {
          console.log('values', values);
          orgVisible.value = false;
          localStorage.setItem('org_data', values.orgId);
          loginSuccess();
        })
        .catch((/*err*/) => {
          // 屏蔽错误处理
          requestFailed(err);
        });
    };

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

      handleTabClick,
      handleSubmit,
      getCaptcha,
      okEvent,
      getLoginCodeData,
    };
  },
  components: {
    UserOutlined,
    LockOutlined,
    MobileOutlined,
    MailOutlined,
    AlipayCircleOutlined,
    TaobaoCircleOutlined,
    WeiboCircleOutlined,
  },
});
</script>

<style lang="less" scoped>
.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;
  }
}
.user-layout-login :deep(.ant-tabs) {
  .ant-tabs-nav::before {
    border-bottom: none;
  }
}
</style>
