<template>
  <div
    id="c-login-page"
    :style="{ 'background-image': 'url(' + props.backImg + ')' }"
  >
    <div class="loginPage">
      <!-- <img :src="logo" class="logo" /> -->
      <div id="title">{{ props.title }}</div>
      <c-tabs v-model:activeKey="activeKey">
        <c-tab-pane
          key="first"
          :tab="$cyt('账号密码登录')"
          v-if="props.loginTypes.includes('userPwd')"
        >
          <a-form
            :model="userForm"
            ref="userFormRef"
            :rule="formRules"
            name="basic"
            @finish="handleFinish"
            @finishFailed="handleFinishFailed"
          >
            <a-form-item
              name="username"
              :rules="[{ required: true, message: $cyt('请输入账号') }]"
            >
              <c-input
                v-model:value="userForm.username"
                autocomplete="off"
                :placeholder="placeholder.username"
                class="first-input"
                size="large"
              >
                <template #prefix>
                  <img src="@/CLoginPage/src/user.png" />
                </template>
              </c-input>
            </a-form-item>
            <a-form-item
              name="password"
              :rules="[{ required: true, message: $cyt('请输入密码') }]"
            >
              <c-input-password
                v-model:value="userForm.password"
                autocomplete="off"
                :placeholder="placeholder.password"
                size="large"
              >
                <template #prefix>
                  <img src="@/CLoginPage/src/lock.png" />
                </template>
              </c-input-password>
            </a-form-item>

            <div
              class="verification"
              v-if="props.setCaptcha && props.getCaptchaUrl"
            >
              <a-form-item
                name="verificationCode"
                :rules="[{ required: true, message: $cyt('请输入验证码') }]"
              >
                <c-input
                  v-model:value="userForm.verificationCode"
                  placeholder="请输入验证码"
                  autocomplete="off"
                  class="verification-ipt"
                  size="large"
                ></c-input>
              </a-form-item>
              <div class="verificationCode" @click="changeCaptchaImg">
                <img :src="base64Img" />
              </div>
            </div>

            <div class="register-forgetPwd">
              <span @click="register">{{ $cyt("注册账号") }}</span>
              <span @click="forgetPwd" v-if="props.isShowForgetPwd"
                >忘记密码</span
              >
            </div>
            <c-button
              type="primary"
              html-type="submit"
              :style="{
                'margin-bottom':
                  props.thirdLoginTypes && props.thirdLoginTypes.length
                    ? 0
                    : '40px',
              }"
              >{{ $cyt("登录") }}</c-button
            >
            <div
              class="thirdLogin"
              v-if="props.thirdLoginTypes && props.thirdLoginTypes.length > 0"
            >
              {{ $cyt("其他登录方式") }}
              <img
                src="@/CLoginPage/src/weixin.png"
                v-if="props.thirdLoginTypes?.includes('weixin')"
              />
              <img
                src="@/CLoginPage/src/dingding.png"
                v-if="props.thirdLoginTypes?.includes('dingding')"
              />
              <img
                src="@/CLoginPage/src/weibo.png"
                v-if="props.thirdLoginTypes?.includes('weibo')"
              />
            </div>
          </a-form>
        </c-tab-pane>
        <c-tab-pane
          key="second"
          :tab="$cyt('手机号登录')"
          v-if="props.loginTypes.includes('phone')"
        >
          <a-form
            :model="PhoneForm"
            name="basic"
            :rules="phoneRules"
            ref="phoneFormRef"
            @finish="handlePhoneFinish"
            @finishFailed="handleFinishFailed"
          >
            <a-form-item name="phone">
              <c-input
                v-model:value="PhoneForm.phone"
                placeholder="请输入手机号"
                autocomplete="off"
                class="first-input"
                size="large"
              >
                <template #prefix>
                  <img src="@/CLoginPage/src/mobile.png" />
                </template>
              </c-input>
            </a-form-item>

            <div
              class="verification"
              v-if="props.setCaptcha && props.getCaptchaUrl"
            >
              <a-form-item
                name="verificationCode"
                :rules="[{ required: true, message: $cyt('请输入验证码') }]"
              >
                <c-input
                  v-model:value="PhoneForm.verificationCode"
                  placeholder="请输入验证码"
                  autocomplete="off"
                  class="verification-ipt"
                  size="large"
                ></c-input>
              </a-form-item>

              <div class="phoneCode" @click="changeCaptchaPhone">
                <c-button :disabled="state.disabled">
                  {{
                    state.disabled
                      ? $cyt("已发送", state.count)
                      : $cyt("获取验证码")
                  }}
                </c-button>
              </div>
            </div>

            <div class="register-forgetPwd">
              <span @click="register">{{ $cyt("注册账号") }}</span>
              <!-- <span @click="forgetPwd">忘记密码</span> -->
            </div>
            <c-button
              type="primary"
              :style="{
                'margin-bottom':
                  props.thirdLoginTypes && props.thirdLoginTypes.length
                    ? 0
                    : '40px',
              }"
              html-type="submit"
              >{{ $cyt("登录") }}</c-button
            >
            <div
              class="thirdLogin"
              v-if="props.thirdLoginTypes && props.thirdLoginTypes.length > 0"
            >
              {{ $cyt("其他登录方式") }}
              <img
                src="@/CLoginPage/src/weixin.png"
                v-if="props.thirdLoginTypes?.includes('weixin')"
              />
              <img
                src="@/CLoginPage/src/dingding.png"
                v-if="props.thirdLoginTypes?.includes('dingding')"
              />
              <img
                src="@/CLoginPage/src/weibo.png"
                v-if="props.thirdLoginTypes?.includes('weibo')"
              />
            </div>
          </a-form>
        </c-tab-pane>
        <!-- <a-tab-pane key="3" tab="Tab 3">Content of Tab Pane 3</a-tab-pane> -->
      </c-tabs>
    </div>

    <div class="bottom" v-if="props.bottomContent">
      {{ props.bottomContent }}
    </div>
  </div>
