<template>
  <view class="p-3">
    <view class="d-flex flex-column align-center justify-center gap-sss">
      <image class="width-300 m-5" src="https://mncdn.wenlvti.net/app_static/minnan/logo.png" mode="widthFix"></image>
      <view class="mt-3 mb-3">
        <text class="text-align-center">请点击微信登录，并授权获取公开信息， 登录后您将获得更多权益</text>
      </view>
      <Button type="primary" block @click="loginWechat(false)">
        微信登录
      </Button>
      <Button v-if="isTestEnv" block @click="loginWechat(true)">
        微信登录(测试)
      </Button>
      <Button block @click="back">
        返回
      </Button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { useAuthStore } from '@/store/auth';
import { onLoad } from '@dcloudio/uni-app';
import { back } from '@/components/utils/PageAction';
import { toast } from '@/components/utils/DialogAction';
import { showError } from '@/common/composeabe/ErrorDisplay';
import Button from '@/components/basic/Button.vue';
import Height from '@/components/layout/space/Height.vue';
import { isTestEnv } from '@/common/config/AppCofig';

const authStore = useAuthStore();

function loginWechat(debug = false) {
  uni.showLoading({ title: '登录中...' });
  Promise.all([
    uni.login({ provider: 'weixin' }),
    uni.getUserProfile({ desc: '用于完善会员资料' }),
  ])
    .then((res) => {
      if (debug) {
        uni.hideLoading();
        const result = 'code: ' + res[0].code + '\nrawData: ' + res[1].rawData + '\nencryptedData: ' + res[1].encryptedData + '\niv: ' + res[1].iv + '\nsignature: ' + res[1].signature;
        uni.showModal({
          title: '测试登录',
          content: '点击确定可复制 code: ' + res[0].code,
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              uni.setClipboardData({
                data: result,
                success: () => {
                  uni.showToast({
                    title: '已复制',
                  })
                }
              })
            }
          },
        });
        return;
      }
      //return;
      authStore.loginWechart(res[0].code, res[1]).then(() => {
        toast('登录成功');
        setTimeout(back, 200);
      }).catch(showError);
    })
    .catch(showError)
    .finally(() => uni.hideLoading());
}
onLoad(() => {
  if (authStore.isLogged) {
    setTimeout(() => {
      back();
    }, 200);
  } else {
  }
})

</script>