<template>
  <div class="login-wrapper bglogin">
    <up-navbar title="登录" placeholder>
      <template #left>
        <!--        <view-->
        <!--            v-if="appStore?.$wxConfig?.auditModeEnstoreAuditModeEnabledabled"-->
        <!--            @click="backHome"-->
        <!--        >-->
        <!--          <image src="@/static/images/tabbar/1-001.png" style="height: 40rpx;width: 40rpx;"></image>-->
        <!--        </view>-->
        <view
          class="back_extend"
          v-if="appStore?.$wxConfig?.storeAuditModeEnabled"
          @click="backHome"
        >
          {{ "<" }} 回到首页
        </view>
      </template>
    </up-navbar>
    <div class="shading">
      <view class="">Hello！</view>
      <view class="">欢迎来到水贝搬运工</view>
      <image src="@/static/images/login_ip.png" class="ip-pic"></image>
    </div>
    <div class="whiteBg" v-if="formItem === 1">
      <view
        class="whiteBg-tab whiteBg-tabimg"
        :class="{ 'whiteBg-tabs whiteBg-tabsimg': current == 1 }"
      >
        <view
          @click="current = item.type"
          :class="{ active: current != index, noActive: current == index }"
          class="whiteBg-tab-li"
          v-for="(item, index) in navList"
          :key="index"
        >
          <view class="">{{ item.name }}</view>
        </view>
      </view>
      <div class="list">
        <div class="item">
          <input
            type="text"
            maxlength="11"
            class="texts"
            placeholder="输入手机号码"
            v-model="account"
            required
          />
        </div>
        <template v-if="current == 0">
          <div class="item">
            <input
              type="password"
              class="texts"
              placeholder="填写登录密码"
              v-model="password"
              required
            />
          </div>
        </template>
        <template v-else-if="current == 1">
          <div class="item">
            <input
              type="number"
              placeholder="填写验证码"
              class="texts"
              v-model="captcha"
              maxlength="6"
            />
            <button
              class="code"
              :disabled="disabled"
              :class="disabled === true ? 'on' : ''"
              @click="code"
            >
              {{ text }}
            </button>
          </div>
          <div class="item">
            <input
              type="text"
              class="texts"
              placeholder="输入邀请码"
              v-model="inviteCode"
            />
          </div>
        </template>
      </div>
      <div class="privacy-box" @click="aloneChecked = !aloneChecked">
        <image
          v-if="aloneChecked"
          src="/static/images/select-active@2x.png"
          mode=""
        ></image>
        <image v-else src="/static/images/select@2x.png" mode=""></image>
        <view class="">我已阅读并同意</view>
        <view class="privacy-text" @click.stop="openPrivacy">《用户协议》</view>
        <view class="privacy-text" @click.stop="openPrivacy">《隐私政策》</view>
      </div>
      <view class="footer">
        <button class="logon" @click="loginMobile" v-if="current !== 0">
          登录
        </button>
        <!-- <button class="logonWX"  open-type="getPhoneNumber" @getphonenumber="getPhoneNumberFn" v-if="current !== 0">微信登录</button> -->
        <button class="logon" @click="submit" v-if="current === 0">登录</button>
      </view>
      <view class="wx-login" v-if="current !== 0">
        <view class="wx-login-tip">
          <view class="login-line"> </view>
          <text class="wx-tip">第三方登录</text>
          <view class="login-line"> </view>
        </view>
        <view class="wx-login-btn">
          <button
            v-if="aloneChecked"
            class="logonWX"
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumberFn"
          >
            <!-- <image
              class="wx-icon"
              src="@/static/images/wxLogin.png"
              mode="widthFix"
            ></image> -->
            手机号快捷登录
          </button>
          <button v-else class="logonWX" @click="checkPrivacyAgreement">
            <!-- <image
              class="wx-icon"
              src="@/static/images/wxLogin.png"
              mode="widthFix"
            ></image> -->
            手机号快捷登录
          </button>
        </view>
      </view>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useAppStore } from "@/stores/app";