</template>
<script lang="ts" setup>
// import logo1 from "@/CLoginPage/src/logo.png";
import axios from "axios";
import { ref, reactive, computed, onMounted } from "vue";
import prop from "../prop";
import type { RuleObject } from "ant-design-vue/es/form";
import { message } from "ant-design-vue";
import { cloneDeep } from "lodash";
import { getMd5, encryptForAes } from "../../Utils/encrypt";
import { createLocale } from "~/Utils/index";
interface FormState {
  username: string;
  password: string;
  verificationKey?: string;
  verificationCode: string;
}
interface phoneForm {
  phone: string;
  verificationKey?: string;
  verificationCode: string;
}
const $cyt = createLocale();
const props = defineProps(prop);
/* 验证成功 验证码图片 手机验证码 忘记密码 注册  */
const emit = defineEmits([
  "successSubmit",
  "changeCaptchaImg",
  "changeCaptchaPhone",
  "register",
  "forgetPwd",
]);
const base64Img = ref<string>();
// const errorMessage = ref<string>()
// const errorVisible = ref<boolean>(false);
// const logo = computed(() => (props.logo == "" ? logo1 : props.logo));
const activeKey = ref("first");
const userFormRef = ref();
const phoneFormRef = ref();
const userForm = reactive({
  username: "admin",
  password: "admin147",
  verificationKey: "",
  verificationCode: "sfA&*!~-",
});
const PhoneForm = reactive<phoneForm>({
  phone: "",
  verificationCode: "",
});

