<template>
  <ie-page bgColor="white">
    <ie-navbar title="" :hide-back="hideBack" :placeholder="false" bgColor="transparent" />
    <ie-image :is-oss="true" src="/login-bg.png" custom-class="w-full min-h-350 absolute top-0 left-0 z-1" />
    <ie-image :is-oss="true" src="/login-title.png" custom-class="w-full h-96 mx-auto mt-240" mode="heightFix" />
    <view class="relative z-2 mx-46 mt-178">
      <view class="ml-18 flex items-center">
        <view class="text-32" :class="{ 'is-active': loginType === 'card' }" @click="changeLoginType('card')">
          会员卡登录
        </view>
        <view class="w-1 h-30 mx-24 bg-fore-light"></view>
        <view class="text-32" :class="{ 'is-active': loginType === 'phone' }" @click="changeLoginType('phone')">
          手机号登录
        </view>
      </view>
      <view class="mt-46">
        <view v-show="loginType === 'phone'">
          <ie-input custom-class="mt-28" type="number" :maxlength="11" v-model="phone" placeholder="请输入手机号" />
          <ie-input custom-class="mt-28" type="number" :maxlength="6" v-model="password" placeholder="请输入验证码">
            <ie-sms :phone="phone" :sms-api-type="EnumSmsApiType.NO_VALIDATION_NO_TOKEN" @send="handleSendSuccess" />
          </ie-input>
        </view>
        <view v-show="loginType === 'card'">
          <ie-input custom-class="mt-28" type="number" :maxlength="8" v-model="cardNo" placeholder="请输入卡号" />
          <ie-input custom-class="mt-28" type="number" :password="!showPassword" :maxlength="6" v-model="cardPassword"
            placeholder="请输入密码">
            <cover-view class="w-60 h-60 flex items-center justify-center" @click="toggleShowPassword">
              <cover-image v-show="!showPassword" src="@/pagesSystem/static/image/icon/icon-eye.png" mode="widthFix"
                class="w-44 h-44" />
              <cover-image v-show="showPassword" src="@/pagesSystem/static/image/icon/icon-eye-off.png" mode="widthFix"
                class="w-44 h-44" />
            </cover-view>
          </ie-input>
        </view>
        <view class="mt-42 ml-26 h-28">
          <uv-checkbox-group v-if="loginType === 'card'" v-model="rememberPassword">
            <uv-checkbox :name="true" label="记住密码" :labelSize="15" :iconSize="14" labelColor="#666666"></uv-checkbox>
          </uv-checkbox-group>
        </view>
      </view>
      <view class="mt-84">
        <ie-button @click="handleLogin">登录</ie-button>
      </view>
      <view class="mt-42 ml-26">
        <uv-checkbox-group v-model="agreePrivacy">
          <uv-checkbox :name="true" shape="circle" label="记住密码" :labelSize="14" :iconSize="13" labelColor="#666666">
            <text class="text-28 text-fore-subcontent">已阅读并同意<text class="text-primary"
                @click.stop="handleAgreePrivacy('user')">《用户协议》</text>和<text class="text-primary"
                @click.stop="handleAgreePrivacy('privacy')">《隐私政策》</text></text>
          </uv-checkbox>
        </uv-checkbox-group>
      </view>
    </view>
    <ie-captcha ref="captchaRef" v-model:code="code" v-model:uuid="uuid" @valid="handleValid" />
  </ie-page>
</template>

<script lang="ts" setup>
import ieCaptcha from '@/components/ie-sms/ie-captcha.vue';
import { useUserStore } from '@/store/userStore';
import { useTransferPage } from '@/hooks/useTransferPage';
import { validatePhone } from '@/hooks/useValidation';
import { useAppConfig } from '@/hooks/useAppConfig';
import { verifyCard } from '@/api/modules/user';
import { EnumBindScene, EnumSmsApiType, EnumUserType } from '@/common/enum';
import { login } from '@/api/modules/login';
import { LoginRequestDTO, MobileLoginResponseDTO, UserInfo } from '@/types/user';

const { transferBack, transferTo } = useTransferPage();
const userStore = useUserStore();
const { isSmsCaptchaEnable } = useAppConfig();
const hideBack = ref(false);
const loginType = ref('card');
const phone = ref('');
const password = ref('');
const cardNo = ref('');
const cardPassword = ref('');
const code = ref('');
const uuid = ref('');
const showPassword = ref(false);
const rememberPassword = ref([false]);
const agreePrivacy = ref([false]);


const changeLoginType = (type: string) => {
  loginType.value = type;
}

const handleAgreePrivacy = (type: string) => {
  if (type === 'user') {
    transferTo('/pagesOther/pages/h5/h5', {
      data: {
        title: '用户协议',
        url: 'https://www.dz1kt.com/admin/protocol/mxjb_user_IE.html'
      }
    });
  } else if (type === 'privacy') {
    transferTo('/pagesOther/pages/h5/h5', {
      data: {
        title: '隐私政策',
        url: 'https://www.dz1kt.com/admin/protocol/mxjb_privacy_IE.html'
      }
    });
  }
}