import {
  loginH5,
  loginMobile as loginMobileApi,
  registerVerify,
  register,
  getUserInfo,
  getUserOpenId,
} from "@/api/user";
import { getLogo, appAuth, appleLogin } from "@/api/public";
import { VUE_APP_API_URL } from "@/utils";
import { useSendCode } from "@/hooks/useSendCode";
import Cache from "@/utils/cache";
import { getPhoneNumber } from "@/utils/util.js";
import { useToast } from "@/hooks/useToast.js";
// import {
// 	useGoEasy
// } from "@/plugin/goeasy";
// import {
// 	getGroupchatList
// } from "@/api/customerService";
import { footprintScan } from "@/api/merchant.js";
import { EXPIRES_TIME } from "@/config/cache";
const appStore = useAppStore();
const { Toast } = useToast();
// const {
// 	connect,
// 	GoEasy
// } = useGoEasy();

const BACK_URL = "login_back_url";

// Reactive state
const navList = ref([
  {
    name: "快速登录",
    type: 1,
  },
  {
    name: "账号登录",
    type: 0,
  },
]);
const current = ref(1);
const account = ref("");
const inviteCode = ref(""); // 邀请码
const password = ref("");
const captcha = ref("");
const formItem = ref(1);
const type = ref("login");
const logoUrl = ref("");
const keyCode = ref("");
const codeUrl = ref("");
const codeVal = ref("");

const platform = ref("");

const appleShow = ref(false);
const aloneChecked = ref(false);

const merchantId = ref("");
const userInfo = ref({});

// Watch formItem to update type
watch(formItem, (newVal) => {
  type.value = newVal === 1 ? "login" : "register";
});

const { disabled, text, sendCode } = useSendCode();

function openPrivacy() {
  // void plus.runtime.openWeb("https://www.shuibeibyg.com/shenhe.html");
  goDetail("https://www.shuibeibyg.com/shenhe.html");
}
const goDetail = (url) => {
  const webviewPageUrl = `/pages/webview/privacy?path=${url}`;
  uni.navigateTo({
    url: webviewPageUrl,
    fail: (err) => {
      console.error("跳转到webview页面失败：", err);
      uni.showToast({
        title: "跳转失败，请重试",
        icon: "none",
        duration: 1500,
      });
    },
  });
};

// Get logo image
const getLogoImage = async () => {
  try {
    const res = await getLogo();
    logoUrl.value = res.data.logoUrl || "/static/images/logo2.png";
  } catch (err) {
    console.error(err);
  }
};

// 验证码登录
const loginMobile = async () => {
  if (!account.value)
    return uni.showToast({
      title: "请填写手机号码",
      icon: "none",
    });
  if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(account.value))
    return uni.showToast({
      title: "请输入正确的手机号码",
      icon: "none",
    });
  if (!captcha.value)
    return uni.showToast({
      title: "请填写验证码",
      icon: "none",
    });
  if (!/^[\w\d]+$/i.test(captcha.value))
    return uni.showToast({
      title: "请输入正确的验证码",
      icon: "none",
    });
  if (!aloneChecked.value) {
    return Toast({
      title: "请阅读并同意用户协议和隐私政策",
      icon: "none",
    });
  }
  try {
    const res = await loginMobileApi({
      phone: account.value,
      captcha: captcha.value,
      platformType: "app",
      spread_spid: Cache.get("spread"),
      inviteCode: inviteCode.value,
    });
    // 使用 LOGIN action 保存 token 到缓存
    appStore.LOGIN({
      token: res.data.token,
    });
    // 保存过期时间（999天后过期）
    const expiresTime = Math.round(new Date() / 1000) + 999 * 24 * 60 * 60;
    Cache.set(EXPIRES_TIME, expiresTime, 0);
    await getUserInfoFn(res.data);
  } catch (res) {
    const message = typeof res === "object" ? res.message : res;
    uni.showToast({
      title: message,
      icon: "none",
    });
  }
};

