<template>
  <view :class="pageClass">
    <!-- mode="aspectFit" -->
    <image class="bgImg" src="../../assets/img/homeImg.jpg" />
    <!-- 视频,已废弃 -->
    <view v-show="false" class="videoBox">
      <!-- <video
        src="https://video.metavatar.cc/sv/d51a6f6-187fa2dff79/d51a6f6-187fa2dff79.mp4"
        autoplay
        muted
        loop
        :controls="false"
      /> -->
      <!-- <video
        src="https://wenlian.wenzhou.gov.cn//upload/video/2021-01-14%E3%80%8A%E7%93%AF%E8%B6%8A%E4%B9%8B%E5%8D%8E%E3%80%8B%E6%B8%A0%E5%B7%9D%EF%BC%9A%E8%B5%B0%E7%AC%94%E5%86%99%E4%BA%BA%E7%94%9F.mp4"
        autoplay
        loop
        :controls="false"
      /> -->
    </view>
    <view class="bottomBox">
      <button
        v-if="!checkboxValue[0] && userInfoModulesPinia.platForm == 2"
        class="bottomBtn"
        type="default"
        id="getPhoneNumber"
        @click="toCreate"
      >
        开始制作我的数字写真
      </button>
      <button
        v-if="checkboxValue[0] && userInfoModulesPinia.platForm == 2"
        class="bottomBtn"
        open-type="getPhoneNumber"
        type="default"
        id="getPhoneNumber"
        @getphonenumber="toCreate"
      >
        开始制作我的数字写真
      </button>
      <!-- 抖音获取手机号 -->
      <!-- <button
        v-if="userInfoModulesPinia.platForm == 3"
        class="bottomBtn"
        open-type="getPhoneNumber"
        type="default"
        id="getPhoneNumber"
        @getphonenumber="dogetphonenumber"
      >
        开始制作我的数字分身
      </button> -->
      <!-- 手机号登录 -->
      <button
        v-if="userInfoModulesPinia.platForm == 3"
        class="bottomBtn"
        type="default"
        id="getPhoneNumber"
        @click="showForm = true"
      >
        开始制作我的数字分身
      </button>
      <!-- <view class="bottomBtn" @click="toCreate"> 开始制作我的数字写真 </view> -->
      <!-- 同意协议   -->
      <u-checkbox-group
        v-if="userInfoModulesPinia.platForm == 2"
        v-model="checkboxValue"
        placement="row"
        @change="changedCheckbox"
      >
        <u-checkbox
          labelColor="white"
          activeColor="red"
          v-for="(item, index) in checkboxList"
          :name="item.name"
          :key="index"
        >
        </u-checkbox>
        <text class="checkPro"
          >同意<text class="goPro" @click="goPro">《智像用户使用协议》</text>
        </text>
      </u-checkbox-group>
    </view>
    <!-- 抖音手机号验证码登录 -->
    <view
      class="phoneLoginForm"
      v-show="userInfoModulesPinia.platForm == 3 && showForm"
    >
      <u--form
        labelPosition="left"
        :model="formData"
        :rules="rules"
        ref="formRef"
      >
        <u-form-item
          labelWidth="80"
          label="手机号"
          prop="phoneNum"
          borderBottom
          ref="form1"
        >
          <u--input
            type="number"
            v-model="formData.phoneNum"
            border="none"
          ></u--input>
        </u-form-item>
        <!-- 获取验证码 -->
        <!-- 验证码 -->
        <view class="getCodeBtn" @click="getCode">
          {{ backwardsNum < 60 ? backwardsNum + "s" : "发送验证码" }}
        </view>
        <!-- <view v-if="backwardsNums <= 0" class="getCodeBtn">{{
          backwardsNum
        }}</view> -->
        <u-form-item labelWidth="80" label="验证码 " borderBottom ref="form2">
          <u--input
            type="number"
            v-model="formData.codeNum"
            border="none"
          ></u--input>
        </u-form-item>
      </u--form>
      <view class="loginBtn" @click="loginByCode">登录</view>
    </view>

    <view class="outSide" v-if="showPrivacy">
      <view class="showPrivacy">
        <view class="title">隐私协议更新</view>
        <view class="content">
          感谢您一直以来对我们的信任和支持。为了更好地保护您的个人信息安全我们已经更新了隐私协议。如您继续使用我们的服务即表示同意并接受更新后的隐私协议。如您有任何疑问或意见，欢迎您联系我们的客户服务团队。
        </view>
        <button
          class="agree"
          type="primary"
          open-type="agreePrivacyAuthorization"
          @agreeprivacyauthorization="handleAgreePrivacyAuthorization"
        >
          同意
        </button>
        <button class="check" @click="handleOpenPrivacyContract">
          查看《隐私保护指引》
        </button>
        <image
          @click="closePrivacy"
          class="delete"
          src="../../assets/icon/delete.png"
          mode=""
        />
      </view>
    </view>
  </view>
