<template>
  <CommonRoot>
    <FlexCol>
      <StatusBarSpace />
      <NavBar v-if="!AppCofig.requireLogin" title="登录" leftButton="back" />

      <FlexCol center>
        <Height :size="200" />
        <Image
          :width="200"
          :src="baseLogo" 
          mode="widthFix"
        />
        <Height :size="60" />
        <Text bold :fontSize="40">您好！欢迎使用村社文化资源挖掘平台</Text>
        <Height :size="60" />
      </FlexCol>

      <FlexCol center v-if="type == 'mobile'" :padding="40">
        <Form 
          :model="loginFormModel"
          :rules="loginFormRules"
          labelWidth="140rpx"
          :fieldProps="{
            fieldStyle: fieldStyle,
          }"
        >
          <Field
            label="用户名"
            name="mobile"
            type="text"
            placeholder="请输入用户名"
          />
          <Field
            label="密码"
            type="password"
            name="password"
            placeholder="请输入密码(6-16位)"
          />
          <Field
            label="角色"
            name="loginType"
            required
            :fieldStyle="{ 
              ...fieldStyle,
              backgroundColor: 'transparent' 
            }"
          >
            <FlexRow align="center">
              <RadioGroup>
                <Radio :name="0" text="志愿者" />
                <Radio :name="1" text="管理员" />
              </RadioGroup>
            </FlexRow>
          </Field>
        </Form>

        <Height :size="25" />
        <Button type="primary" block size="large" text="登录" @click="loginMobile" />
        <Height :size="20" />
        <Button type="text" block text="返回" @click="type='wechat'" />
      </FlexCol>

      <FlexCol center v-if="type == 'wechat'" :padding="40">
        <!-- #ifdef MP-WEIXIN -->
        <Button type="primary" block size="large" text="微信登录" icon="wechat-white" :iconProps="{color: 'white'}" @click="loginWechat" />
        <Height :size="20" />
        <!-- #endif -->
        <Button type="default" block size="large" text="用户名密码登录" @click="type='mobile'" />

        <FlexRow v-if="isTestEnv" position="absolute" :left="10" :bottom="10">
          <CheckBox v-model="isTestCode" />
        </FlexRow>
      </FlexCol>
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { useTheme } from '@/components/theme/ThemeDefine';
import { useAuthStore } from '@/store/auth';
import { useAppInit } from '@/common/composeabe/AppInit';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import { onMounted, ref } from 'vue';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { alert, closeToast, confirm, toast } from '@/components/dialog/CommonRoot';
import { checkAndGoBindVolunteer } from '../dig/forms/bind';
import { back } from '@/components/utils/PageAction';
import AppCofig, { isTestEnv } from '@/common/config/AppCofig';
import type { Rules } from 'async-validator';
import FlexCol from '@/components/layout/FlexCol.vue';
import Form from '@/components/form/Form.vue';
import Field from '@/components/form/Field.vue';
import RadioGroup from '@/components/form/RadioGroup.vue';
import Radio from '@/components/form/Radio.vue';
import Button from '@/components/basic/Button.vue';
import Height from '@/components/layout/space/Height.vue';
import baseLogo from '/static/logo.png';
import FlexRow from '@/components/layout/FlexRow.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import StatusBarSpace from '@/components/layout/space/StatusBarSpace.vue';
import Image from '@/components/basic/Image.vue';
import Text from '@/components/basic/Text.vue';
import CheckBox from '@/components/form/CheckBox.vue';
import MemoryTimeOut from '@/common/composeabe/MemoryTimeOut';
import NavBar from '@/components/nav/NavBar.vue';

/**
 * 登录页面
 * 
 * 登录页面，支持微信登录和用户名密码登录
 */

const type = ref('wechat');
const authStore = useAuthStore();
const themeContext = useTheme();
const { init } = useAppInit();

const loginFormModel = ref({
  mobile: '',
  password: '',
  loginType: 0,
});
const loginFormRules : Rules = {
  'mobile': {
    type: 'string',
    required: true,
    message: '请填写用户名',
  },
  'password': {
    type: 'string',
    min: 6,
    max: 16,
    required: true,
    message: '请填写密码(6-16位)',
  },
};
const fieldStyle = themeContext.useThemeStyle({
  backgroundColor: '#ececec',
  paddingVertical: '30rpx',
  paddingHorizontal: '25rpx',
  borderRadius: '20rpx',
  marginBottom: '20rpx',
});

const isTestCode = ref(false);
const tipBindWechat = new MemoryTimeOut('TipBindWechat', 1000 * 3600 * 72);

async function loginWechat() {

  toast({
    type: 'loading',  
    content: '登录中...',
  })

  try {
    const res = await Promise.all([
      uni.login({ provider: 'weixin' }),
      uni.getUserProfile({ desc: '用于完善会员资料' }),
    ])

    //测试code功能
    if (isTestCode.value) {
      uni.setClipboardData({
        data: res[0].code,
      });
      alert({
        title: '测试登录',
        content: '已复制登录信息到剪贴板\n' + JSON.stringify(res),
      });
      return;
    }

    //登录微信
    await authStore.loginWechart(res[0].code, res[1]);
    toast({  type: 'success',content: '登录成功' });
    await loginAfter();
  } catch(e) {
    showError(e);
  } finally {
    closeToast();
  }
}
async function loginMobile() {
  toast({
    type: 'loading',  
    content: '登录中...',
  })

  try {
    await authStore.loginMobile(
      loginFormModel.value.mobile, 
      loginFormModel.value.password,
      loginFormModel.value.loginType,
    );
    toast({ type: 'success',content: '登录成功' });
    await loginAfter(true);

  } catch (e) { 
    closeToast()
    showError(e); 
  }
}
async function loginAfter(isMobileLogin = false) {
  await waitTimeOut(200);

  //检查是否有志愿者信息，跳转至不同的页面
  //已认领志愿者，跳转至首页
  //未认领志愿者，跳转至绑定账号页面
  if (await checkAndGoBindVolunteer())
    return;

  //刷新用户信息
  await init();

  //如果用户未绑定微信，提示用户绑定微信
  if (isMobileLogin && !authStore.userInfo?.openId && tipBindWechat.isTimeout()) {
    tipBindWechat.recordTime();

    if (await confirm({
      title: '提示',
      content: '绑定微信账号后登录更方便，是否前往绑定？',
      confirmText: '前往绑定',
      cancelText: '稍后绑定',
      width: 580,
    })) {
      uni.redirectTo({ url: '/pages/dig/sharereg/bind-wx?fromLogin=true' });
      return;
    }
  }
  redirectToIndex();
}
function redirectToIndex() {
  if (AppCofig.requireLogin)
    uni.redirectTo({ url: '/pages/index' });
  else
    back();
}

onMounted(() => {
  toast({
    type: 'loading',  
    content: '请稍后...',
  });
  setTimeout(() => {
    closeToast();
    if (authStore.isLogged) 
      loginAfter();
  }, 800);
})

</script>