<template>
  <view class="pc">
    <view class="pc-header">
      <uv-navbar
        title="个人中心"
        fixed
        placeholder
        leftIconSize="0"
        bgColor="transparent"
        :border="false"
        titleStyle="font-weight: 700;color: #1a1a1a;"
      >
      </uv-navbar>

      <view
        class="pc-user u-flex-center-sb"
        @tap.stop="goJump('/pages/set/edit', true)"
      >
        <view class="pc-user-left u-flex-center">
          <image
            v-if="userInformation && userInformation.headPhoto"
            :src="userInformation.headPhoto"
            class="pc-avatar"
            mode="aspectFill"
          />
          <image
            v-else
            :src="$defaultAvatar"
            class="pc-avatar"
            mode="aspectFill"
          />
          <view class="pc-user-info">
            <view class="pc-user-name">{{
              userInformation.id ? userInformation.nickname : "登录/注册"
            }}</view>
            <view class="pc-user-phone u-flex-center" v-if="userInformation.id">
              <image
                class="pc-user-phone-icon"
                src="/static/image/personalCenter/icon_phone.png"
                mode="aspectFill"
              />
              <text class="pc-user-phone-text">{{
                userInformation.mobile
              }}</text>
            </view>
          </view>
        </view>
        <view class="pc-nav-right">
          <view
            class="pc-nav-icon"
            @tap.stop="goJump('/pages/user/myMsg', true)"
          >
            <uv-icon name="chat" color="#1a1a1a" size="44rpx"></uv-icon>
            <view class="pc-nav-badge" v-if="myMsgText">{{ myMsgText }}</view>
          </view>
          <view
            class="pc-nav-icon"
            @tap.stop="goJump('/pages/set/index', true)"
          >
            <uv-icon name="setting" color="#1a1a1a" size="44rpx"></uv-icon>
          </view>
          <!-- <uv-icon name="arrow-right" color="#1a1a1a" size="44rpx"></uv-icon> -->
        </view>
      </view>

      <view class="pc-assets u-flex-center-sb">
        <view
          class="pc-assets-card"
          style="
            background-image: url('/static/image/personalCenter/icon_points.png');
          "
          @tap.stop="goMypoints"
        >
          <view class="pc-assets-value">{{ integralAble || 0 }} <text class="unit">积分</text></view>
          <view class="pc-assets-label">我的积分</view>
        </view>
        <view
          class="pc-assets-card"
          style="
            background-image: url('/static/image/personalCenter/icon_amount.png');
          "
          @tap.stop="goToMyWallet"
        >
          <view class="pc-assets-value">{{
            $addDecimals(userInformation.balance || 0, 2)
          }} <text class="unit">元</text></view>
          <view class="pc-assets-label">我的钱包</view>
        </view>
      </view>
    </view>

    <view class="pc-body">
      <view class="pc-card">
        <view class="pc-card-head u-flex-center-sb">
          <view class="pc-card-title">商城订单</view>
          <view class="pc-card-more u-flex-center" @tap.stop="goOrderList(-1)">
            <text>查看更多</text>
            <uv-icon name="arrow-right" size="24rpx" color="#999999"></uv-icon>
          </view>
        </view>
        <view class="pc-order-grid">
          <view
            class="pc-order-item"
            v-for="item in orderStatusList"
            :key="item.keys"
            @tap.stop="goOrderList(item.keys)"
          >
            <image class="pc-order-icon" :src="item.icon" mode="aspectFill" />
            <view class="pc-order-text">{{ item.label }}</view>
          </view>
        </view>
      </view>

      <view class="pc-card">
        <view class="pc-card-head">
          <view class="pc-card-title">其他工具</view>
        </view>
        <view class="pc-tool-grid">
          <view
            class="pc-tool-item"
            v-for="(item, index) in toolsList"
            :key="index"
          >
            <template v-if="item.key === 'kf'">
              <!-- #ifdef MP-WEIXIN -->
              <button open-type="contact" class="pc-tool-btn">
                <image
                  class="pc-tool-icon"
                  :src="item.icon"
                  mode="aspectFill"
                />
                <view class="pc-tool-text">{{ item.label }}</view>
              </button>
              <!-- #endif -->
              <!-- #ifndef MP-WEIXIN -->
              <view class="pc-tool-btn" @tap.stop="customerService">
                <image
                  class="pc-tool-icon"
                  :src="item.icon"
                  mode="aspectFill"
                />
                <view class="pc-tool-text">{{ item.label }}</view>
              </view>
              <!-- #endif -->
            </template>
            <template v-else>
              <view class="pc-tool-btn" @tap.stop="goSublevelPage(item)">
                <image
                  class="pc-tool-icon"
                  :src="item.icon"
                  mode="aspectFill"
                />
                <view class="pc-tool-text">{{ item.label }}</view>
              </view>
            </template>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script setup>