</template>

<script setup>
//#region 导入
import { ref, reactive, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { findImageApi, findGlodApi } from "../../api/home";
import {
  loginApi,
  loginPhoneApi,
  getCodeApi,
  loginByCodeApi,
} from "../../api/login.js";
import { userInfoModules } from "@/store/modules/userInfo";
//#endregion
const userInfoModulesPinia = userInfoModules();

const showPrivacy = ref(false);

const pageClass = computed(() => {
  if (userInfoModulesPinia.platForm == 1) {
    return "page pageH5";
  } else {
    return "page";
  }
});
//#region 勾选和手机号授权
const checkboxValue = ref([]);
const checkboxList = ref([
  {
    name: "同意智像相机用户使用协议",
  },
]);
function changedCheckbox(e) {
  console.log(e);
}

async function dogetphonenumber(e) {
  console.log(e, "e");
  if (e.detail.errMsg.includes("ok")) {
    // if (e.detail.errMsg.includes("fail")) {
    //用户授权了手机号
    const data = {
      appId: userInfoModulesPinia.getAppId(),
      openId: userInfoModulesPinia.openId,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      uid: urlUid.value,
    };
    try {
      const res2 = await loginPhoneApi(data);
      uni.showToast({
        icon: "none",
        title: "获取成功",
      });
      userInfoModulesPinia.token = res2.data.token;
      uni.setStorageSync("token", userInfoModulesPinia.token);
      uni.switchTab({
        url: "/pages/uploadPhoto/uploadPhoto",
      });
    } catch (error) {
      uni.showToast({
        icon: "none",
        title: "获取手机号失败",
      });
    }
  } else {
    uni.showToast({
      icon: "none",
      title: "获取手机号失败",
    });
    //code已过期 重新拿code再授权
  }
}

async function toCreate(e) {
  console.log();
  if (checkboxValue.value[0]) {
    // await handleLogin();
    await dogetphonenumber(e);
  } else {
    uni.showModal({
      title: "提示",
      content: "同意智像相机用户使用协议？",
      success: function (res) {
        if (res.confirm) {
          checkboxValue.value = ["同意智像相机用户使用协议"];
          // handleLogin();
          dogetphonenumber(e);
        } else if (res.cancel) {
        }
      },
      fail: (err) => {},
    });
  }
}
const userInfo = ref(null);

async function handleLogin() {
  // uni.getUserInfo({});
  // getPhoneNumber
  // getUserProfile
  uni.getUserProfile({
    desc: "用于完善用户信息",
    success: async (res1) => {
      console.log(res1);
      userInfo.value = res1.userInfo;
      userInfoModulesPinia.userInfo = res1.userInfo;
      console.log(userInfoModulesPinia.openId, "拿出openid");
      const data = {
        appId: "wx75cf14e3a0d45821",
        openId: userInfoModulesPinia.openId,
        encryptedData: res1.encryptedData,
        iv: res1.iv,
      };
      try {
        const res2 = await loginPhoneApi(data);
        uni.showToast({
          icon: "none",
          title: "获取成功",
        });
      } catch (error) {
        uni.showToast({
          icon: "none",
          title: "获取失败",
        });
      }
    },
    fail: (err) => {
      console.log(err);
      uni.showToast({
        icon: "none",
        title: "用户拒绝获取",
      });
    },
  });
}

const goPro = () => {
  uni.navigateTo({
    url: "/pages/protocol/user",
  });
};
//#endregion ---------------------

//#region 抖音手机号登录
const showForm = ref(false);
const formData = ref({
  phoneNum: null,
  codeNum: null,
});
const rules = {
  phoneNum: [
    {
      required: true,
      message: "请填写手机号",
      trigger: ["blur"],
    },
    {
      // 自定义验证函数，见上说明
      validator: (rule, value, callback) => {
        // 上面有说，返回true表示校验通过，返回false表示不通过
        // uni.$u.test.mobile()就是返回true或者false的
        return uni.$u.test.mobile(value);
      },
      message: "手机号码不正确",
      // 触发器可以同时用blur和change
      trigger: ["blur"],
    },
  ],
};
const formRef = ref(null);
const form1 = ref(null);
const backwardsNum = ref(60);
const countdownTimer = ref(null); // 倒计时的计时器
const timerFlag = ref(false);
function getCode() {
  if (timerFlag.value) {
    return; // 如果倒计时尚未结束，不执行倒计时操作
  }
  timerFlag.value = true;
  formRef.value
    .validate()
    .then(async (res0) => {
      try {
        uni.showLoading({
          title: "请稍后",
          mask: true,
        });
        console.log("duanxing1");
        const res = await getCodeApi(formData.value.phoneNum);
        console.log(res.code, "duanxing2");
        uni.hideLoading();
        if (res.code != 200) {
          uni.showToast({
            title: res.message,
            icon: "none",
          });
        }
        console.log(res);
        // 表单验证通过后开始倒计时
        countdownTimer.value = setInterval(() => {
          if (backwardsNum.value > 0) {
            backwardsNum.value--;
          } else {
            clearInterval(countdownTimer.value);
            countdownTimer.value = null;
            backwardsNum.value = 60;
            timerFlag.value = false;
          }
        }, 1000);
      } catch (error) {
        uni.hideLoading();
        uni.$u.toast("短信验证码获取失败");
        clearInterval(countdownTimer.value);
        countdownTimer.value = null;
        backwardsNum.value = 60;
        timerFlag.value = false;
      }
    })
    .catch((errors) => {
      console.log(errors);
    });
}

async function loginByCode() {
  uni.showLoading({
    title: "请稍后",
    mask: true,
  });
  const data = {
    appId: userInfoModulesPinia.getAppId(),
    openId: userInfoModulesPinia.openId,
    phone: formData.value.phoneNum,
    code: formData.value.codeNum,
  };
  try {
    const res = await loginByCodeApi(data);
    console.log(res);
    uni.hideLoading();
    userInfoModulesPinia.token = res.data.token;
    uni.setStorageSync("token", userInfoModulesPinia.token);
    console.log(res.code, "denglu");
    if (res.code != 200) {
      uni.showToast({
        title: res.message,
        icon: "none",
      });
    } else {
      uni.switchTab({
        url: "/pages/uploadPhoto/uploadPhoto",
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: "登录失败，请重试",
      icon: "none",
    });
  }
}
//#endregion ---------------------

//#region 隐私协议
const getPrivacySetting = (num) => {
  const canIUsePrivacy = wx.canIUse("getPrivacySetting");
  // console.log(canIUsePrivacy, "canIUse getPrivacySetting");
  if (canIUsePrivacy) {
    wx.getPrivacySetting({
      success: (res) => {
        // console.log(res, "getPrivacySetting"); // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        if (res.needAuthorization) {
          // 需要弹出隐私协议
          showPrivacy.value = true;
        } else {
          // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
          if (num == 1) {
            // 返回token，直接跳转首页
            // uni.switchTab({
            //   url: "/pages/uploadPhoto/uploadPhoto",
            // });
          } else if (num == 2) {
            // 没有返回token，无事发生
          }
        }
      },
      fail: () => {},
      complete: () => {},
    });
  }
};

// 关闭弹框直接退出小程序，仅对微信小程序生效
const closePrivacy = () => {
  wx.exitMiniProgram();
};

const handleAgreePrivacyAuthorization = () => {
  // console.log("Privacy Agreed!");
  showPrivacy.value = false;
  // 用户同意隐私协议事件回调
  // 用户点击了同意，之后所有已声明过的隐私接口和组件都可以调用了
};

const handleOpenPrivacyContract = () => {
  // 打开隐私协议页面
  wx.openPrivacyContract({
    success: () => {}, // 打开成功
    fail: () => {}, // 打开失败
    complete: () => {},
  });
};
//#endregion ---------------------------------

//#region 初始化
const urlUid = ref(""); //通过邀请来的会携带邀请人ID参数
onLoad((options) => {
  // 获取平台及系统信息
  uni.getSystemInfo({
    success: function (res) {
      let uniPlatform = "";
      let osName = "";
      if (res.uniPlatform == "web") {
        uniPlatform = 1;
      } else if (res.uniPlatform == "mp-weixin") {
        uni.setStorageSync("plat", 1);
        uniPlatform = 2;
      } else if (res.uniPlatform == "mp-toutiao") {
        uni.setStorageSync("plat", 3);
        uniPlatform = 3;
      }
      if (res.osName == "windows") {
        osName = 1;
      } else if (res.osName == "ios") {
        osName = 2;
      } else if (res.osName == "android") {
        osName = 3;
      } else if (res.osName == "mac") {
        osName = 4;
      } else if (res.osName == "linux") {
        osName = 5;
      }

      userInfoModulesPinia.platForm = uniPlatform; // 平台
      userInfoModulesPinia.hostSystem = osName; // 系统
      console.log(res.uniPlatform, uniPlatform, "PlatForm");
      console.log(res.osName, osName, "System");

      // 原来的登录逻辑
      // 二维码扫描进入时
      if (options.scene) {
        const str = decodeURIComponent(options.scene);
        const regex = /_u:(\d+)/; // 正则表达式匹配_u:后面的数字
        const match = str.match(regex);
        urlUid.value = match[1];
      }
      // 分享链接进入时
      else if (options.userId) {
        urlUid.value = options.userId;
      } else {
        urlUid.value = null;
      }
      console.log(urlUid.value, "邀请人id");
      uni.hideHomeButton();
      // workId.value = options.id;

      if (options.type == "tokenFfalse") {
        uni.showToast({
          title: "登录失效,请重新登录",
          icon: "none",
        });
      }
      // 已有token时直接登录
      if (uni.getStorageSync("token")) {
        uni.switchTab({ url: "/pages/uploadPhoto/uploadPhoto" });
      }

      if (userInfoModulesPinia.platForm == 2) {
        uni.login({
          provider: "weixin", // 使用微信登录授权
          success: async (res) => {
            console.log(res, "uni.login");
            if (res.code) {
              try {
                uni.showLoading({
                  title: "加载中...",
                  mask: true,
                });
                const data = {
                  appId: userInfoModulesPinia.getAppId(),
                  code: res.code,
                };
                const res2 = await loginApi(data);
                userInfoModulesPinia.openId = res2.data.openId;
                if (res2.data.token) {
                  userInfoModulesPinia.token = res2.data.token;
                  uni.setStorageSync("token", userInfoModulesPinia.token);
                  console.log(userInfoModulesPinia.openId, "获取openid");
                  // 获取头像和金币
                  const res3 = await findImageApi();
                  if (res3.data) {
                    uni.setStorageSync("userId", res3.data.id);
                  }
                  userInfoModulesPinia.myAvatar =
                    res3.data && res3.data.image ? res3.data.image : "";
                  const res4 = await findGlodApi();
                  if (res4.data) {
                    uni.setStorageSync("userId", res4.data.id);
                  }
                  if (!res4.data) {
                    userInfoModulesPinia.myGlod = 0;
                  } else {
                    userInfoModulesPinia.myGlod = res4.data
                      .digitalAvatarResidueGlod
                      ? res4.data.digitalAvatarResidueGlod
                      : 0;
                  }
                  uni.hideLoading();
                  if (res2.data.token) {
                    getPrivacySetting(1);
                  } else {
                    console.log("error1");
                    uni.showToast({
                      title: "登录失败，请重试",
                      icon: "none",
                    });
                  }
                } else {
                  getPrivacySetting(2);
                }
                uni.hideLoading();
              } catch (error) {
                // uni.redirectTo({
                //   url: "pages/index/index",
                // });
                console.log(error, "error2");
                uni.showToast({
                  title: "登录失败，请重试",
                  icon: "none",
                });
              }
            } else {
              // uni.redirectTo({
              //   url: "pages/index/index",
              // });
              console.log("error3");
              uni.showToast({
                title: "登录失败，请重试",
                icon: "none",
              });
            }
          },
          fail: (err) => {
            // uni.redirectTo({
            //   url: "pages/index/index",
            // });
            console.log("error4");
            uni.showToast({
              title: "登录失败，请重试",
              icon: "none",
            });
          },
        });
      }
      // 抖音头条授权
      else if (userInfoModulesPinia.platForm == 3) {
        uni.login({
          provider: "toutiao", // 使用微信登录授权
          success: async (res) => {
            console.log(res, "uni.login");
            if (res.code) {
              try {
                uni.showLoading({
                  title: "加载中...",
                  mask: true,
                });
                const data = {
                  appId: userInfoModulesPinia.getAppId(),
                  code: res.code,
                };
                const res2 = await loginApi(data);
                userInfoModulesPinia.openId = res2.data.openId;
                if (res2.data.token) {
                  userInfoModulesPinia.token = res2.data.token;
                  // uni.setStorageSync("token", userInfoModulesPinia.token);
                  console.log(userInfoModulesPinia.openId, "获取openid");
                  uni.hideLoading();
                } else {
                  uni.hideLoading();
                  // uni.redirectTo({
                  //   url: "/pages/login/index",
                  // });
                  console.log("error1");
                  uni.showToast({
                    title: "登录失败，请重试",
                    icon: "none",
                  });
                }
                uni.hideLoading();
              } catch (error) {
                uni.hideLoading();
                console.log(error, "error2");
                uni.showToast({
                  title: "登录失败，请重试",
                  icon: "none",
                });
              }
            } else {
              console.log("error3");
              uni.showToast({
                title: "登录失败，请重试",
                icon: "none",
              });
            }
          },
          fail: (err) => {
            console.log("error4");
            uni.showToast({
              title: "登录失败，请重试",
              icon: "none",
            });
          },
        });
      }
    },
  });
});
//#endregion ---------------------------------

//#region

//#endregion ---------------------------------
</script>

<style lang="scss">
.page {
  position: relative;
  padding: 0;
  min-height: 100vh;
}

.bgImg {
  width: 750rpx;
  height: 100vh;
}

.videoBox {
  width: 750rpx;
  height: 1120rpx;

  // aspect-ratio: 9/12;
  video {
    width: 100%;
    height: 100%;
    // aspect-ratio: 9/12;
  }
}

.bottomBox {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 345rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.8);
  color: #fff !important;

  .bottomBtn {
    margin-top: 55rpx;
    margin-bottom: 65rpx;
    width: 520rpx;
    height: 100rpx;
    border-radius: 50rpx;
    line-height: 100rpx;
    text-align: center;
    color: #fff;
    background-color: rgba(255, 79, 0, 1);
    font-size: 30rpx;
    font-weight: 900;
  }

  .checkPro {
    display: inline-block;
    height: 27rpx;
    line-height: 54rpx;

    .goPro {
      color: #ff4f00;
    }
  }
}

