<template>
  <CommonRoot>
    <view class="p-3">
      <FlexCol center v-if="type == 'mobile'">
        <image class="width-300 m-5" :src="baseLogo" mode="widthFix"></image>
        <Form 
          :model="loginFormModel"
          :rules="loginFormRules"
          labelWidth="140rpx"
        >
          <Field
            label="用户名"
            name="mobile"
            type="text"
            placeholder="请输入用户名"
          />
          <Field
            label="密码"
            type="password"
            name="password"
            placeholder="请输入密码(6-16位)"
          />
          <Field
            label="登录为"
            name="loginType"
          >
            <FlexRow align="center">
              <RadioGroup>
                <Radio :name="0" text="志愿者" />
                <Radio :name="1" text="管理员" />
              </RadioGroup>
            </FlexRow>
          </Field>
        </Form>

        <Height :size="25" />
        <Button type="primary" block text="登录" @click="loginMobile" />
        <Height :size="20" />
        <Button type="default" block text="微信登录" @click="type='wechat'" />
      </FlexCol>

      <FlexCol center v-if="type == 'wechat'">
        <image 
          class="width-300"
          :src="baseLogo" 
          mode="widthFix"
        />
        <view class="mt-3 mb-3">
          <text class="text-align-center">请登录后进入平台继续操作</text>
        </view>
        <!-- #ifdef MP-WEIXIN -->
        <Button type="primary" block text="微信登录" @click="loginWechat" />
        <Height :size="20" />
        <!-- #endif -->
        <Button type="default" block text="用户名密码登录" @click="type='mobile'" />
      </FlexCol>
    </view>
  </CommonRoot>
</template>

<script setup lang="ts">
import baseLogo from '/static/logo.png';
import { useAuthStore } from '@/store/auth';
import { useCollectStore } from '@/store/collect';
import { onMounted, ref } from 'vue';
import { showError } from '@/common/composeabe/ErrorDisplay';
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 type { Rules } from 'async-validator';
import { closeToast, toast } from '@/components/dialog/CommonRoot';
import FlexRow from '@/components/layout/FlexRow.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';

const type = ref('wechat');
const authStore = useAuthStore();
const collectStore = useCollectStore();

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位)',
  },
}

function loginWechat() {

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

  Promise.all([
    uni.login({ provider: 'weixin' }),
    uni.getUserProfile({ desc: '用于完善会员资料' }),
  ])
    .then((res) => {
      console.log(res);
      //return;
      authStore.loginWechart(res[0].code, res[1]).then(() => {
        toast({
          type: 'success',  
          content: '登录成功',
        });
        collectStore.loadCollectableModules();
        setTimeout(() => redirectToIndex(), 200);
      }).catch(showError);
    })
    .catch(showError)
    .finally(() => closeToast());
}
function loginMobile() {
  toast({
    type: 'loading',  
    content: '登录中...',
  })
  authStore.loginMobile(
    loginFormModel.value.mobile, 
    loginFormModel.value.password,
    loginFormModel.value.loginType,
  ).then(() => {
    toast({
      type: 'success',  
      content: '登录成功',
    });
    setTimeout(() => redirectToIndex(), 200);
  }).catch((e) => { 
    closeToast()
    showError(e); 
  })
}
function redirectToIndex() {
  uni.redirectTo({ url: '/pages/index' });
}

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

</script>