<template>
  <uv-navbar :fixed="false" title="分销中心" left-arrow @leftClick="$onClickLeft" />
  <view class="page flex-col" v-if="isDistributor">
    <!-- 头部导航 -->
    <view class="flex-col">
      <!-- <view class="flex-row">
        <view class="flex-row">
          <text class="header-title">分销中心</text>
        </view>
      </view> -->

      <!-- 用户信息 -->
      <view class="user-info">
        <image class="avatar" :src="userAvatar" mode="aspectFill"></image>
        <view class="user-detail">
          <view class="flex-row" style="align-items: center">
            <text class="username">Hi,{{ userName }}</text>
          </view>
          <view class="flex-row" style="align-items: center">
            <text class="user-id">ID: {{ userId }}</text>
            <text class="invite-code" @tap="showInviteCodePopup">邀请码</text>
          </view>
        </view>
        <button class="share-btn" open-type="share" hover-class="none">
          <image class="share-icon" src="/static/images/share.png" mode="aspectFill"></image>
          <text class="share-text">分享</text>
        </button>
      </view>
    </view>

    <!-- 佣金统计 -->
    <view class="commission-box flex-col">
      <view class="flex-row">
        <view class="commission-item">
          <text class="commission-label">累计佣金(元)</text>
          <view>
            <text class="commission-value">{{ totalCommission }}</text>
          </view>
        </view>

        <view class="commission-item">
          <text class="commission-label">分销订单(笔)</text>
          <view>
            <text class="commission-value">{{ orderCount }}</text>
          </view>
        </view>
      </view>

      <!-- 申请分销商按钮 -->
      <!-- <view class="apply-btn" @tap="goToApplyForm">
        <text>申请成为分销商</text>
      </view> -->
    </view>

    <!-- 佣金明细 -->
    <view class="details-list flex-col">
      <view class="details-title">
        <text>佣金明细 </text>
        <text style="margin-top: 6rpx; font-size: 22rpx; color: #999999">（佣金将于每月15日结算至您的银行卡账号中）</text>
      </view>

      <!-- 佣金明细列表 -->
      <view v-if="commissionList.length > 0">
        <view v-for="(item, index) in commissionList" :key="index" class="detail-item" @tap="addCommission">
          <view class="detail-left">
            <image class="user-avatar" :src="item.avatar" mode="aspectFill"></image>
            <view class="detail-info">
              <text class="detail-name">{{ item.name }}</text>
              <text class="detail-date">下单日期: {{ item.date }}</text>
              <text class="detail-date">结算时间: {{ item.commissionTime }}</text>
            </view>
          </view>
          <view class="detail-amount">
            <text class="add-icon" v-if="item.refundStatus !== 2">+</text>
            <text v-if="item.refundStatus !== 2">{{ item.amount }}</text>
            <text v-else class="refund-text">已退款</text>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-box">
        <!-- <image
          class="empty-icon"
          src="/static/images/empty-commission.png"
          mode="aspectFill"
        ></image> -->
        <text class="empty-text">暂无佣金明细</text>
      </view>
    </view>

    <!-- 邀请码弹窗 -->
    <view class="invite-popup-mask" v-if="showInvitePopup" @tap="closeInviteCodePopup">
      <view class="invite-popup-content" @tap.stop>
        <view class="invite-popup-box">
          <image class="invite-popup-avatar" :src="userAvatar" mode="aspectFill"></image>
          <view class="invite-popup-id">分销员ID: {{ userId }}</view>
          <view class="invite-popup-qrcode-container">
            <uv-qrcode ref="qrcode" canvas-id="qrcode" :value="qrcodeValue" :size="200" background-color="#FFFFFF"
              foreground-color="#000000"></uv-qrcode>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useMainStore } from "@/store/store";
import { storeToRefs } from "pinia";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { getDistributorInfo, getCommissionList } from "@/api/distributor";

const main = useMainStore();
const { isLogin } = storeToRefs(main);

//是否是分销商
const isDistributor = ref(false);

// 用户信息
const userAvatar = ref("/static/images/avatar.png");
const userName = ref("爱喝汤的小力");
const userId = ref("1234567890");
const spreadUid = ref(""); // 新增分销员ID参数

// 佣金统计
const totalCommission = ref("0.00");
const orderCount = ref("1");

// 佣金明细列表
const commissionList = ref([
  {
    avatar: "/static/images/avatar.png",
    name: "VVV用户昵称",
    date: "2023-09-05 09:05:47",
    amount: "78.0",
  },
  {
    avatar: "/static/images/avatar.png",
    name: "VVV用户昵称",
    date: "2023-09-05 09:05:47",
    amount: "78.0",
  },
]);

