<template>
  <div class="dataVisualize-box">
    <div class="card top-box">
      <div class="top-title">工作台</div>
      <div class="top-content">
        <div class="item-center">
          <div class="gitee-traffic traffic-box">
            <div class="traffic-img">
              <img src="./images/add_person.png" alt="" />
            </div>
            <span class="item-value">{{ auditSums["店铺入驻"] || 0 }}</span>
            <span class="traffic-name sle">待审核商铺</span>
          </div>
          <div class="today-traffic traffic-box">
            <div class="traffic-img">
              <img src="./images/today.png" alt="" />
            </div>
            <span class="item-value">{{ auditSums["商家申诉"] || 0 }}</span>
            <span class="traffic-name sle">待审核商家申诉</span>
          </div>
          <div class="yesterday-traffic traffic-box">
            <div class="traffic-img">
              <img src="./images/book_sum.png" alt="" />
            </div>
            <span class="item-value">{{ auditSums["套餐"] || 0 }}</span>
            <span class="traffic-name sle">待审核套餐</span>
          </div>
          <div class="gitHub-traffic traffic-box">
            <div class="traffic-img">
              <img src="./images/add_team.png" alt="" />
            </div>
            <span class="item-value">{{ auditSums["代金券"] || 0 }}</span>
            <span class="traffic-name sle">代金券审核</span>
          </div>
          <div class="yesterday-traffic traffic-box">
            <div class="traffic-img">
              <img src="./images/book_sum.png" alt="" />
            </div>
            <span class="item-value">{{ auditSums["经营许可证"] || 0 }}</span>
            <span class="traffic-name sle">待食品许可证审批</span>
          </div>
        </div>
      </div>
    </div>

    <div class="card top-box">
      <el-tabs v-model="tabActive" class="demo-tabs">
        <el-tab-pane v-for="item in tab" :key="item.name" :label="item.label" :name="item.name" />
      </el-tabs>
      <div class="card top-box">
        <el-table :data="tableData" height="250">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="content" label="内容" />
          <el-table-column prop="type" label="类型" />
          <el-table-column prop="createdTime" label="提交时间" />
          <el-table-column prop="status" label="状态" />
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="scope">
              <el-button type="primary" link @click="handleAudit(scope.row)"> 通过 </el-button>
              <el-button type="primary" link @click="handleAudit2(scope.row)"> 拒绝 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-if="total > 0"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[5, 10, 15, 20]"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          background
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>
    <!-- 拒接弹出框 -->
    <el-dialog v-model="dialogFormVisible" title="审核拒接" width="500">
      <el-form :model="form">
        <el-form-item>
          <el-input v-model="form.reason" autocomplete="off" style="width: 500px" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false"> 取消 </el-button>
          <el-button type="primary" @click="handleOk"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted, onActivated, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Audit } from "@/api/interface";
import { ElMessage, ElMessageBox } from "element-plus";
import { getAuditList, getAuditSum } from "@/api/modules/audit";
import { approveStoreInfo } from "@/api/modules/storeUser";
import { consentComplaintFun, rejectClaimFun } from "@/api/modules/storeCommentAppeal";
import { updateStatus } from "@/api/modules/groupPackage";
import { changeStatus } from "@/api/modules/groupPackage";
import { updatefoodLicenceImageStatus } from "@/api/modules/storeUser";

const dialogFormVisible = ref(false);
const router = useRouter();
const tabActive = ref(1);
const form = ref({
  reason: ""
});
// 分页相关响应式数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const route = useRoute();

const tab = [
  { label: "商铺入驻", name: 1, type: "1" },
  { label: "审核商家申诉", name: 4, type: "3" },
  { label: "审核套餐", name: 5, type: "4" },
  { label: "代金券审核", name: 7, type: "6" },

  // { label: "审核活动", name: 6, type: "5" }
  { label: "食品许可证审批", name: 8, type: "7" }
];

const tableData = ref<any[]>([]);
const auditSums = ref<{
  [key: string]: number;
}>({});

// 封装参数处理函数
const processParams = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  delete newParams.createTime;
  delete newParams.pageNum;
  delete newParams.pageSize;
  newParams.status = newParams.status || "";
  newParams.type = newParams.type || "";
  newParams.page = newParams.page || 1;
  newParams.size = newParams.size || 10;
  newParams.classBigType = newParams.classBigType || "";
  newParams.classTeacher = newParams.classTeacher || "";
  newParams.className = newParams.className || "";
  return newParams;
};

const getTableList = async (params: any) => {
  const newParams = processParams(params);
  try {
    const res = await getAuditList(newParams);
    return res;
  } catch (error) {
    console.error("getTableList - 获取审核列表失败:", error);
    return { records: [], total: 0 };
  }
};

// 统一数据加载方法
const loadData = async () => {
  try {
    // 获取当前标签页的类型
    const currentTab = tab.find(item => item.name === tabActive.value);
    const type = currentTab ? currentTab.type : "1";

    const res = await getTableList({
      page: currentPage.value,
      size: pageSize.value,
      type: type
    });

    // 检查响应数据格式
    if (res.data && res.data.current && res.data.size && res.data.total) {
      // 更新分页数据
      currentPage.value = res.data.current;
      pageSize.value = res.data.size;
      total.value = res.data.total;

      // 更新表格数据
      tableData.value = res.data.records || [];
    } else {
      console.error("loadData - 响应数据格式不正确:", res);
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("loadData - 获取审核列表失败:", error);
    tableData.value = [];
    total.value = 0;
  }
};

// 页码变化处理
const handlePageChange = (newPage: number) => {
  currentPage.value = newPage;
  loadData();
};

// 每页数量变化处理
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  loadData();
};

