<script setup lang="ts">
import { ref, reactive, onMounted, watch, h } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElTag } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import QRCode from "qrcode";
import {
  getDistributorDetail,
  getReferralList,
  getCommissionList
} from "@/api/distribution";
import type { PaginationProps } from "@pureadmin/table";
import {
  initPagination,
  handlePageSizeChange,
  handleCurrentPageChange,
  updatePaginationData
} from "@/utils/paginationHelper";
import type { Distributor, Referral, Commission } from "../utils/types";

defineOptions({
  name: "DistributorDetail"
});

const route = useRoute();
const router = useRouter();

const loading = ref(false);
const detail = ref<Distributor | null>(null);
const qrcodeDataUrl = ref<string>("");

const statusMap: Record<number, { text: string; type: "success" | "warning" | "danger" | "info" | "primary" }> = {
  0: { text: "待激活", type: "info" },
  1: { text: "已激活", type: "success" },
  2: { text: "已停用", type: "danger" }
};

const referralLoading = ref(false);
const referralList = ref<Referral[]>([]);
const referralPagination = reactive<PaginationProps>(initPagination());

const referralStatusMap: Record<number, { text: string; type: "success" | "warning" | "danger" | "info" | "primary" }> = {
  0: { text: "待生效", type: "info" },
  1: { text: "已生效", type: "success" },
  2: { text: "已失效", type: "danger" }
};

const referralColumns = [
  { label: "用户ID", prop: "userId", width: 80 },
  { label: "用户名", prop: "userName", minWidth: 120 },
  {
    label: "状态",
    prop: "status",
    minWidth: 100,
    cellRenderer: ({ row }) => {
      const item = referralStatusMap[row.status] || {
        text: "未知",
        type: "info"
      };
      return h(ElTag, { type: item.type as any }, () => item.text);
    }
  },
  {
    label: "首单金额",
    prop: "firstOrderAmount",
    minWidth: 120,
    formatter: ({ firstOrderAmount }) =>
      firstOrderAmount !== undefined && firstOrderAmount !== null
        ? `¥${firstOrderAmount.toFixed(2)}`
        : "-"
  },
  {
    label: "首单时间",
    prop: "firstOrderTime",
    minWidth: 160,
    formatter: ({ firstOrderTime }) => firstOrderTime || "-"
  },
  {
    label: "生效时间",
    prop: "effectiveTime",
    minWidth: 160,
    formatter: ({ effectiveTime }) => effectiveTime || "-"
  },
  {
    label: "创建时间",
    prop: "createTime",
    minWidth: 160,
    formatter: ({ createTime }) => createTime || "-"
  }
];

const commissionLoading = ref(false);
const commissionList = ref<Commission[]>([]);
const commissionPagination = reactive<PaginationProps>(initPagination());

const commissionStatusMap: Record<number, { text: string; type: "success" | "warning" | "danger" | "info" | "primary" }> = {
  0: { text: "待结算", type: "info" },
  1: { text: "已结算", type: "success" },
  2: { text: "已冻结", type: "warning" }
};

const commissionColumns = [
  { label: "用户ID", prop: "userId", width: 80 },
  { label: "用户名", prop: "userName", minWidth: 120 },
  {
    label: "佣金类型",
    prop: "commissionTypeLabel",
    minWidth: 100
  },
  {
    label: "佣金金额",
    prop: "amount",
    minWidth: 120,
    formatter: ({ amount }) =>
      amount !== undefined && amount !== null
        ? `¥${amount.toFixed(2)}`
        : "¥0.00"
  },
  {
    label: "订单金额",
    prop: "orderAmount",
    minWidth: 120,
    formatter: ({ orderAmount }) =>
      orderAmount !== undefined && orderAmount !== null
        ? `¥${orderAmount.toFixed(2)}`
        : "¥0.00"
  },
  {
    label: "佣金比例",
    prop: "rate",
    minWidth: 100,
    formatter: ({ rate }) =>
      rate !== undefined && rate !== null ? `${(rate * 100).toFixed(1)}%` : "-"
  },
  {
    label: "状态",
    prop: "status",
    minWidth: 100,
    cellRenderer: ({ row }) => {
      const item = commissionStatusMap[row.status] || {
        text: "未知",
        type: "info"
      };
      return h(ElTag, { type: item.type as any }, () => item.text);
    }
  },
  {
    label: "创建时间",
    prop: "createTime",
    minWidth: 160,
    formatter: ({ createTime }) => createTime || "-"
  }
];

