<template>
  <view class="app-container">
    <view class="container-mine">
      <uv-navbar
        title="个人中心"
        placeholder
        :bgColor="tabBg"
        leftIconSize="0"
        titleStyle="font-weight: 700;"
      />
      <view class="mine-top u-flex-center-sb">
        <view
          class="mine-top-user u-flex-center"
          @click.stop="goJump('/pages/setup/edit', true)"
        >
          <!-- src="/personalCenter/avatar.png" -->
          <image
            v-if="userInformation && userInformation.headPhoto"
            :src="userInformation.headPhoto"
            alt=""
            class="top-user-avatar"
          />
          <image
            class="top-user-avatar"
            v-else
            :src="$defaultAvatar"
            mode=""
          ></image>
          <view class="top-user-info" v-if="userInformation.id">
            <view class="top-user-name">{{ userInformation.nickname }}</view>
            <view class="top-user-phone u-flex-center">
              <image
                class="top-user-phone-img"
                :src="$handleImageUrl('/personalCenter/icon_phone.png')"
                alt=""
              />
              <text>{{ userInformation.mobile }}</text>
            </view>
          </view>
          <view class="top-user-info" v-else>
            <view class="top-user-name">登录/注册</view>
          </view>
        </view>
        <view
          class="mine-top-QRcode"
          v-if="userInformation.id"
          @click="showMembershipCode"
        >
          <image
            :src="$handleImageUrl('/personalCenter/icon_QR.png')"
            alt=""
            class="top-QRcode-img"
          />
          <view class="top-QRcode-text">会员码</view>
        </view>
      </view>
      <view class="mine-content">
        <view class="mine-content-item u-flex-center-sb">
          <view class="mine-content-item-view" @click="goToMyWallet">
            <image
              :src="$handleImageUrl('/personalCenter/bg_icon2.png')"
              alt=""
              class="mine-content-item-img"
            />
            <view class="mine-content-item-view">
              <view class="mine-content-item-title">我的余额</view>
              <view class="mine-content-item-value">{{
                $addDecimals(userInformation.balance || 0, 2)
              }}</view>
              <view class="mine-content-item-unit">元</view>
            </view>
          </view>
          <view class="mine-content-item-view" @click="goMypoints">
            <image
              :src="$handleImageUrl('/personalCenter/bg_icon1.png')"
              alt=""
              class="mine-content-item-img"
            />
            <view class="mine-content-item-view">
              <view class="mine-content-item-title">我的积分</view>
              <view class="mine-content-item-value">{{
                integralAble || 0
              }}</view>
              <view class="mine-content-item-unit">积分</view>
            </view>
          </view>
        </view>
        <view class="mine-content-order">
          <view class="mine-content-order-title">我的订单</view>
          <view class="mine-content-order-list">
            <view
              class="mine-content-order-item"
              @click.stop="goJump('/pages/order/mallOrder/orderList', true)"
            >
              <image
                class="mine-content-order-item-img1"
                :src="$handleImageUrl('/personalCenter/icon_mall.png')"
                alt=""
              />
              <view class="mine-content-order-item-title">商城订单</view>
            </view>
            <!-- <view class="order-item-line"> </view>
            <view
              class="mine-content-order-item"
              @click.stop="goJump('/pages/order/onlineOrder/list', true)"
            >
              <image
                class="mine-content-order-item-img1"
                :src="$handleImageUrl('/personalCenter/icon_online.png')"
                alt=""
              />
              <view class="mine-content-order-item-title">在线订单</view>
            </view>
            <view class="order-item-line"> </view>
            <view
              class="mine-content-order-item"
              @click.stop="goJump('/pages/order/queuingOrders/list', true)"
            >
              <image
                class="mine-content-order-item-img2"
                :src="$handleImageUrl('/personalCenter/icon_queue.png')"
                alt=""
              />
              <view class="mine-content-order-item-title">排队订单</view>
            </view> -->
          </view>
        </view>
      </view>
      <view class="app-center">
        <view class="app-center-title">
          <text>应用中心</text>
        </view>
        <view class="app-center-list">
          <view
            class="app-center-item"
            v-for="(item, index) in toolsList"
            :key="index"
            @click.stop="goSublevelPage(item)"
          >
            <template v-if="item.key == 'kf'">
              <!-- #ifdef MP-WEIXIN -->
              <button open-type="contact" class="app-center-item-button">
                <image
                  :src="$handleImageUrl(item.icon)"
                  alt=""
                  class="app-center-item-img"
                />
                <view class="app-center-item-text">{{ item.label }}</view>
              </button>
              <!-- #endif -->
              <!-- #ifndef MP-WEIXIN -->
              <image
                :src="$handleImageUrl(item.icon)"
                alt=""
                class="app-center-item-img"
              />
              <view class="app-center-item-text">{{ item.label }}</view>
              <!-- #endif -->
            </template>
            <template v-else>
              <image
                :src="$handleImageUrl(item.icon)"
                alt=""
                class="app-center-item-img"
              />
              <view class="app-center-item-text">{{ item.label }}</view>
            </template>
          </view>
        </view>
      </view>

      <!-- 商家工作台 -->
      <image
        v-if="shopInfo.businessId && shopInfo.shelvedStatus"
        @click.stop="
          goSublevelPage({
            url: '/pages/shop/content/index',
            idNeedLogin: true,
          })
        "
        :src="$handleImageUrl('/personalCenter/img_workbench.png')"
        class="workbench"
        alt=""
      />
    </view>

    <!-- 会员码 -->
    <membershipCode ref="membershipCodeRef" />
  </view>