//倒计时
const state = reactive({
  count: 60,
  disabled: false,
});
const countdownHandler = function () {
  // state.count = number
  var countdown = function () {
    if (state.count == 0) {
      state.disabled = false;
      state.count = 60;
      localStorage.removeItem("remainderTime");
      return;
    } else {
      state.disabled = true;
      state.count--;
    }
    setTimeout(countdown, 1000);
  };
  setTimeout(countdown, 1000);
};
window.onbeforeunload = () => {
  //刷新的时候就把剩余倒计时的秒数保存到本地存储中，名字叫remainderTime
  if (state.count != 60 && state.count != 0) {
    localStorage.setItem("remainderTime", state.count + "");
  }
};
if (localStorage.getItem("remainderTime")) {
  console.log(localStorage.getItem("remainderTime"));
  state.count = Number(localStorage.getItem("remainderTime"));
  state.disabled = true;
  countdownHandler();
}

// Make a request for a user with a given ID
const changeImg = () => {
  axios
    .post(
      props.getCaptchaUrl,
      {
        type: "CAPTCHA",
        content: "c",
      },
      {
        headers: { "Access-Control-Expose-Headers": "*" },
      }
    )
    .then(function (response) {
      const {
        data: { uniqueId, base64 },
      } = response.data;
      userForm.verificationKey = uniqueId;
      base64Img.value = base64;
      //判断返回数据是否有一层data包裹
      // if (data.hasOwnProperty("verificationCode")) {
      //   base64Img.value = data.base64Img;
      //   if (data.verificationKey)
      //     userForm.verificationKey = data.verificationKey;
      // } else {
      //   base64Img.value = data.data.base64Img;
      //   if (data.data.verificationKey)
      //     userForm.verificationKey = data.data.verificationKey;
      // }
    })
    .catch(function (error) {
      // handle error
      message.error($cyt("验证码获取失败") as any);
    })
    .then(function () {
      // always executed
    });
};
changeImg();
let clientHeight = document.body.clientHeight + "px";
let curHeight = ref(clientHeight);
window.onresize = function () {
  clientHeight = document.body.clientHeight + "px";
  curHeight.value = clientHeight;
};
const validatePhone = async (_rule: RuleObject, value: string) => {
  var reg =
    /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/;
  if (PhoneForm.phone == "" || PhoneForm.phone == undefined) {
    return Promise.reject($cyt("请输入手机号码"));
  } else if (!reg.test(PhoneForm.phone)) {
    console.log(PhoneForm.phone);
    return Promise.reject($cyt("手机号码格式不正确"));
  } else {
  }
};
const validatePass = async (_rule: RuleObject, value: string) => {
  if (
    userForm.password.length < 5 ||
    userForm.password == undefined ||
    userForm.password == ""
  ) {
    return Promise.reject($cyt("密码不能小于5位"));
  }
};
const formRules = {
  // password: [{ required: true, validator: validatePass, trigger: 'change' }],
  // username: [{ required: true, message: '请输入用户名!' }],
  // verificationCode: [{ required: true, message: '请输入验证码' }],
};
const phoneRules = {
  phone: [{ required: true, validator: validatePhone, trigger: "change" }],
  verificationCode: [{ required: true, message: $cyt("请输入验证码") }],
};
//点击图片改变图片验证码
const changeCaptchaImg = () => {
  changeImg();
  emit("changeCaptchaImg");
};
//获取手机验证码
const changeCaptchaPhone = async () => {
  try {
    await phoneFormRef.value.validateFields("phone");
    countdownHandler();
    message.info($cyt("短信验证码已发送") as any);
    state.disabled = true;
    // emit('changeCaptchaPhone');
    if (!props.phoneCodeUrl) {
      emit("changeCaptchaPhone", PhoneForm);
    } else {
      axios
        .post(props.phoneCodeUrl, { phone: PhoneForm.phone })
        .then(function (response) {
          emit("changeCaptchaPhone", {
            res: response.data,
            arguments: PhoneForm,
          });
          console.log(response.data);
        })
        .catch(function (error) {
          // handle error
          console.log(error.response.data.resultMessage);
          message.error(error.response.data.resultMessage);
        })
        .then(function () {
          // always executed
        });
    }
  } catch (errorInfo) {
    console.log("Failed:", errorInfo);
  }
};