.phoneLoginForm {
  position: absolute;
  top: 20%;
  left: 30rpx;
  width: 690rpx;
  z-index: 9;
  background-color: rgba(255, 255, 255, 0.6);
  padding: 50rpx 30rpx;
  border-radius: 30rpx;

  .u-code {
    width: 100%;
    height: 80rpx;
    background-color: green;
    color: #ff4f00;
  }

  .getCodeBtn {
    background-color: green;
    text-align: center;
    line-height: 50rpx;
    border-radius: 15rpx;
  }

  .loginBtn {
    background-color: #ff4f00;
    text-align: center;
    line-height: 50rpx;
    border-radius: 15rpx;
  }
}

.outSide {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  color: #000000;
  background-color: #00000059;

  .showPrivacy {
    position: fixed;
    width: 520rpx;
    background-color: #fff;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 60rpx 50rpx;
    border-radius: 20rpx;
    box-shadow: #00000047 2px 1px 2px 2px;

    .title {
      text-align: center;
      font-size: 30rpx;
      font-weight: 600;
    }

    .content {
      text-indent: 2em;
      margin: 40rpx 0;
    }

    button {
      width: 350rpx;

      &.agree {
        margin-bottom: 25rpx;
        background-color: #ff4f00;
      }

      &.check {
        background-color: #ffffff00;
        font-size: 21rpx;
        text-decoration: underline;
        padding: 0;

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

    .delete {
      position: absolute;
      top: 15rpx;
      right: 15rpx;
      width: 65rpx;
      height: 65rpx;
    }
  }
}
</style>
