<template>
  <view class="login_home">
    <nut-row>
      <nut-col :span="24" class="login_tiitle">
        <div class="title">你好，</div>
        <div class="title">欢迎登录鱼测云</div>
      </nut-col>

      <nut-popup
        v-model:visible="show"
        position="bottom"
        :closeable="false"
        :overlay="false"
        round
        :style="{ height: '83%' }"
      >
        <nut-col :span="24">
          <nut-config-provider :theme-vars="themeVars">
            <view :style="{ padding: '0 16px', marginTop: '20px' }">
              <nut-button
                block
                type="primary"
                size="large"
                open-type="getPhoneNumber"
                @getphonenumber="wxLogin"
                :loading="isLoading"
                v-if="loginForm.agreement"
                >手机号一键登录</nut-button
              >
              <nut-button block size="large" type="primary" v-else @click="wxLoginCheck"
                >手机号一键登录</nut-button
              >
              <nut-divider> OR </nut-divider>
              <nut-button
                block
                type="primary"
                size="large"
                :style="{
                  fontWeight: 'bold',
                  fontSize: '14px !important',
                  color: '#09B8C2 !important',
                }"
                color="#E7F8F9"
                @click="login"
                >其它手机号登录</nut-button
              >
              <!-- 底部协议 -->
              <view class="container agrBottom">
                <view>
                  <nut-checkbox v-model="loginForm.agreement" />
                </view>
                <view class="font_28 c_888 view_f"
                  >我已阅读<view :style="{ color: '#09B8C2' }" @click="toAgreement()"
                    >用户使用协议</view
                  >和<view :style="{ color: '#09B8C2' }" @click="toPriAgreement()"
                    >隐私政策</view
                  >并理解相关条款内容</view
                >
              </view>
            </view>
          </nut-config-provider>
        </nut-col>

        <nut-col
          :span="24"
          @click="unlogin"
          class="agrBottom2"
          :style="{
            fontWeight: 'bold',
            fontSize: '14px !important',
            color: '#09B8C2 !important',
            marginTop: '10rpx',
            textAlign: 'center',
          }"
        >
          暂不登录
        </nut-col>
      </nut-popup>
      <!-- 弹出层提示 -->
      <nut-toast :msg="state.msg" v-model:visible="state.show" :type="state.type" />
    </nut-row>
  </view>