const activeTab = ref("referral");

async function generateQrcodeDataUrl(content: string) {
  if (!content) {
    qrcodeDataUrl.value = "";
    return;
  }
  try {
    qrcodeDataUrl.value = await QRCode.toDataURL(content, {
      width: 200,
      margin: 2,
      color: {
        dark: "#000000",
        light: "#ffffff"
      }
    });
  } catch (error) {
    console.error("生成二维码失败:", error);
    qrcodeDataUrl.value = "";
  }
}

watch(detail, (newVal) => {
  if (newVal?.qrcodeContent) {
    generateQrcodeDataUrl(newVal.qrcodeContent);
  } else {
    qrcodeDataUrl.value = "";
  }
});

async function fetchDetail() {
  const id = route.query.id as string;
  if (!id) {
    ElMessage.warning("缺少分销员ID参数");
    return;
  }
  loading.value = true;
  try {
    const res = await getDistributorDetail(id);
    if (res && res.data) {
      detail.value = res.data;
    } else {
      ElMessage.error("获取分销员详情失败");
    }
  } catch (error) {
    console.error("获取分销员详情失败:", error);
    ElMessage.error("获取分销员详情失败");
  } finally {
    loading.value = false;
  }
}

async function fetchReferralList() {
  const id = route.query.id as string;
  if (!id) return;
  referralLoading.value = true;
  try {
    const res = await getReferralList({
      distributorId: id,
      page: referralPagination.currentPage,
      pageSize: referralPagination.pageSize
    });
    if (res && res.data) {
      referralList.value = res.data.list || [];
      updatePaginationData(referralPagination, res.data);
    }
  } finally {
    referralLoading.value = false;
  }
}

async function fetchCommissionList() {
  const id = route.query.id as string;
  if (!id) return;
  commissionLoading.value = true;
  try {
    const res = await getCommissionList({
      distributorId: id,
      page: commissionPagination.currentPage,
      pageSize: commissionPagination.pageSize
    });
    if (res && res.data) {
      commissionList.value = res.data.list || [];
      updatePaginationData(commissionPagination, res.data);
    }
  } finally {
    commissionLoading.value = false;
  }
}

