<template>
  <el-dialog v-model="dialogShow" title="预付款审核" draggable width="700px" @close="handleClose">
    <!-- 预计指标标题 -->
    <div class="section-header">预计指标</div>

    <!-- 关键指标卡片区域 -->
    <div class="metrics-cards">
      <div class="metric-card">
        <div class="metric-label">GMV(元)</div>
        <div class="metric-value" style="margin-left: 70px">
          {{ formatAmount(detailData.orderNewGmv) }}
        </div>
      </div>
      <div class="metric-card">
        <div class="metric-label">播放量</div>
        <div class="metric-value" style="margin-left: 70px">
          {{ detailData.orderPlayCount }}
        </div>
      </div>
    </div>

    <!-- 详情展示区域 -->
    <div class="review-container">
      <div class="review-detail">
        <el-descriptions :column="2" border>
          <!-- 第一列：重要信息 -->
          <el-descriptions-item label="订单编号" :span="2">
            {{ detailData.orderNo }}
          </el-descriptions-item>
          <el-descriptions-item label="套餐名称" :span="2">
            {{ detailData.name }}
          </el-descriptions-item>
          <el-descriptions-item label="商家ID">
            {{ detailData.id }}
          </el-descriptions-item>
          <el-descriptions-item label="商家昵称">
            {{ detailData.storeName }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ detailData.realName }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证号码" :span="2">
            {{ detailData.idCard }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ detailData.userPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="实付款(元)">
            {{ formatAmount(detailData.orderMoney) }}
          </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>
      </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="400px" 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,
      userPhone: detailData.value.userPhone,
      name: detailData.value.name,
      storeTel: detailData.value.storeTel,
      orderNo: detailData.value.orderNo,
      advance: detailData.value.advance
    });

    // 关闭弹窗并通知刷新
    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,
      userPhone: detailData.value.userPhone,
      name: detailData.value.name,
      storeTel: detailData.value.storeTel,
      reasonRefusal: rejectForm.reasonRefusal,
      orderMoney: detailData.value.orderMoney,
      orderNo: detailData.value.orderNo,
      advance: detailData.value.advance
    });

    // 关闭所有弹窗并通知刷新
    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-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  padding: 10px 0;
  margin-bottom: 20px;
}
.metric-card {
  padding: 12px 15px;
  background: #f8f9fa;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgb(0 0 0 / 5%);
  transition: all 0.3s ease;
  &:hover {
    background: #f0f7ff;
    border-color: #d6e4ff;
    box-shadow: 0 4px 12px rgb(0 0 0 / 8%);
    transform: translateY(-2px);
  }
}
.metric-label {
  margin-bottom: 6px;
  font-size: 13px;
  font-weight: 600;
  color: #606266;
}
.metric-value {
  font-size: 18px;
  font-weight: 700;
  line-height: 1.2;
  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>
