<template>
  <div class="login">
    <div class="login-panel">
      <div class="form">
        <div class="description">
          <div class="logo">
            <img src="" alt="" />
          </div>
          <div class="tips">
            <div class="title">ICPX Studio3.0</div>
            <div class="info">零开发基础，快速搭建业务模型</div>
          </div>
        </div>
        <form @submit="handleSubmit">
          <div class="error-message" v-if="errorMessage">
            <div class="emailMsg">{{ errorMessage }}</div>
          </div>
          <my-input-item
            v-model="modelRef.username"
            class="input-item-space"
            placeholder="请输入用户名"
          >
            <template #icon>
              <img src="@/assets/user/user.svg" alt="" />
            </template>
          </my-input-item>
          <my-input-item
            v-model="modelRef.password"
            class="input-item-space"
            placeholder="请输入密码"
            maxlength="16"
            :type="modelRef.passwordShow ? 'text' : 'password'"
          >
            <template #icon>
              <div
                class="input-icon__pointer"
                @click="modelRef.passwordShow = !modelRef.passwordShow"
              >
                <img v-if="modelRef.passwordShow" src="@/assets/user/password-hide.svg" alt="" />
                <img v-else src="@/assets/user/password-show.svg" alt="" />
              </div>
            </template>
          </my-input-item>

          <div class="verify-code input-item-space">
            <my-input-item
              title="验证码"
              placeholder="请输入验证码"
              v-model="modelRef.verifyCode"
              maxlength="16"
            >
              <template #icon>
                <img src="@/assets/user/password.svg" alt="" />
              </template>
            </my-input-item>
            <div class="verify-code-img">
              <img width="104" height="42" :src="loginCodeInfo.src" @click="getLoginCodeData" />
            </div>
          </div>

          <div
            class="next-step"
            @click="handleSubmit"
            :class="{ 'next-step__disabled': loginButtonStatus.status }"
          >
            登录
          </div>
          <div class="footer-info">
            <div class="account">
              <span class="span-space">忘记密码？</span>
              <span>|</span>
              <span class="span-space" @click="register">注册</span>
            </div>
            <!--            <div class="outline">
              <div class="outline-icon">
                <img src="@/assets/user/outline.svg" alt="" />
              </div>
              <span class="span-space">脱机操作</span>
            </div>-->
          </div>
          <input class="input-hidden" type="submit" />
        </form>
      </div>
    </div>
    <div class="my-footer">
      <my-footer theme="white"></my-footer>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs, watch } from 'vue';
import { getLoginCode } from '@/api/platform/user/login';
import { notification } from 'ant-design-vue';
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 md5 from 'js-md5';
import { SET_INFO } from '@/store/modules/user/mutations';

import MyInputItem from '@/views/user/component/MyInputItem.vue';
import MyFooter from '@/views/user/component/MyFooter.vue';