</template>
<script setup>
import { ref } from "vue";
import {
  onLoad,
  onShow,
  onPullDownRefresh,
  onPageScroll,
} from "@dcloudio/uni-app";

import { userInfo } from "@/api/login.js";
import {
  messageUnreadNum_Api,
  totalIntegral_Api,
  businessUserInfo_Api,
} from "@/api/userInfo.js";
import utils from "@/util/index.js";
const membershipCodeRef = ref(null);
const userInformation = ref({});
const myMsg = ref(0);
const shopInfo = ref({}); // 商家信息
const integralAble = ref(0); // 用户积分数据

const toolsList = ref([
  {
    label: "我的拼团",
    icon: "/personalCenter/app_icon1.png",
    url: "/pages/groupBuying/myGbOrder/list",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "分销中心",
    icon: "/personalCenter/app_icon1.png",
    url: "/pages/distribution/index",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "收货地址",
    icon: "/personalCenter/app_icon1.png",
    url: "/pages/user/address/addressList?formType=mine",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "个人信息",
    icon: "/personalCenter/app_icon2.png",
    url: "/pages/setup/edit",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "我的优惠券",
    icon: "/personalCenter/app_icon3.png",
    url: "/pages/couponCenter/index?isMyCoupon=true",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "优惠券中心",
    icon: "/personalCenter/app_icon12.png",
    url: "/pages/couponCenter/index",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "我的收藏",
    icon: "/personalCenter/app_icon4.png",
    url: "/pages/user/collection",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "商家入驻",
    icon: "/personalCenter/app_icon5.png",
    url: "/pages/user/merchant/settleIn?type=tenants_agreement",
    idNeedLogin: true,
    isPage: true,
  },
  // {
  //   label: "代理中心",
  //   icon: "/personalCenter/app_icon6.png",
  //   url: "/pages/agencyCenter/index",
  //   idNeedLogin: true,
  //   isPage: true,
  //   isAgent: true, // 是否为代理商才显示
  // },
  {
    label: "官方客服",
    icon: "/personalCenter/app_icon7.png",
    url: "",
    key: "kf",
    idNeedLogin: false,
    isPage: false,
  },
  {
    label: "常见问题",
    icon: "/personalCenter/app_icon8.png",
    url: "/pages/user/faq",
    idNeedLogin: false,
    isPage: true,
  },
  {
    label: "消息通知",
    icon: "/personalCenter/app_icon9.png",
    url: "/pages/user/myMsg",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "投诉建议",
    icon: "/personalCenter/app_icon10.png",
    url: "/pages/set/feedback/index",
    idNeedLogin: true,
    isPage: true,
  },
  {
    label: "设置",
    icon: "/personalCenter/app_icon11.png",
    url: "/pages/set/index",
    idNeedLogin: true,
    isPage: true,
  },
]);