import { computed, ref } from "vue";
import { onShow, onPullDownRefresh } from "@dcloudio/uni-app";

import { userInfo } from "@/api/login.js";
import { messageUnreadNum_Api, totalIntegral_Api } from "@/api/userInfo.js";
import utils from "@/util/index.js";

const userInformation = ref({});
const myMsg = ref(0);
const integralAble = ref(0); // 用户积分数据

const myMsgText = computed(() => {
  if (!myMsg.value) return "";
  if (myMsg.value > 99) return "99+";
  return String(myMsg.value);
});

const orderStatusList = [
  { label: "待付款", icon: "/static/image/order/order-icon1.png", keys: 0 },
  { label: "待发货", icon: "/static/image/order/order-icon2.png", keys: 1 },
  { label: "待收货", icon: "/static/image/order/order-icon3.png", keys: 3 },
  { label: "待评价", icon: "/static/image/order/order-icon4.png", keys: 5 },
  { label: "退款/售后", icon: "/static/image/order/order-icon5.png", keys: 6 },
];

const toolsList = ref([
  {
    label: "我的拼团",
    icon: "/static/image/personalCenter/tool2.png",
    url: "/pages/groupBuying/myGbOrder/list",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "收货地址",
    icon: "/static/image/personalCenter/tool3.png",
    url: "/pages/user/address/addressList?formType=mine",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "分销中心",
    icon: "/static/image/personalCenter/tool1.png",
    url: "/pages/distribution/index",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "我的收藏",
    icon: "/static/image/personalCenter/tool5.png",
    url: "/pages/user/collection",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "商家入驻",
    icon: "/static/image/personalCenter/tool4.png",
    url: "/pages/user/merchant/settleIn?type=tenants_agreement",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "官方客服",
    icon: "/static/image/personalCenter/tool9.png",
    url: "",
    key: "kf",
    idNeedLogin: false,
    isPage: false,
  },
  {
    label: "常见问题",
    icon: "/static/image/personalCenter/tool8.png",
    url: "/pages/user/faq",
    idNeedLogin: false,
    isPage: true,
  },
  {
    label: "领券中心",
    icon: "/static/image/personalCenter/tool6.png",
    url: "/pages/couponCenter/index",
    idNeedLogin: false,
    isPage: true,
  },
  {
    label: "优惠券",
    icon: "/static/image/personalCenter/tool7.png",
    url: "/pages/couponCenter/index?isMyCoupon=true",
    idNeedLogin: true,
    isPage: true,
  },
]);

const goOrderList = (keys) => {
  goJump(`/pages/order/mallOrder/orderList?keys=${keys}`, true);
};

// 跳转我的积分
function goMypoints() {
  if (utils.isLoginTo(true)) return;
  uni.navigateTo({ url: "/pages/user/pointsList" });
}
//获取未读消息
function getUnreadNum() {
  return messageUnreadNum_Api()
    .then((res) => {
      uni.stopPullDownRefresh();
      if (res && res.code == 200) {
        myMsg.value = res.data || 0;
      } else {
        myMsg.value = 0;
      }
    })
    .catch(() => {
      myMsg.value = 0;
    });
}

//前往我的钱包
function goToMyWallet() {
  if (utils.isLoginTo(true)) return;
  uni.navigateTo({
    url: "/pages/user/wallet/index",
  });
}

//判断是否登录
function judgeLogin() {
  return userInfo().then((res) => {
    uni.stopPullDownRefresh();
    if (res && res.code == 200) {
      userInformation.value = res.data;
      uni.setStorageSync("personal", res.data);
    }
  });
}

// 跳转子级页面
const goSublevelPage = (item) => {
  if (item.key === "kf") return;
  if (item.idNeedLogin) {
    let url = item.url;
    if (utils.isLoginTo(true)) return;
    uni.navigateTo({ url });
    return;
  }
  uni.navigateTo({ url: item.url });
};

// 跳转页面
const goJump = (url = "", isLogin = false) => {
  if (!url) return;
  if (isLogin && utils.isLoginTo(isLogin)) return;
  uni.navigateTo({
    url,
  });
};

// 查询总积分
const getTotalIntegral = () => {
  return totalIntegral_Api().then((res) => {
    if (res.code == 200) {
      integralAble.value = res.data || 0;
    }
  });
};

// 客服
const customerService = () => {
  // #ifdef APP-PLUS
  let sweixin;
  plus.share.getServices(
    (res) => {
      sweixin = res.find((i) => i.id === "weixin");
      if (sweixin) {
        sweixin.openCustomerServiceChat(
          {
            corpid: "wxf4cb2367022f4941",
            url: "https://work.weixin.qq.com/kfid/kfcfa748e7c99d682b8",
          },
          (suc) => {
            console.log("success", JSON.stringify(suc));
          },
          (err) => {
            console.log("error", JSON.stringify(err));
          }
        );
      } else {
        plus.nativeUI.alert("当前环境不支持微信操作!");
      }
    },
    function (e) {
      uni.showToast({
        title: "获取服务失败，不支持该操作。" + JSON.stringify(e),
        icon: "error",
      });
    }
  );
  // #endif
};