// 邀请码弹窗控制
const showInvitePopup = ref(false);

// 页面加载
onLoad((options) => {
  uni.hideShareMenu();
  if (!isLogin.value) {
    uni.navigateTo({ url: "/pages/components/pages/login/login" });
  }

  // 获取传递的分销员ID参数
  if (options && options.spreadUid) {
    spreadUid.value = options.spreadUid;
    console.log("spreadUid:", spreadUid.value);
  }

  uni.showLoading({
    title: "加载中...",
  });
  getCommissionData();
  uni.hideLoading();

  setTimeout(() => {
    uni.$mpShare = shareData.value; // 分享配置
  }, 1000);
});

onShow(() => {
  setTimeout(() => {
    uni.$mpShare = shareData.value; // 分享配置
  }, 1000);
});

// 获取分销员数据
const getCommissionData = async () => {


  // 修改getDistributorInfo调用，传入spreadUid参数
  let data = await getDistributorInfo({ id: spreadUid.value });
  if (data) {
    isDistributor.value = true;
    userName.value = data.name || "爱喝汤的小力";
    userId.value = data.id || "1234567890";
    totalCommission.value = data.totalCommission || "0.00";
    // orderCount.value = data.orderCount || "0";
  }
  getOrderCommissionList();
};

//获取分销员的订单明细
const getOrderCommissionList = async () => {
  let data = await getCommissionList({ distributorId: userId.value, page: 1, limit: 10 });
  if (data) {

    commissionList.value = data.map(item => ({
      avatar: item.avatar || '/static/images/avatar.png',
      name: item.realName || '用户',
      date: formatDate(item.createTime) || '',  // 修改这里，使用formatDate函数格式化时间
      amount: item.commission || '0.00',
      refundStatus: item.refundStatus || 0,
      commissionTime: formatDate(item.commissionTime) || ''
    }));
    orderCount.value = data.length;
  }
};

// 格式化时间戳为日期字符串
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 添加佣金（演示用）
const addCommission = () => {
  // uni.showToast({
  //   title: "查看佣金详情",
  //   icon: "none",
  // });
};

// 跳转到分销商申请表单
const goToApplyForm = () => {
  uni.navigateTo({
    url: "/pages/components/pages/fenxiao/fenxiaorequestform",
  });
};

// 显示邀请码弹窗
const showInviteCodePopup = () => {
  showInvitePopup.value = true;
};

// 关闭邀请码弹窗
const closeInviteCodePopup = () => {
  showInvitePopup.value = false;
};

const qrcodeValue = computed(() => {
  return `https://www.aiyushantp.com/pages/menu/menu?distributorId=${userId.value}`;
});


// 分享配置

const shareData = computed(() => { // 分享的数据
  return {
    title: "爱愈膳汤铺",
    path: '/pages/menu/menu?distributorId=' + userId.value,
    imageUrl: "https://file.aiyushantp.com/file/b22aa4e4625714e2747b15cfa174ea2351e59df4bacec69d338f9c87c7dae5ca.png"
  }
})
// const onShareAppMessage = () => {
//   return {
//     title: '1111',
//     path: `/pages/menu/menu?distributorId=${userId.value}`,
//     imageUrl: "https://file.aiyushantp.com/file/b22aa4e4625714e2747b15cfa174ea2351e59df4bacec69d338f9c87c7dae5ca.png"
//   }
// };
// const onShareTimeline = () => {
//   return {
//     title: '11111',
//     path: `/pages/menu/menu?distributorId=${userId.value}`,
//     imageUrl: "https://file.aiyushantp.com/file/b22aa4e4625714e2747b15cfa174ea2351e59df4bacec69d338f9c87c7dae5ca.png"
//   }
// }
</script>

<style scoped>
@import "./common.css";

.apply-btn {
  background-color: #52ac41;
  border-radius: 30rpx;
  padding: 15rpx 0;
  margin: 20rpx 30rpx 0;
  text-align: center;
}

.apply-btn text {
  color: #ffffff;
  font-size: 28rpx;
  font-weight: 500;
}

/* 邀请码弹窗样式 */
.invite-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.invite-popup-content {
  width: 560rpx;
  max-width: 80%;
  padding: 0;
}

.invite-popup-box {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.invite-popup-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-bottom: 20rpx;
}

.invite-popup-id {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 30rpx;
}

.invite-popup-qrcode-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10rpx;
  padding: 20rpx;
}

.invite-popup-qrcode-container>>>.uqrcode {
  margin: 0 auto;
}

.refund-text {
  color: #ff0000;
  font-weight: bold;
  font-size: 28rpx;
}
</style>