const isSign = ref(false);
const tabBg = ref("none");
onPageScroll((e) => {
  // console.log(e.scrollTop)
  if (e.scrollTop > 10) {
    tabBg.value = "#ffffff";
  } else {
    tabBg.value = "none";
  }
});
// 获取商家信息
const getbusinessUserInfo = () => {
  businessUserInfo_Api().then((res) => {
    if (res && res.code == 200) {
      shopInfo.value = res.data || {};
    }
  });
};

// 跳转我的积分
function goMypoints() {
  if (!utils.isLoginTo(true)) {
    uni.navigateTo({
      url: "/pages/user/pointsList",
    });
  }
}

async function getAll() {
  await judgeLogin(); //判断是否登录
  if (utils.isLoginTo(true)) {
    getTotalIntegral();
    getbusinessUserInfo();
    await getUnreadNum(); //未读消息
    await getMyStatistics(); //登录消息
    uni.$forceUpdate();
  }
}
//获取未读消息
function getUnreadNum() {
  messageUnreadNum_Api()
    .then((res) => {
      uni.stopPullDownRefresh();
      if (res && res.code == 200) {
        myMsg.value = res.data || 0;
      } else {
        myMsg.value = 0;
      }
    })
    .catch((err) => {
      myMsg.value = 0;
    });
}

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

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

// 跳转子级页面
const goSublevelPage = (item) => {
  if (item.idNeedLogin) {
    let url = item.url;
    if (item.isAgent && !userInformation.value.isAgent) {
      url = "/pages/agencyCenter/regionalAgent";
    }
    if (!utils.isLoginTo()) {
      uni.navigateTo({
        url,
      });
    } else {
      uni.$uv.toast("请先登录");
    }
  } else {
    if (item.key == "kf") {
      customerService();
    } else {
      uni.navigateTo({
        url: item.url,
      });
    }
  }
};

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

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

// 显示会员码
const showMembershipCode = () => {
  membershipCodeRef.value.open();
};

// 客服
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
};

onLoad(() => {});
//清空数据
//显示弹出框
onShow(async () => {
  let token = uni.getStorageSync("apiToken");
  if (token) {
    getTotalIntegral();
    getbusinessUserInfo();
    await judgeLogin()
      .then((res) => {
        // console.log('judgeLogin = res', res)
      })
      .catch((err) => {});
    await getUnreadNum();
  } else {
    integralAble.value = 0;
    shopInfo.value = {};
    myMsg.value = 0;
    userInformation.value = {};
    isSign.value = false;
    // uni.setStorageSync("personal", '');
  }
});
onPullDownRefresh(() => {
  let token = uni.getStorageSync("apiToken");
  if (!token) {
    uni.stopPullDownRefresh();
  } else {
    getAll();
  }
});
</script>

<style scoped lang="scss">
.app-container {
  background-color: #f7f8fa;
}