// 注册
const registerFn = async () => {
  if (!account.value)
    return uni.showToast({
      title: "请填写手机号码",
      icon: "none",
    });
  if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(account.value))
    return uni.showToast({
      title: "请输入正确的手机号码",
      icon: "none",
    });
  if (!captcha.value)
    return uni.showToast({
      title: "请填写验证码",
      icon: "none",
    });
  if (!/^[\w\d]+$/i.test(captcha.value))
    return uni.showToast({
      title: "请输入正确的验证码",
      icon: "none",
    });
  if (!password.value)
    return uni.showToast({
      title: "请填写密码",
      icon: "none",
    });
  // 正则1：验证长度6-18位
  const lengthReg = /^.{6,18}$/;
  // 正则2：必须包含至少1个数字（\d）和至少1个字母（a-zA-Z）
  const hasNumAndLetterReg = /(?=.*\d)(?=.*[a-zA-Z])/;
  if (!lengthReg.test(password.value)) {
    return uni.showToast({
      title: "密码长度必须为6-18位",
      icon: "none",
    });
  } else if (!hasNumAndLetterReg.test(password.value)) {
    return uni.showToast({
      title: "密码必须同时包含数字和字母",
      icon: "none",
    });
  }
  try {
    const res = await register({
      account: account.value,
      captcha: captcha.value,
      password: password.value,
      spread: Cache.get("spread"),
    });
    uni.showToast({
      title: res.message,
      icon: "none",
    });
    formItem.value = 1;
  } catch (res) {
    uni.showToast({
      title: res.message,
      icon: "none",
    });
  }
};

// 发送验证码
const code = async () => {
  if (!account.value)
    return uni.showToast({
      title: "请填写手机号码",
      icon: "none",
    });
  if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(account.value))
    return uni.showToast({
      title: "请输入正确的手机号码",
      icon: "none",
    });

  if (formItem.value === 2) type.value = "register";
  try {
    const res = await registerVerify(account.value);
    uni.showToast({
      title: res.message,
      icon: "none",
    });
    sendCode();
  } catch (err) {
    uni.showToast({
      title: err.message,
      icon: "none",
    });
  }
};

// Navigation tab switch
const navTap = (index) => {
  current.value = index;
};

// 账号密码登录
const submit = async () => {
  appStore.setIndexRefersh(true);
  if (!account.value)
    return Toast({
      title: "请填写账号",
      icon: "none",
    });
  if (!/^[\w\d]{5,16}$/i.test(account.value))
    return Toast({
      title: "请输入正确的账号",
      icon: "none",
    });
  if (!password.value)
    return Toast({
      title: "请填写密码",
      icon: "none",
    });
  if (!aloneChecked.value) {
    return Toast({
      title: "请阅读并同意用户协议和隐私政策",
      icon: "none",
    });
  }
  try {
    const { data } = await loginH5({
      account: account.value,
      password: password.value,
      platformType: "app",
      spread: Cache.get("spread"),
    });
    appStore.LOGIN({
      token: data.token,
    });
    // 保存过期时间（999天后过期）
    const expiresTime = Math.round(new Date() / 1000) + 999 * 24 * 60 * 60;
    Cache.set(EXPIRES_TIME, expiresTime, 0);

    await getUserInfoFn(data);
  } catch (err) {
    const message = typeof err === "object" ? err.message : err;
    uni.showToast({
      title: message,
      icon: "none",
    });
  }
};
// 订阅已加入的群组
// function getGroupchatListFn(uid) {
// 	getGroupchatList({
// 		userId: uid
// 	}).then((res) => {
// 		if (res && res.data && res.data.length > 0) {
// 			//订阅群消息
// 			var groupIds = res.data;
// 			GoEasy.im.subscribeGroup({
// 				groupIds: groupIds,
// 				onSuccess: function() {
// 					//订阅成功
// 					console.log("Group message subscribe successfully.");
// 				},
// 				onFailed: function(error) {
// 					//订阅失败
// 					console.log(
// 						"Failed to subscribe group message, code:" +
// 						error.code +
// 						" content:" +
// 						error.content
// 					);
// 				},
// 			});
// 		}
// 	});
// }

// 获取用户授权code并调用getUserOpenId接口获取openId
const getUserOpenIdHandler = async () => {
  try {
    const loginRes = await new Promise((resolve, reject) => {
      uni.login({
        provider: "weixin",
        scope: "snsapi_base",
        success: resolve,
        fail: reject,
      });
      // #endif
    });

    if (!loginRes.code) {
      throw new Error("获取授权code失败");
    }
    const code = loginRes.code;

    const openIdRes = await getUserOpenId(code);
    if (openIdRes.data && openIdRes.data.openId) {
      Cache.set("userOpenId", openIdRes.data.openId, 86400);
      console.log("获取openId成功：", openIdRes.data.openId);
      return openIdRes.data.openId;
    } else {
      throw new Error("获取openId返回数据异常");
    }
  } catch (err) {
    const message = err.message || "获取openId失败";
    Toast({ title: message, icon: "none" });
    console.error("获取openId失败：", err);
    return null;
  }
};