const handleSendSuccess = (_phone: string, _code: string, _uuid: string) => {
  console.log('短信发送成功', _phone, _code, _uuid);
  code.value = _code;
  uuid.value = _uuid;
}

const toggleShowPassword = () => {
  showPassword.value = !showPassword.value;
}

const loginValidate = () => {
  if (loginType.value === 'phone') {
    if (!validatePhone(phone.value)) {
      uni.$ie.showToast('请输入正确的手机号');
      return false;
    }
    if (!password.value) {
      uni.$ie.showToast('请输入验证码');
      return false;
    }
  } else if (loginType.value === 'card') {
    if (!cardNo.value || !cardNo.value.trim()) {
      uni.$ie.showToast('请输入卡号');
      return false;
    }
    if (!cardPassword.value || !cardPassword.value.trim()) {
      uni.$ie.showToast('请输入密码');
      return false;
    }
  }
  if (!agreePrivacy.value[0]) {
    uni.$ie.showToast('请先阅读并同意用户协议和隐私政策');
    return false;
  }
  return true;
}

const captchaRef = ref();
const handleLogin = async () => {
  if (!loginValidate()) {
    return;
  }
  if (loginType.value === 'phone') {
    submitLogin();
  } else if (loginType.value === 'card') {
    if (isSmsCaptchaEnable.value) {
      captchaRef.value.open();
    } else {
      submitLogin();
    }
    userStore.rememberLoginInfo(!!rememberPassword.value[0], cardNo.value, cardPassword.value);
    // submitLogin();
  }
}

const submitLogin = async () => {
  const params: LoginRequestDTO = {
    code: code.value,
    uuid: uuid.value
  };
  if (loginType.value === 'phone') {
    params.mobile = phone.value;
    params.password = password.value;
    handleMobileLogin(params);
  } else if (loginType.value === 'card') {
    params.username = cardNo.value;
    params.password = cardPassword.value;
    handleCardLogin(params);
  }
}

const handleMobileLogin = async (params: LoginRequestDTO) => {
  uni.$ie.showLoading();
  login(params).then((res) => {
    uni.$ie.hideLoading();
    if (res.data) {
      const { code, message } = res.data;
      if (code === 101) {
        console.log('registerInfo:', params)
        // 账号不存在，需要注册
        transferTo('/pagesSystem/pages/bind-profile/bind-profile', {
          data: {
            scene: EnumBindScene.REGISTER,
            userInfo: {},
            cardInfo: {},
            registerInfo: {
              ...params
            }
          }
        });
      }
    } else {
      if (res.token) {
        userStore.login(res.token).then(({ success, userInfo }) => {
          if (success) {
            transferBack(true);
          } else {
            uni.$ie.showToast('登录失败')
          }
        });
      }
    }
  }).catch(err => {
    console.log('登录失败', err)
  })
}
const handleCardLogin = (params: LoginRequestDTO) => {
  uni.$ie.showLoading();
  login(params).then(res => {
    if (res.token) {
      userStore.login(res.token).then(({ success, userInfo }) => {
        uni.$ie.hideLoading();
        if (success && userInfo) {
          const needComplete = needCompleteInfo(userInfo);
          if (needComplete) {
            transferTo('/pagesSystem/pages/bind-teacher-profile/bind-teacher-profile');
          } else {
            transferBack(true);
          }
        } else {
          uni.$ie.showToast('登录失败')
        }
      });
    } else if (res.data.code === 101) {
      // 
      verifyCard(cardNo.value, cardPassword.value).then(res => {
        console.log('卡信息：', res)
        uni.$ie.hideLoading();
        if (res.data) {
          console.log('registerInfo:', params)
          transferTo('/pagesSystem/pages/phone-verify/phone-verify', {
            data: {
              scene: EnumBindScene.REGISTER,
              userInfo: {},
              cardInfo: res.data,
              registerInfo: params
            }
          });
        }
      }).catch(err => {
        console.log('验证会员卡失败', err);
      })
    }
  }).catch(err => {
    uni.$ie.hideLoading();
    console.log('登录失败', err)
  });

}

const needCompleteInfo = (userInfo: UserInfo) => {
  const { userType, location, examType, endYear } = userInfo;
  return [EnumUserType.TEACHER, EnumUserType.AGENT].includes(userType) && (!location || !examType || !endYear);
};

const handleValid = (data: { code: string; uuid: string }) => {
  console.log(code.value, uuid.value);
  captchaRef.value.close();
  submitLogin();
}

onShow(() => {
  const pages = getCurrentPages();
  hideBack.value = pages.length <= 1;
});

onLoad(() => {
  rememberPassword.value[0] = userStore.rememberPwd;
  if (import.meta.env.DEV) {
    agreePrivacy.value = [true];
    phone.value = '17363958504';
    password.value = '1234';
  }
  if (userStore.rememberPwd) {
    cardNo.value = userStore.cardNo;
    cardPassword.value = userStore.cardPassword;
  }
});
</script>

<style lang="scss" scoped>
.is-active {
  @apply text-primary font-[800];
}
</style>
