<template>
  <view
    class="header-user"
    v-if="userDetails.id"
    @click.stop="handleOperation({ type: 'userDetails', needToken: true })"
  >
    <view class="user-photo">
      <image
        :src="userDetails.headPhoto || $defaultAvatar"
        mode="aspectFill"
      ></image>
    </view>
    <view class="user-info">
      <view class="user-name">{{ userDetails.nickname || "" }}</view>
      <view class="user-phone">{{ userDetails.mobile || "" }}</view>
    </view>
    <text class="iconfont icon-right1">&#xe671;</text>
  </view>
  <uv-gap height="12" bgColor="#F7F7F7"></uv-gap>
  <view class="body-operation">
    <view
      v-for="item in operationList"
      class="operation-item"
      :key="item.type"
      @click.stop="handleOperation(item)"
    >
      <text class="operation-item-label">{{ item.label }}</text>
      <text class="iconfont icon-right1">&#xe671;</text>
    </view>

    <view
      class="operation-item"
      key="versionUpdate"
      @click.stop="handleOperation({ type: 'versionUpdate' })"
      v-if="!weiXinShow"
    >
      <text class="operation-item-label">检测更新</text>
      <view>
        <text class="color-green" v-if="!appInfo.appUpdate && appInfo.version">
          V{{ appInfo.version }}</text
        >
        <text v-if="appInfo.appUpdate" style="color: #08be5d">有新版本</text>
        <text class="iconfont icon-right1">&#xe671;</text>
      </view>
    </view>
  </view>
  <!-- <uv-gap height="12" bgColor="#F7F7F7" v-if="!weiXinShow"></uv-gap>
  <view class="body-operation" v-if="!weiXinShow">
    <view class="bind-label">第三方绑定</view>
    <view
      class="operation-item bind-item"
      v-for="item in bindList"
      :key="item.type"
      @click="handleOperation(item)"
    >
      <text class="operation-item-label">{{ item.label }}</text>
      <view>
        <text class="color-green" v-if="item.bindShow" style="color: #808080;">已绑定</text>
        <text class="color-green" v-else>绑定验证</text>
        <text class="iconfont icon-right1">&#xe671;</text>
      </view>
    </view>
  </view> -->

  <view class="sign">
    <button class="u-btn-two" @click="logOut(1)">退出登录</button>
  </view>

  <!-- #ifdef APP-PLUS -->
  <!-- 版本更新 -->
  <VersionUpdate
    ref="versionUpdateRef"
    :open="false"
    @setAppInfo="setAppInfo"
  />
  <!-- #endif -->

</template>