const getUserInfoFn = async (data) => {
  try {
    appStore.SETUID(data.uid);
    const res = await getUserInfo();
    appStore.UPDATE_USERINFO(res.data);
    userInfo.value = res.data;

    // 获取openId
    await getUserOpenIdHandler();

    // connect({
    // 	id: appStore.uid?.toString(),
    // 	data: {
    // 		avatar: appStore.$userInfo?.avatar,
    // 		nickname: appStore.$userInfo?.nickname,
    // 		phone: appStore.$userInfo?.phone,
    // 		uid: appStore.uid?.toString(),
    // 	},
    // });
    // 订阅已加入的群组
    // await getGroupchatListFn(data.uid);

    if (merchantId.value != "") {
      let obj = {
        merchantId: merchantId.value,
        userId: res.data.userId,
      };

      await footprintScanFn(obj);
    } else {
      appStore.UPDATE_MERCHANT_ID("");
      Toast({
        title: "登录成功",
      });
      backHome();
    }
  } catch (err) {
    console.error(err);
    uni.showToast({
      title: err.msg,
      icon: "none",
    });
  }
};
const backHome = () => {
  if (userInfo.value.merchant && userInfo.value.merchant.id) {
    uni.navigateTo({
      url: "/pages/merchantCenter/index",
    });
  } else {
    uni.switchTab({
      url: "/pages/index/index",
    });
  }
};
const footprintScanFn = async (data) => {
  const res = await footprintScan(data);
  appStore.USERINFO();
  Toast({
    title: "登录成功",
  });
  backHome();
};
const checkPrivacyAgreement = () => {
  if (!aloneChecked.value) {
    Toast({
      title: "请阅读并同意用户协议和隐私政策",
      icon: "none",
    });
  }
};

const getPhoneNumberFn = async (e) => {
  console.log("e", e);
  // Toast({ title: "登录中..." });
  appStore.setIndexRefersh(true);
  if (!aloneChecked.value) {
    return Toast({
      title: "请阅读并同意用户协议和隐私政策",
      icon: "none",
    });
  }
  const res = await getPhoneNumber(e);
  console.log("res", res);
  if (res) {
    appStore.LOGIN({
      token: res.data.token,
    });
    // 保存过期时间（999天后过期）
    const expiresTime = Math.round(new Date() / 1000) + 999 * 24 * 60 * 60;
    Cache.set(EXPIRES_TIME, expiresTime, 0);
    await getUserInfoFn(res.data);
  }
};
onLoad(() => {
  console.log(appStore.$wxConfig);
  merchantId.value = appStore.merchantId || "";
  getLogoImage();
});

onMounted(() => {
  uni.getSystemInfo({
    success(res) {
      platform.value = res.platform.toLowerCase();
      if (platform.value === "ios" && res.system.split(" ")[1] >= 13) {
        appleShow.value = true;
      }
    },
  });
});
</script>

<style lang="scss" scoped>
::v-deep .u-status-bar {
  background: transparent;
  background-color: transparent !important;
}

::v-deep .u-navbar__content {
  background: transparent;
  background-color: transparent !important;
}

.login-wrapper {
  //background: url('https://sb-admin.oss-cn-shenzhen.aliyuncs.com/shuibei-mini/new-mini/login@2x.png');
  background-repeat: no-repeat;
  background-size: 100% 624rpx;
  background-color: #ffffff;
}

.appLogin {
  .hds {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24rpx;
    color: #b4b4b4;

    .line {
      width: 68rpx;
      height: 1rpx;
      background: #cccccc;
    }

    p {
      margin: 0 20rpx;
    }
  }

  .btn-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30rpx;

    .btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 68rpx;
      height: 68rpx;
      border-radius: 50%;
    }

    .apple-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 30rpx;
      background: #000;
      border-radius: 34rpx;
      font-size: 40rpx;

      .icon-s-pingguo {
        color: #fff;
        font-size: 40rpx;
      }
    }

    .iconfont {
      font-size: 40rpx;
      color: #fff;
    }

    .wx {
      margin-right: 30rpx;
      background-color: #61c64f;
    }

    .mima {
      background-color: #28b3e9;
    }

    .yanzheng {
      background-color: #f89c23;
    }
  }
}

.code img {
  width: 100%;
  height: 100%;
}