const getTobList = async () => {
  try {
    // 初始化所有类型为0
    auditSums.value = {
      店铺入驻: 0,
      商家申诉: 0,
      套餐: 0,
      代金券: 0,
      食品许可证审批: 0
    };
    const resp = await getAuditSum({});
    // 检查响应数据格式
    if (resp.code === 200 && resp.data) {
      resp.data.forEach(item => {
        const type = item.type;
        const typeSum = parseInt(item.typeSum, 10);
        auditSums.value[type] = typeSum;
      });
    } else {
      console.error("getTobList - 响应数据格式不正确:", resp);
      ElMessage.error("获取审核统计数据失败，响应数据格式不正确");
    }
    return resp;
  } catch (error) {}
};

// 审核通过操作
const handleAudit = (row: any) => {
  ElMessageBox.confirm("确定要通过该审核吗？", "审核确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // 同意
      // 商铺入驻
      if (tabActive.value == 1) {
        approveStoreInfo({
          id: row.storeInfoId,
          approvalStatus: 1
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success("审核通过成功");
            loadData();
            getTobList();
          }
        });
      } else if (tabActive.value == 4) {
        //  审核商家申诉
        consentComplaintFun({
          id: row.storeCommentAppealId,
          appealStatus: "2"
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success("审核通过成功");
            loadData();
            getTobList();
          }
        });
      } else if (tabActive.value == 5) {
        // 审核套餐
        updateStatus({
          id: row.lifeGroupPackageId,
          status: 2,
          approvalComments: ""
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success("审核通过成功");
            loadData();
            getTobList();
          }
        });
      } else if (tabActive.value == 7) {
        // 代金券审核
        changeStatus({
          id: row.couponId,
          status: 5,
          comment: "",
          type: 1
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success("审核通过成功");
            loadData();
            getTobList();
          }
        });
      } else if (tabActive.value == 8) {
        // 许可证审核
        updatefoodLicenceImageStatus({
          id: row.storeInfoId,
          foodLicenceStatus: 1,
          foodLicenceReason: ""
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success("审核通过成功");
            loadData();
            getTobList();
          }
        });
      }
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};
const rowValue = ref({});
// 驳回操作
const handleOk = () => {
  if (form.value.reason) {
    dialogFormVisible.value = false;
    if (tabActive.value == 1) {
      approveStoreInfo({
        id: rowValue.value.storeInfoId,
        approvalStatus: 2,
        reason: form.value.reason
      }).then(res => {
        if (res.code === 200) {
          handleCs();
          loadData();
          getTobList();
        }
      });
    } else if (tabActive.value == 4) {
      //  审核商家申诉
      rejectClaimFun({
        id: rowValue.value.storeCommentAppealId,
        appealStatus: "1",
        logRemark: form.value.reason
      }).then(res => {
        if (res.code === 200) {
          handleCs();
          loadData();
          getTobList();
        }
      });
    } else if (tabActive.value == 5) {
      // 审核套餐
      updateStatus({
        id: rowValue.value.lifeGroupPackageId,
        status: 3,
        approvalComments: form.value.reason
      }).then(res => {
        if (res.code === 200) {
          handleCs();
          loadData();
          getTobList();
        }
      });
    } else if (tabActive.value == 7) {
      // 代金券审核
      changeStatus({
        id: rowValue.value.couponId,
        status: 3,
        comment: form.value.reason,
        type: 1
      }).then(res => {
        if (res.code === 200) {
          handleCs();
          loadData();
          getTobList();
        }
      });
    } else if (tabActive.value == 8) {
      // 许可证审核
      updatefoodLicenceImageStatus({
        id: rowValue.value.storeInfoId,
        foodLicenceStatus: 3,
        foodLicenceReason: form.value.reason
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success("审核通过成功");
          loadData();
          getTobList();
        }
      });
    }
  } else {
    ElMessage.error("请填写审核拒绝原因!");
  }
};
const handleCs = () => {
  ElMessage.success("审核拒接成功!");
  form.value.reason = "";
};
// 审核拒绝操作
const handleAudit2 = (row: any) => {
  rowValue.value = row;
  dialogFormVisible.value = true;
};

// 监听 tabActive 变化
watch(tabActive, async (newVal, oldVal) => {
  if (newVal !== oldVal) {
    // 重置分页状态
    currentPage.value = 1;
    total.value = 0;

    // 加载新数据
    getTobList();
    await loadData();
  }
});

// 页面加载时触发查询
onMounted(async () => {
  await loadData();
  await getTobList();
});

// 从其他页面返回时触发查询
onActivated(async () => {
  await loadData();
});

// 表格配置项
const columns = reactive<ColumnProps<Audit.ResAuditList>[]>([
  { prop: "index", label: "序号", type: "index", width: 100 },
  { prop: "content", label: "内容", search: { el: "input" } },
  { prop: "type", label: "类型" },
  { prop: "createdTime", label: "提交时间" },
  { prop: "status", label: "状态" },
  { prop: "operation", label: "操作", fixed: "right", width: 120 }
]);
</script>
<style scoped lang="scss">
@import "./index";
.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
}
</style>