export default defineComponent({
  name: 'Login',
  components: { MyFooter, MyInputItem },
  setup() {
    const errorMessage = ref<string>('');
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    const state = reactive({
      loginBtn: false,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,

      time: 60,
      smsSendBtn: false,
    });
    const loginCodeInfo = reactive({
      src: '',
    });
    const orgList = reactive([]);

    const modelRef = reactive({
      username: '',
      password: '',
      passwordShow: false,
      verifyCode: '',
      uuid: '',
    });

    const rulesRef = reactive({
      username: [{ required: true, message: '请输入帐户名或邮箱地址', type: 'string' }],
      password: [
        { required: true, message: '请输入密码', type: 'string', trigger: ['blur', 'change'] },
      ],
      verifyCode: [{ required: true, message: '请输入验证码' }],
    });
    const { validate } = useForm(modelRef, rulesRef);

    const tenantOptions = ref([]);

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

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

    const requestFailed = (err: AxiosError) => {
      state.isLoginError = true;
      notification.error({
        message: '错误',
        description: ((err.response || {}).data || {}).errorMessage || '请求出现错误，请稍后再试',
        duration: 4,
      });
    };
    const loginSuccess = () => {
      store.commit(`user/${SET_INFO}`, {
        username: modelRef.username,
      });
      const query: any = {};
      if (route.query?.checkCode) {
        query.checkCode = route.query?.checkCode;
      }
      if (route.query?.username) {
        query.username = route.query?.username;
      }
      if (route.query?.password) {
        query.password = route.query?.password;
      }
      router.push({
        path: decodeURIComponent((route.query?.redirect as string) || '') || '/',
        query,
      });

      notification.success({
        message: '欢迎',
        description: '欢迎回来 ' + modelRef.username,
      });
      state.isLoginError = false;
    };

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

      const validateNames = ['username', 'password', 'verifyCode'];
      state.loginBtn = true;
      validate(validateNames)
        .then(values => {
          const loginParams = {
            username: modelRef.username,
            password: md5(modelRef.password),
            uuid: modelRef.uuid,
            verifyCode: modelRef.verifyCode,
          };

          store
            .dispatch(`user/${LOGIN}`, loginParams)
            .then(() => {
              loginSuccess();
            })
            .catch(err => {
              // requestFailed(err);
              state.isLoginError = true;
              errorMessage.value = err.msg || '账户或密码错误';
            })
            .finally(() => {
              state.loginBtn = false;
              getLoginCodeData();
            });
        })
        .catch((/*err*/) => {
          // 屏蔽错误处理
          state.loginBtn = false;
        });
    };

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

    const getPopupContainer = () => {
      return document.body;
    };
    // 添加登录按钮校验
    const loginButtonStatus = reactive({
      status: true,
    });
    watch(modelRef, () => {
      if (modelRef.username && modelRef.password && modelRef.verifyCode) {
        loginButtonStatus.status = false;
      } else {
        loginButtonStatus.status = true;
      }
    });

    const register = () => {
      router.push('/user/register');
    };

    return {
      ...toRefs(state),
      modelRef,
      loginCodeInfo,
      tenantOptions,
      orgList,
      handleSubmit,
      okEvent,
      getLoginCodeData,
      getPopupContainer,
      // ++
      loginButtonStatus,
      errorMessage,
      register,
    };
  },
});
</script>

<style lang="less" scoped>
.login {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  display: flex;
  align-items: stretch;
  justify-content: center;
  flex-direction: column;
  background-image: url('@/assets/user/login-bg.jpg');
  background-position: center;
  background-size: cover;
  .login-panel {
    background-color: rgba(1, 50, 155, 0.5);
    .form {
      width: 360px;
      margin: auto;
      position: relative;
      padding: 60px 0;
      .description {
        position: absolute;
        top: 50%;
        transform: translate((-100% - 40px), -50%);
        display: flex;
        align-items: center;
        .logo {
          width: 66px;
          height: 66px;
          img {
            width: 100%;
            display: block;
          }
        }
        .tips {
          margin-left: 20px;
          color: white;
          .title {
            font-size: 36px;
            font-weight: bold;
          }
          .info {
            font-size: 18px;
          }
        }
      }
      .next-step {
        background-color: #01329b;
        padding: 8px 0;
        border-radius: 2px;
        color: white;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
      }
      .next-step__disabled {
        background-color: darkgray;
      }
      .footer-info {
        display: flex;
        align-items: center;
        color: white;
        padding-top: 20px;
        .span-space {
          padding: 8px 6px;
          cursor: pointer;
        }
        .account {
          flex: 1;
        }
        .outline {
          display: flex;
          align-items: center;
          .outline-icon {
            width: 18px;
            height: 18px;
            img {
              display: block;
              width: 100%;
            }
          }
        }
      }
      .verify-code {
        display: flex;
      }
      .verify-code-img {
        margin-left: 20px;
      }
    }
  }
}
.error-message {
  padding: 8px 10px;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  margin-bottom: 20px;
}
.input-item-space {
  margin-bottom: 20px;
}
.input-icon {
  img {
    width: 100%;
    display: block;
  }
}
.input-hidden {
  display: none;
}
.my-footer {
  position: absolute;
  width: 100%;
  bottom: 0;
  left: 0;
}
</style>
