<template>
  <el-dialog v-model="dialogShow" title="尾款审核" draggable width="860px" @close="handleClose">
    <!-- 合并指标区域为一行 -->
    <div class="metrics-sections">
      <div class="metrics-section">
        <div class="section-header">预计指标</div>
        <div class="metrics-cards">
          <div class="metric-card">
            <div class="metric-label">GMV(元)</div>
            <div class="metric-value">
              {{ formatAmount(detailData.orderGmv) }}
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-label">播放量</div>
            <div class="metric-value">
              {{ detailData.orderPlayCount || 0 }}
            </div>
          </div>
        </div>
      </div>

      <div class="metrics-section">
        <div class="section-header">实际完成</div>
        <div class="metrics-cards">
          <div class="metric-card">
            <div class="metric-label">GMV(元)</div>
            <div class="metric-value">
              {{ formatAmount(detailData.actualGmv) }}
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-label">播放量</div>
            <div class="metric-value">
              {{ detailData.actualPlayCount || 0 }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 详情展示区域 -->
    <div class="review-container">
      <div class="review-detail">
        <el-descriptions :column="2" border>
          <!-- 第一列：重要信息 -->
          <el-descriptions-item label="套餐名称">
            {{ detailData.name }}
          </el-descriptions-item>
          <el-descriptions-item label="订单编号">
            {{ detailData.orderNo }}
          </el-descriptions-item>
          <el-descriptions-item label="达人ID">
            {{ detailData.expertId }}
          </el-descriptions-item>
          <el-descriptions-item label="达人昵称">
            {{ detailData.userName }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ detailData.realName }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ detailData.userPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证号码" :span="2">
            {{ detailData.idCard }}
          </el-descriptions-item>

          <!-- 第二列：财务信息 -->
          <el-descriptions-item label="订单金额(元)" :span="2">
            {{ formatAmount(detailData.orderMoney) }}
          </el-descriptions-item>
          <el-descriptions-item label="尾款比例"> {{ detailData.endPaymentRate || 0 }}% </el-descriptions-item>
          <el-descriptions-item label="尾款(元)">
            {{ formatAmount(detailData.endPayment) }}
          </el-descriptions-item>
          <el-descriptions-item label="预付款比例"> {{ detailData.advanceRate || 0 }}% </el-descriptions-item>
          <el-descriptions-item label="预付款(元)">
            {{ formatAmount(detailData.advance) }}
          </el-descriptions-item>
          <el-descriptions-item label="佣金比例"> {{ detailData.commissionRate || 0 }}% </el-descriptions-item>
          <el-descriptions-item label="佣金(元)">
            {{ formatAmount(detailData.commission) }}
          </el-descriptions-item>

          <!-- 底部重要信息 -->
          <el-descriptions-item label="推广模块" :span="2">
            <el-tag
              v-for="(item, index) in getPromoteTypes(detailData.promoteType)"
              :key="index"
              style="margin-right: 5px; margin-bottom: 5px"
            >
              {{ item }}
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="状态" :span="2">
            <el-tag v-if="detailData.advancePaymentStatus == 0" type="success"> 审核通过 </el-tag>
            <el-tag v-if="detailData.advancePaymentStatus == 1" type="success"> 待完成 </el-tag>
            <el-tag v-if="detailData.advancePaymentStatus == 2" type="primary"> 已完成 </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="下单时间">
            {{ detailData.orderTime || "--" }}
          </el-descriptions-item>
          <el-descriptions-item label="支付时间">
            {{ detailData.payTime || "--" }}
          </el-descriptions-item>
          <el-descriptions-item label="完成时间" v-if="detailData.completeTime">
            {{ detailData.completeTime }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间" v-if="detailData.endFundsTime">
            {{ detailData.endFundsTime }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button type="success" @click="confirmApprove"> 同意 </el-button>
        <el-button type="warning" @click="openRejectDialog"> 驳回 </el-button>
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>

    <!-- 驳回原因弹窗 -->
    <el-dialog title="驳回原因" v-model="rejectDialogVisible" width="520px" append-to-body>
      <el-form :model="rejectForm" :rules="rejectRules" ref="rejectFormRef" label-width="80px">
        <el-form-item label="原因" prop="reasonRefusal">
          <el-input v-model="rejectForm.reasonRefusal" type="textarea" :rows="3" placeholder="请输入驳回原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelRejectDialog">取消</el-button>
          <el-button type="primary" @click="confirmReject">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose, defineEmits } from "vue";
import { ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

// 定义弹窗状态
const dialogShow = ref(false);
const rejectDialogVisible = ref(false);

// 详情数据
const detailData: any = ref({});
// 处理推广板块字符串
const getPromoteTypes = (promoteType: string) => {
  if (!promoteType) return [];
  return promoteType.split(",");
};

// 金额格式化
const formatAmount = (amount: number | string) => {
  const num = typeof amount === "string" ? parseFloat(amount) : amount;
  return isNaN(num) ? "¥0.00" : `¥${num.toFixed(2)}`;
};

// 驳回表单
const rejectForm = reactive({
  reasonRefusal: ""
});

// 驳回表单验证规则
const rejectRules: FormRules = {
  reasonRefusal: [
    { required: true, message: "请输入驳回原因", trigger: "blur" },
    { min: 2, max: 200, message: "驳回原因长度为2-200个字符", trigger: "blur" }
  ]
};

// 表单引用
const rejectFormRef = ref<FormInstance>();

// 事件触发
const emit = defineEmits(["approve", "reject", "close", "refresh"]);

// 显示弹窗方法
const open = (data: any) => {
  detailData.value = {
    ...data
  };
  dialogShow.value = true;
};

// 关闭弹窗
const handleClose = () => {
  dialogShow.value = false;
  emit("close");
};

// 直接确认同意发放尾款
const confirmApprove = async () => {
  try {
    await ElMessageBox.confirm("确认同意发放尾款?", "确认同意", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 触发同意事件
    emit("approve", {
      id: detailData.value.id,
      name: detailData.value.name,
      orderMoney: detailData.value.orderMoney,
      orderNo: detailData.value.orderNo,
      storeTel: detailData.value.storeTel,
      userPhone: detailData.value.userPhone,
      endPayment: detailData.value.endPayment
    });

    // 关闭弹窗并通知刷新
    dialogShow.value = false;
    emit("refresh");
  } catch (error) {
    // 用户取消，不执行操作
  }
};

// 打开驳回原因弹窗
const openRejectDialog = () => {
  rejectForm.reasonRefusal = "";
  rejectDialogVisible.value = true;
};

// 取消驳回
const cancelRejectDialog = () => {
  rejectDialogVisible.value = false;
};

// 确认驳回（二次确认）
const confirmReject = async () => {
  if (!rejectFormRef.value) return;

  const valid = await rejectFormRef.value.validate();
  if (!valid) return;

  try {
    await ElMessageBox.confirm("确认取消发放尾款？", "确认驳回", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 触发驳回事件
    emit("reject", {
      id: detailData.value.id,
      name: detailData.value.name,
      orderMoney: detailData.value.orderMoney,
      orderNo: detailData.value.orderNo,
      storeTel: detailData.value.storeTel,
      userPhone: detailData.value.userPhone,
      endPayment: detailData.value.endPayment,
      endPaymentRefusal: rejectForm.reasonRefusal
    });

    // 关闭所有弹窗并通知刷新
    rejectDialogVisible.value = false;
    dialogShow.value = false;
    emit("refresh");
  } catch (error) {
    // 用户取消二次确认
  }
};

// 暴露给父组件的方法
defineExpose({
  open,
  close: handleClose
});
</script>

<style lang="scss" scoped>
.section-header {
  padding-left: 5px;
  margin: 10px 0 12px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-left: 3px solid #409eff;
}
.metrics-sections {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;

  /* 在小屏幕上自动堆叠 */
  @media (width <=600px) {
    flex-direction: column;
    gap: 10px;
  }
}
.metrics-section {
  flex: 1;
  min-width: 0;
  .section-header {
    padding-left: 5px;
    margin: 0 0 8px;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    border-left: 3px solid #409eff;
  }
}
.metrics-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}
.metric-card {
  padding: 8px 10px;
  background: #f8f9fa;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  transition: all 0.2s ease;
  &:hover {
    background: #f0f7ff;
    border-color: #d6e4ff;
  }
}
.metric-label {
  margin-bottom: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #606266;
}
.metric-value {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}
.review-container {
  margin-bottom: 15px;

  /* 滚动条样式优化 */
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
}
.review-detail {
  .introduction {
    line-height: 1.5;
    word-break: break-word;
    white-space: pre-wrap;
  }
}

/* 隐藏预览时的操作栏 */
:deep(.el-image-viewer__btn) {
  display: none !important;
}

/* 或者更精确地隐藏操作栏区域 */
:deep(.el-image-viewer__actions) {
  display: none !important;
}
.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
}
.image-item {
  aspect-ratio: 1;
  overflow: hidden;
}
.gallery-image {
  width: 100%;
  height: 100%;
  cursor: pointer;
  object-fit: cover;
}

/* 调整描述项的间距 */
:deep(.el-descriptions__label) {
  font-weight: 600;
  background-color: #fafafa;
}
:deep(.el-descriptions__cell) {
  padding: 10px 20px;
}
</style>