.acea-row.row-middle {
  input {
    margin-left: 20rpx;
    display: block;
  }
}

.login-wrapper {
  height: 100vh;

  .shading {
    padding: 72rpx 78rpx;
    display: flex;
    justify-content: center;
    flex-direction: column;
    position: relative;
    z-index: 1;

    view {
      color: #333333;
      font-size: 36rpx;
      font-weight: bold;

      &:first-child {
        font-size: 48rpx;
        margin-bottom: 16rpx;
      }
    }

    .ip-pic {
      width: 261rpx;
      height: 480rpx;
      position: absolute;
      right: 14rpx;
      bottom: calc(-76rpx - 88rpx);
    }
  }

  .whiteBg {
    // margin-top: 100rpx;
    background: #ffffff;
    border-radius: 48rpx 48rpx 0rpx 0rpx;
    position: relative;
    z-index: 5;

    .whiteBg-tab {
      color: #666666;
      display: flex;
      align-items: center;
      height: 88rpx;
      text-align: center;
      //background: url('https://sb-admin.oss-cn-shenzhen.aliyuncs.com/shuibei-mini/new-mini/logintab1.png');
      background-repeat: no-repeat;
      background-size: cover;

      .active {
        width: 407rpx;

        view {
          color: #f8c008;
          font-weight: bold;
          position: relative;

          &::after {
            left: 50%;
            bottom: -12rpx;
            content: "";
            transform: translateX(-50%);
            position: absolute;
            width: 32rpx;
            height: 8rpx;
            background: #f8c008;
            border-radius: 4rpx;
          }
        }
      }

      .noActive {
        flex: 1;
      }
    }

    .whiteBg-tabs {
      //background: url('https://sb-admin.oss-cn-shenzhen.aliyuncs.com/shuibei-mini/new-mini/logintab.png');
      background-repeat: no-repeat;
      background-size: cover;
    }

    .list {
      padding: 0 80rpx;
      margin-top: 120rpx;

      .item {
        display: flex;
        height: 88rpx;
        align-items: center;
        justify-content: space-between;
        padding: 0 8rpx 0 24rpx;
        background: #f9f7f0;
        border-radius: 16rpx;
        margin-bottom: 32rpx;

        .texts {
          flex: 1;
          font-size: 28rpx;
        }

        .code {
          padding: 0;
          margin: 0;
          width: 188rpx;
          display: flex;
          align-items: center;
          height: 72rpx;
          justify-content: center;
          background: #ffffff;
          border-radius: 16rpx;
          color: #f8c008;
          font-size: 28rpx;
          font-weight: bold;
          border: none;

          &::after {
            width: 0;
            border: none;
          }
        }
      }
    }

    .logon {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 88rpx;
      background-color: #f8c008;
      border-radius: 16rpx;
      color: #333333;
      font-size: 32rpx;
      font-weight: bold;
    }

    .logonWX {
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f8c008;
      border: none !important;
      border-radius: 16rpx;
      color: #fff;
      padding: 11rpx 28rpx;
      font-size: 30rpx;
    }

    .logonWX[disabled] {
      background-color: #beedc7;
    }
  }

  .privacy-box {
    font-size: 24rpx;
    padding: 0 80rpx;
    display: flex;
    align-items: center;

    image {
      width: 28rpx;
      height: 28rpx;
      margin-right: 8rpx;
    }

    .privacy-text {
      color: #f8c008;

      vertical-align: top;
    }
  }
}

.footer {
  padding: 48rpx 80rpx 72rpx;
}

.back_extend {
  //position: fixed;
  //top: 50px;
  //left: 10px;
  //font-size: 26rpx;
  //color: #999;
}

.wx-login-tip {
  display: flex;
  align-items: center;
  width: 590rpx;
  margin: 0 auto;
  justify-content: space-between;

  .login-line {
    width: 193rpx;
    height: 1rpx;
    background-color: #f1f3f8;
  }

  .wx-tip {
    font-size: 28rpx;
    line-height: 44rpx;
    color: #999;
    flex: 1;
    width: 100rpx;
    text-align: center;
    display: block;
  }
}

.wx-login-btn {
  width: 590rpx;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 32rpx;
  padding-bottom: 30rpx;

  .wx-icon {
    width: 92rpx;
    height: 92rpx;
  }
}
</style>