//注册
const register = () => {
  emit("register");
};
//忘记密码
const forgetPwd = () => {
  emit("forgetPwd");
};

//手机验证码登录
const handlePhoneFinish = (values: any) => {
  let phoneForms = cloneDeep(PhoneForm);
  console.log("Success:", PhoneForm);
  //有传登录接口就调用，没有直接返回
  if (!props.phoneLoginUrl) {
    emit("successSubmit", phoneForms);
  } else {
    axios
      .post(props.phoneLoginUrl, phoneForms)
      .then(function (response) {
        emit("successSubmit", { res: response.data, arguments: phoneForms });
        console.log(response.data);
      })
      .catch(function (error) {
        // handle error
        console.log(error.response.data.resultMessage);
        message.error(error.response.data.resultMessage);
      })
      .then(function () {
        // always executed
      });
  }
};

const getEncryptedPw = (password: string) => {
  console.debug(props.encryptType);
  if (props.encryptType == "md5") {
    return getMd5(password);
  } else if (props.encryptType == "aes") {
    if (!props.originKey) {
      throw new Error(" no originKey  provider");
    }
    return encryptForAes(password, props.originKey);
  } else {
    //none
    return password;
  }
};
//账号密码登录
const handleFinish = (values: any) => {
  let userForms = cloneDeep(userForm);
  if (userForms.password) {
    userForms.password = getEncryptedPw(userForms.password);
  }
  console.log("Success:", userForms);
  //有传登录接口就调用，没有直接返回
  if (!props.userLoginUrl) {
    emit("successSubmit", userForms);
  } else {
    axios
      .post(props.userLoginUrl, userForms)
      .then(function (response) {
        emit("successSubmit", { res: response.data, arguments: userForms });
        console.log(response.data);
      })
      .catch(function (error) {
        // handle error
        console.log(error.response.data.resultMessage);
        message.error(error.response.data.resultMessage);
      })
      .then(function () {
        // always executed
      });
  }
};
//验证失败
const handleFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};

// countdownHandler(60)
</script>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "c-login-page",
});
</script>
<style lang="less" scoped>
#c-login-page {
  width: 100%;
  height: v-bind(curHeight);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.loginPage {
  width: 518px;
  background-color: #ffffff85;
  border-radius: 4px;
  position: absolute;
  top: 50%;
  left: 70%;
  transform: translate(-50%, -50%);
  padding: 80px 70px 52px;
  #title {
    width: 112px;
    height: 28px;
    font-size: 28px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    line-height: 28px;
    margin-bottom: 28px;
  }

  .logo {
    width: 184px;
    height: 49px;
    margin: 0 auto;
    margin-top: 65px;
  }

  .register-forgetPwd {
    display: flex;
    justify-content: space-between;
    color: #0074ff;
    cursor: pointer;
  }
  .verification {
    height: 40px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .verification-ipt {
      width: 218px;
    }
    .verificationCode {
      height: 40px;
      width: 150px;
      border: 1px solid #d2d5e1;

      img {
        padding: 4px;
        width: calc(100% - 2px);
        height: calc(100% - 2px);
      }
    }
    .phoneCode {
      height: 40px;
      width: 150px;

      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #222222;
      .ant-btn {
        width: 100%;
        height: 100%;
      }
    }
  }
  .ant-btn-primary {
    background-color: #0074ff;
    width: 100%;
    height: 40px;
    margin-top: 24px;
  }
  .first-input {
    margin-top: 8px;
  }
  .thirdLogin {
    width: 100%;
    text-align: left;
    color: #999999;
    font-size: 14px;
    margin-top: 20px;
    img {
      width: 22px;
      height: 22px;
      display: inline-block;
      margin-left: 10px;
      cursor: pointer;
    }
  }
}
.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 34px;
  background: #e0e6f585;
  text-align: center;
  color: #678fac;
  line-height: 34px;
  font-family: PingFang SC;
}
</style>