</template>
<script setup lang="ts" name="Login">
import { loginFormType } from "./types";
import { stateType } from "@/utils/types";
import { loginWxToPhone } from "@/api/login";
import Taro from "@tarojs/taro";
// 已阅读参数
const instance = Taro.getCurrentInstance();
const store: any = inject("store");
const agreement = instance.router.params.agreement;
const show = ref(true);
const loginForm: loginFormType = reactive({
  phonenumber: "",
  code: "",
  identity: false,
  agreement: agreement ? true : false,
});
const themeVars = ref({
  formItemLabelFontSize: "15px",
  cellBorderRadius: "0px",
  cellBoxShadow: "0px",
  checkboxLabelMarginLeft: "0px",
  checkboxMarginRight: "2px",
});
const state: stateType = reactive({
  msg: "",
  type: "text",
  center: true,
  show: false,
});
const isLoading = ref(false);
/** -----------------method start----------------- */
Taro.useDidShow(() => {
  if(agreement){
    loginForm.agreement = true
  }else{
    loginForm.agreement = false
  }
  Taro.setStorageSync("UnLogin", 1);
  store.updateUnLogin(1);
})
/** 手机号码登录 */
function login() {
  if (!loginForm.agreement) {
    state.msg = "请阅读用户协议";
    state.show = true;
    return;
  }
  // 跳转手机号登录
  Taro.navigateTo({ url: "/pages/login/loginPhone" });
}
function wxLoginCheck() {
  if (!loginForm.agreement) {
    state.msg = "请阅读用户协议";
    state.show = true;
    return;
  }
}
/** 微信登录 */
function wxLogin(e) {
  isLoading.value = true;
  console.log('获取手机号返回：', e.detail);
  
  // 用户拒绝授权
  if (!e.detail.code) {
    state.msg = "获取手机号失败，请允许授权";
    state.show = true;
    isLoading.value = false;
    return;
  }
  
  if (e.detail.code) {
    Taro.login({
      success: function (res) {
        console.log('微信登录返回：', res);
        if (res.code) {
          const params = { code: e.detail.code, js_code: res.code };
          console.log('调用登录接口参数：', params);
          
          loginWxToPhone(params)
            .then((res) => {
              console.log('登录接口返回：', res);
              if (res.statusCode == 200) {
                Taro.setStorageSync(
                  "ReTime",
                  res.data.createdTime
                    ? formatDate(new Date(res.data.createdTime))
                    : formatDate(new Date())
                );
                Taro.setStorageSync("UnLogin", 2);
                Taro.setStorageSync("UserName", res.data.userName);
                Taro.setStorageSync("Phone", res.data.mobilePhone);
                Taro.setStorageSync("UserId", res.data.id);
                store.updateRootUserId(res.data.id);
                store.updateUserId(res.data.id);
                store.updateUnLogin(2);
                store.updateRootUserName(res.data.userName);
                store.updateLoginStatus(0);
                state.msg = "登录成功";
                state.show = true;
                Taro.switchTab({
                  url: "/pages/main/home",
                });
                return;
              } else {
                state.msg = `登录失败：${res.data?.msg || '服务器返回异常'}`;
                state.show = true;
              }
            })
            .catch((err) => {
              console.error('登录接口错误：', err);
              state.msg = `登录失败：${err.data?.msg || err.errMsg || '网络错误'}`;
              state.show = true;
            })
            .finally(() => {
              isLoading.value = false;
            });
        } else {
          state.msg = "微信登录失败，请重试";
          state.show = true;
          isLoading.value = false;
        }
      },
      fail: function (err) {
        console.error('微信登录失败：', err);
        state.msg = `微信登录失败：${err.errMsg || '未知错误'}`;
        state.show = true;
        isLoading.value = false;
      },
    });
  }
}
/** 查看用户协议 */
function toAgreement() {
  Taro.redirectTo({
    url: "/agreement/index?phonenumber=" + loginForm.phonenumber + "&pages=login",
  });
}
/** 隐私协议 */
function toPriAgreement() {
  Taro.redirectTo({
    url: "/agreement/indexpri?phonenumber=" + loginForm.phonenumber + "&pages=login",
  });
}
Taro.useDidShow(() => {
  if (!Taro.getStorageSync("Access-Token")) {
    Taro.clearStorageSync();
  } else {
    Taro.switchTab({
      url: "/pages/main/home",
    });
  }
});
/** 暂不登录 */
function unlogin() {
  Taro.setStorageSync("UnLogin", 1);
  store.updateUnLogin(1);
  Taro.switchTab({
    url: "/pages/main/home",
  });
}
/** -----------------method end------------------- */
</script>
<style lang="scss">
.login_home {
  height: 100%;
  width: 100%;
  background-size: 100% 100%;
  position: fixed;
  margin: 0;
  background: linear-gradient(90deg, #74dce2 0%, #ddf7f2 100%);

  font-size: 32px;
  font-family: "PingFang SC";
  font-weight: 400;

  .login_tiitle {
    padding: 20px !important;

    .title {
      font-size: 46px;
      color: #000;
      font-family: "PingFang SC";
      font-weight: 800;
    }
  }

  .itemLabel {
    color: #000;
    font-family: "PingFang SC";
    font-weight: 400;
  }

  .code {
    color: #09b8c2;
  }

  .disabled {
    color: #ccc;
  }

  .container {
    display: flex;
  }

  .agrBottom {
    position: fixed;
    bottom: 50%;
    left: 2%;
  }
  .agrBottom2 {
    position: fixed;
    bottom: 45%;
  }
}
</style>