onShow(async () => {
  let token = uni.getStorageSync("apiToken");
  if (token) {
    await Promise.allSettled([
      getTotalIntegral(),
      judgeLogin(),
      getUnreadNum(),
    ]);
  } else {
    integralAble.value = 0;
    myMsg.value = 0;
    userInformation.value = {};
  }
});
onPullDownRefresh(() => {
  let token = uni.getStorageSync("apiToken");
  if (!token) {
    uni.stopPullDownRefresh();
  } else {
    Promise.allSettled([
      getTotalIntegral(),
      judgeLogin(),
      getUnreadNum(),
    ]).finally(() => {
      uni.stopPullDownRefresh();
    });
  }
});
</script>

<style scoped lang="scss">
.pc {
  min-height: 100vh;
  // background-color: #f7f7f7;
  background: linear-gradient(0deg, #f4f4f4 55%, #ffb700) no-repeat;
}

.pc-header {
  padding: 0 24rpx 24rpx;
  box-sizing: border-box;
}

.pc-nav-right {
  display: flex;
  align-items: center;
  // gap: 22rpx;
}

.pc-nav-icon {
  position: relative;
  // width: 56rpx;
  // height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.pc-nav-badge {
  position: absolute;
  right: -6rpx;
  top: -6rpx;
  min-width: 28rpx;
  height: 28rpx;
  padding: 0 8rpx;
  box-sizing: border-box;
  background: #ff3b30;
  border-radius: 999rpx;
  color: #ffffff;
  font-size: 20rpx;
  font-weight: 700;
  line-height: 28rpx;
  text-align: center;
  border: 2rpx solid rgba(255, 255, 255, 0.85);
}

.pc-user {
  // margin-top: 24rpx;
  // padding: 10rpx 0;
}

.pc-user-left {
  flex: 1;
  min-width: 0;
}

.pc-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(255, 255, 255, 0.95);
  flex-shrink: 0;
}

.pc-user-info {
  margin-left: 20rpx;
  flex: 1;
  min-width: 0;
}

.pc-user-name {
  font-size: 44rpx;
  font-weight: 800;
  color: #1a1a1a;
  line-height: 1.2;
}

.pc-user-phone {
  margin-top: 14rpx;
  display: inline-flex;
  align-items: center;
  padding: 6rpx 18rpx;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 999rpx;
}

.pc-user-phone-icon {
  width: 26rpx;
  height: 26rpx;
  flex-shrink: 0;
}

.pc-user-phone-text {
  margin-left: 10rpx;
  font-size: 26rpx;
  color: #1a1a1a;
}

.pc-assets {
  margin-top: 26rpx;
}

.pc-assets-card {
  width: 329rpx;
  min-height: 176rpx;
  // background: rgba(255, 255, 255, 0.88);
  border-radius: 10rpx;
  padding: 24rpx 26rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  // justify-content: center;
  background-size: 100% 100%;
  // background-position: center;
  background-repeat: no-repeat;
}

.pc-assets-card + .pc-assets-card {
  margin-left: 18rpx;
}

.pc-assets-value {
  font-size: 43rpx;
  font-weight: 700;
  color: #ff6a00;
  line-height: 1.1;
  .unit{
    font-size: 26rpx;
    font-weight: 400;
  }
}

.pc-assets-label {
  margin-top: 12rpx;
  font-size: 26rpx;
  color: #1a1a1a;
}

.pc-body {
  padding: 24rpx;
  box-sizing: border-box;
}

.pc-card {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 28rpx 24rpx;
  box-sizing: border-box;
}

.pc-card + .pc-card {
  margin-top: 24rpx;
}

.pc-card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.pc-card-title {
  font-size: 30rpx;
  font-weight: 700;
  color: #1a1a1a;
}

.pc-card-more {
  font-size: 26rpx;
  color: #999999;
}

.pc-order-grid {
  margin-top: 22rpx;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10rpx;
}

.pc-order-item {
  text-align: center;
}

.pc-order-icon {
  width: 56rpx;
  height: 56rpx;
}

.pc-order-text {
  margin-top: 14rpx;
  font-size: 24rpx;
  color: #1a1a1a;
}

.pc-tool-grid {
  margin-top: 26rpx;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10rpx;
}

.pc-tool-item {
  text-align: center;
}

.pc-tool-btn {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: transparent;
  padding: 0;
  border: 0;
  line-height: initial;
}

.pc-tool-btn:after {
  border: none;
}

.pc-tool-icon {
  width: 56rpx;
  height: 56rpx;
}

.pc-tool-text {
  margin-top: 14rpx;
  margin-bottom: 22rpx;
  font-size: 26rpx;
  color: #1a1a1a;
}
</style>