function handleDownloadQrcode() {
  if (!qrcodeDataUrl.value) {
    ElMessage.warning("该分销员尚未生成二维码");
    return;
  }
  try {
    const link = document.createElement("a");
    link.href = qrcodeDataUrl.value;
    link.download = `${detail.value?.name || detail.value?.code}_qrcode.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success("下载成功");
  } catch {
    ElMessage.error("下载失败");
  }
}

function handleTabChange(tab: string) {
  if (tab === "referral") {
    fetchReferralList();
  } else if (tab === "commission") {
    fetchCommissionList();
  }
}

function handleReferralSizeChange(val: number) {
  handlePageSizeChange(val, referralPagination, fetchReferralList);
}

function handleReferralCurrentChange(val: number) {
  handleCurrentPageChange(val, referralPagination, fetchReferralList);
}

function handleCommissionSizeChange(val: number) {
  handlePageSizeChange(val, commissionPagination, fetchCommissionList);
}

function handleCommissionCurrentChange(val: number) {
  handleCurrentPageChange(val, commissionPagination, fetchCommissionList);
}

function goBack() {
  router.push("/distribution/distributor");
}

onMounted(() => {
  fetchDetail();
  fetchReferralList();
});
</script>

<template>
  <div class="distributor-detail" v-loading="loading">
    <div class="detail-header">
      <el-button :icon="ArrowLeft" @click="goBack">返回列表</el-button>
      <span class="header-title">分销员详情</span>
    </div>

    <template v-if="detail">
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="姓名">
            {{ detail.name }}
          </el-descriptions-item>
          <el-descriptions-item label="分销员编码">
            {{ detail.code }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ detail.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusMap[detail.status]?.type">
              {{ statusMap[detail.status]?.text || "未知" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ detail.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ detail.remark || "-" }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>推广二维码</span>
            <div v-if="qrcodeDataUrl" class="card-header-actions">
              <el-button size="small" @click="handleDownloadQrcode">
                下载二维码
              </el-button>
            </div>
          </div>
        </template>
        <div class="qrcode-area">
          <template v-if="qrcodeDataUrl">
            <div class="qrcode-container">
              <el-image
                :src="qrcodeDataUrl"
                fit="contain"
                class="qrcode-image"
                :preview-src-list="[qrcodeDataUrl]"
              />
              <div class="qrcode-content">
                <el-text type="info" size="small">{{ detail.qrcodeContent }}</el-text>
              </div>
            </div>
          </template>
          <div v-else class="qrcode-empty">
            <el-empty description="暂无二维码，请在列表页生成" :image-size="80" />
          </div>
        </div>
      </el-card>

      <div class="stats-grid">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-item">
            <div class="stat-value">{{ detail.totalReferrals || 0 }}</div>
            <div class="stat-label">总推荐数</div>
          </div>
        </el-card>
        <el-card class="stat-card" shadow="hover">
          <div class="stat-item">
            <div class="stat-value">{{ detail.validReferrals || 0 }}</div>
            <div class="stat-label">有效推荐数</div>
          </div>
        </el-card>
        <el-card class="stat-card stat-card--primary" shadow="hover">
          <div class="stat-item">
            <div class="stat-value">
              ¥{{ detail.commissionBalance?.toFixed(2) || "0.00" }}
            </div>
            <div class="stat-label">佣金余额</div>
          </div>
        </el-card>
        <el-card class="stat-card stat-card--warning" shadow="hover">
          <div class="stat-item">
            <div class="stat-value">
              ¥{{ detail.frozenAmount?.toFixed(2) || "0.00" }}
            </div>
            <div class="stat-label">冻结金额</div>
          </div>
        </el-card>
        <el-card class="stat-card stat-card--success" shadow="hover">
          <div class="stat-item">
            <div class="stat-value">
              ¥{{ detail.totalCommission?.toFixed(2) || "0.00" }}
            </div>
            <div class="stat-label">累计佣金</div>
          </div>
        </el-card>
        <el-card class="stat-card" shadow="hover">
          <div class="stat-item">
            <div class="stat-value">
              ¥{{ detail.totalWithdrawn?.toFixed(2) || "0.00" }}
            </div>
            <div class="stat-label">已提现金额</div>
          </div>
        </el-card>
      </div>

      <el-card class="detail-card" shadow="never">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="推荐用户列表" name="referral">
            <pure-table
              align-whole="center"
              showOverflowTooltip
              table-layout="auto"
              :loading="referralLoading"
              :data="referralList"
              :columns="referralColumns"
              :pagination="referralPagination"
              @page-size-change="handleReferralSizeChange"
              @page-current-change="handleReferralCurrentChange"
            />
          </el-tab-pane>

          <el-tab-pane label="佣金记录列表" name="commission">
            <pure-table
              align-whole="center"
              showOverflowTooltip
              table-layout="auto"
              :loading="commissionLoading"
              :data="commissionList"
              :columns="commissionColumns"
              :pagination="commissionPagination"
              @page-size-change="handleCommissionSizeChange"
              @page-current-change="handleCommissionCurrentChange"
            />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </template>
    <template v-else-if="!loading">
      <el-empty description="分销员信息加载失败，请返回列表重试" />
    </template>
  </div>
</template>

<style lang="scss" scoped>
.distributor-detail {
  padding: 16px;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .header-title {
    margin-left: 12px;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.detail-card {
  margin-bottom: 16px;

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      font-size: 16px;
      font-weight: 600;
    }

    .card-header-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.qrcode-area {
  display: flex;
  justify-content: center;
  padding: 20px;

  .qrcode-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
  }

  .qrcode-image {
    width: 200px;
    height: 200px;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
  }

  .qrcode-content {
    max-width: 300px;
    text-align: center;
    word-break: break-all;
  }

  .qrcode-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 200px;
    height: 200px;
    border: 1px dashed var(--el-border-color);
    border-radius: 8px;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 16px;
  margin-bottom: 16px;

  @media (max-width: 1200px) {
    grid-template-columns: repeat(3, 1fr);
  }

  @media (max-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.stat-card {
  text-align: center;

  .stat-item {
    padding: 12px 0;
  }

  .stat-value {
    font-size: 24px;
    font-weight: 700;
    color: var(--el-text-color-primary);
    margin-bottom: 8px;
  }

  .stat-label {
    font-size: 13px;
    color: var(--el-text-color-secondary);
  }

  &.stat-card--primary {
    .stat-value {
      color: var(--el-color-primary);
    }
  }

  &.stat-card--warning {
    .stat-value {
      color: var(--el-color-warning);
    }
  }

  &.stat-card--success {
    .stat-value {
      color: var(--el-color-success);
    }
  }
}
</style>