.container-mine {
  min-height: 100vh;
  box-sizing: border-box;
  padding: 23rpx;
  // background: url("/personalCenter/bg_icon.png");
  // 背景图片
  background: url("http://sly2020.oss-cn-beijing.aliyuncs.com/2025/11/25/040000f4d9254462bd559f27181bb7db.png");
  background-size: 100% 742rpx;
  background-repeat: no-repeat;

  .mine-top {
    padding-right: 60rpx;

    .mine-top-user {
      flex: 1;

      .top-user-avatar {
        width: 140rpx;
        height: 140rpx;
        border: 4rpx solid #ffffff;
        border-radius: 50%;
        flex-shrink: 0;
      }

      .top-user-info {
        margin-left: 20rpx;
        flex: 1;

        .top-user-name {
          font-size: 50rpx;
          color: #1a1a1a;
          font-weight: 700;
        }

        .top-user-phone {
          margin-top: 10rpx;

          .top-user-phone-img {
            width: 26rpx;
            height: 26rpx;
          }

          text {
            font-size: 28rpx;
            color: #1a1a1a;
          }
        }
      }
    }

    .mine-top-QRcode {
      flex-shrink: 0;
      margin-left: 20rpx;
      text-align: center;

      .top-QRcode-img {
        width: 57rpx;
        height: 57rpx;
        border-radius: 10rpx;
        margin: 0;
      }

      .top-QRcode-text {
        font-size: 24rpx;
        color: #1a1a1a;
        // margin-top: 10rpx;
      }
    }
  }

  .mine-content {
    margin-top: 30rpx;
    min-height: 447rpx;
    // opacity: 0.71;
    background: linear-gradient(180deg, #ffd0cc, #fbf3f3);
    border-radius: 20rpx;
    padding: 30rpx 24rpx;
    box-sizing: border-box;

    .mine-content-item {
      // background: #ffffff;
      border-radius: 20px;

      .mine-content-item-view {
        position: relative;
        width: 318rpx;
        height: 180rpx;

        .mine-content-item-img {
          position: absolute;
          left: 0;
          top: 0;
          width: 318rpx;
          height: 180rpx;
          z-index: 1;
        }

        .mine-content-item-view {
          position: relative;
          z-index: 2;
          display: flex;
          flex-direction: column;
          // align-items: center;
          justify-content: space-between;
          padding: 10rpx 20rpx 14rpx 20rpx;
          box-sizing: border-box;

          .mine-content-item-title {
            font-size: 30rpx;
            font-weight: 700;
            color: #1a1a1a;
          }

          .mine-content-item-value {
            font-size: 40rpx;
            font-weight: normal;
            color: #da4f4f;
          }

          .mine-content-item-unit {
            font-size: 28rpx;
            color: #666666;
          }
        }
      }
    }

    .mine-content-order {
      margin-top: 40rpx;

      .mine-content-order-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #1a1a1a;
        margin-bottom: 15rpx;
      }

      .mine-content-order-list {
        display: flex;
        justify-content: space-around;
        align-items: center;

        .order-item-line {
          width: 1rpx;
          height: 85rpx;
          background: #e1d7d7;
        }

        .mine-content-order-item {
          text-align: center;

          .mine-content-order-item-img1 {
            width: 60rpx;
            height: 58rpx;
          }

          .mine-content-order-item-img2 {
            width: 48rpx;
            height: 58rpx;
          }

          .mine-content-order-item-title {
            margin-top: 13rpx;
            font-size: 24rpx;
            font-weight: 400;
            color: #1a1a1a;
          }
        }
      }
    }
  }

  .app-center {
    margin-top: 30rpx;
    padding: 38rpx 24rpx 12rpx 24rpx;
    box-sizing: border-box;
    min-height: 468rpx;
    background: #ffffff;
    border-radius: 20rpx;

    .app-center-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #1a1a1a;
      margin-bottom: 34rpx;
    }

    .app-center-list {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      /* 创建4列，每列占据可用空间 */
      gap: 10rpx;
      /* 可选，设置网格之间的间隔 */
      text-align: center;

      .app-center-item-button {
        line-height: initial;
        background-color: #ffffff !important;
        border: 1rpx solid #ffffff !important;
        padding: 0;
        &:after {
          border: none !important;
        }
      }

      .app-center-item-img {
        width: 47rpx;
        height: 47rpx;
      }

      .app-center-item-text {
        font-size: 26rpx;
        font-weight: 400;
        color: #1a1a1a;
        margin-top: 10rpx;
        margin-bottom: 26rpx;
      }
    }
  }

  .workbench {
    width: 704rpx;
    height: 197rpx;
    border-radius: 20rpx;
    margin-top: 30rpx;
  }
}
</style>