<script setup>
import { ref } from "vue";
import { onLoad, onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app";
import { userLogout_Api, userBinding_Api, userInfo } from "@/api/login.js";
import { thirdBindingInfo_Api } from "@/api/userInfo.js";
import utils from "@/util/index.js";

const versionUpdateRef = ref(null);
const weiXinShow = ref(false);
const userDetails = ref({});
const appInfo = ref({}); // app信息
const operationList = [
  {
    label: "更换手机号",
    needToken: true,
    type: "updatePhone",
  },
  {
    label: "设置支付密码",
    needToken: true,
    type: "setPayPassword",
  },
  {
    label: "关于我们",
    needToken: false,
    type: "aboutUs",
  },
  {
    label: "注销账户",
    needToken: true,
    type: "logOut",
  },
];

const bindList = ref([
  {
    label: "微信",
    needToken: true,
    type: "wxBind",
    bindShow: false,
  },
  {
    label: "支付宝",
    needToken: true,
    type: "zfbBind",
    bindShow: false,
  },
]);

const setAppInfo = (data) => {
  appInfo.value = data;
};

const handleOperation = (item) => {
  if (item.needToken && utils.isLoginTo(true)) return;
  switch (item.type) {
    case "updatePhone":
      uni.navigateTo({
        url: "/pages/set/updatePhone",
      });
      break;
    case "setPayPassword":
      uni.navigateTo({
        url: "/pages/set/payPassword",
      });
      break;
    case "aboutUs":
      uni.navigateTo({
        url: "/pages/protocol/index?code=about_us",
      });
      break;
    case "logOut":
      logOut(0);
      break;
    case "versionUpdate":
      if (appInfo.value.appUpdate) {
        versionUpdateRef.value.open();
      } else {
        uni.$uv.toast("当前版本为最新版本");
      }
      break;
    case "wxBind":
      WXBind();
      break;
    case "zfbBind":
      alipayBind();
      break;
    case "userDetails":
      uni.navigateTo({
        url: "/pages/set/edit",
      });
      break;
    default:
      break;
  }
};

// 退出登录
const logOut = (type = 0) => {
  uni.showModal({
    title: type ? "你确定要退出吗？" : "你确定要注销账户吗？",
    success: function (res) {
      if (res.confirm) {
        uni.showLoading({
          title: type ? "正在退出..." : "注销中...",
          mask: true,
        });
        userLogout_Api()
          .then((res) => {
            uni.hideLoading();
            if (res.code == 200) {
              uni.clearStorageSync();
              uni.$uv.toast(type ? "退出成功" : "注销成功");
              // #ifdef MP-WEIXIN
              uni.redirectTo({
                url: "/pages/login/wxLogin",
              });
              // #endif
              // #ifndef MP-WEIXIN
              // 在此处编写仅在 App 端执行的代码
              uni.redirectTo({
                url: "/pages/login/otherLogin",
              });
              // #endif
            }
          })
          .catch((err) => {
            // uni.hideLoading();
          });
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};

// 绑定用户信息
const setUserBinding = (data) => {
  userBinding_Api(data).then((res) => {
    if (res.code == 200) {
      uni.showToast({
        title: "绑定成功！",
        icon: "success",
        duration: 1500,
      });
      getThirdBindingInfo();
    }
  });
};

// 微信绑定
const WXBind = () => {
  uni.login({
    provider: "weixin",
    onlyAuthorize: true, // 微信登录仅请求授权认证
    success: (event) => {
      const { code } = event;
      // console.log(event)
      //客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
      let param = {
        thirdType: 0,
        code: code,
      };
      setUserBinding(param);
    },
    fail: (err) => {
      console.log(err);
      // 登录授权失败
      // err.code是错误码
      uni.$uv.toast("当前环境不支持微信操作!");
    },
  });
};
// 支付宝绑定
const alipayBind = () => {
  const AlipayAuth = uni.requireNativePlugin("DHQ-AlipayAuth");
  AlipayAuth.login(
    {
      appId: "2021006116626014", //你在支付宝平台申请的App ID
      scheme: "xctUrlSchemes", // 需要传到支付宝SDK的scheme,注意需要在manifest.json-->App其他常用配置-->UrlSchemes中配置Android和iOS的
      scope: "auth_user", //默认为auth_user
      init: "init", //默认传入init
    },
    (res) => {
      // console.log("res===>", res);
      //客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
      let code = res.auth_code;
      if (code) {
        let param = {
          code: code,
          thirdType: 1,
        };
        setUserBinding(param);
      }
    },
    (e) => {
      console.log(e);
      uni.$uv.toast("当前环境不支持支付宝操作!");
    }
  );
};

// 获取用户信息
const getuserDetails = () => {
  userInfo().then((res) => {
    if (res && res.code == 200) {
      userDetails.value = res.data || {};
      uni.setStorageSync("personal", res.data || {});
    }
  });
};

// 获取第三方绑定信息
const getThirdBindingInfo = () => {
  thirdBindingInfo_Api().then((res) => {
    if (res && res.code == 200) {
      // bindList.value = res.data || [];
      bindList.value[0].bindShow = res.data.bindingWechat ? true : false;
      bindList.value[1].bindShow = res.data.bindingAlipay ? true : false;
    }
  });
};

onLoad(() => {
  // #ifdef MP-WEIXIN
  weiXinShow.value = true;
  // #endif

  getuserDetails();

  // #ifndef MP-WEIXIN
  console.log("不是小程序");
  getThirdBindingInfo()
  // #endif

});
</script>

<style lang="scss" scoped>
.header-user {
  display: flex;
  align-items: center;
  padding: 40rpx 30rpx;
  font-size: 28rpx;
  font-family: PingFang SC, PingFang SC-Regular;
  font-weight: normal;
  color: #666666;

  .user-photo {
    flex-shrink: 0;
    image {
      width: 100rpx;
      height: 100rpx;
      margin-right: 25rpx;
      border-radius: 50%;
    }
  }

  .user-info {
    flex: 1;
    width: 0;
    margin-right: 20rpx;

    .user-name {
      margin-bottom: 5rpx;
      font-size: 32rpx;
      font-family: PingFang SC, PingFang SC-Bold;
      font-weight: bold;
      color: #1a1a1a;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .icon-right1 {
    margin-left: auto;
  }
}

.body-operation {
  padding: 0 30rpx;
  font-size: 28rpx;
  font-family: PingFang SC, PingFang SC-Regular;
  font-weight: normal;
  color: #1a1a1a;

  .operation-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border: none;
    }

    .icon-right1 {
      margin-left: auto;
      color: #666666;
    }
  }

  .bind-label {
    padding-top: 30rpx;
    font-size: 32rpx;
    font-family: PingFang SC, PingFang SC-Bold;
    font-weight: bold;
    color: #1a1a1a;
  }

  .operation-item.bind-item {
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.sign {
  padding: 100rpx 30rpx;
  box-sizing: border-box;
  .u-btn-two {
    height: 90rpx;
    line-height: 90rpx;
  }
}
.color-green {
  color: #0090ff;
  font-size: 28rpx;
}
</style>
