<template>
  <div class="app-container">
    <el-tabs v-model="activeName" class="demo-tabs">
      <!-- 年级统计 -->
      <el-tab-pane label="年级统计" name="first">
        <el-row :gutter="20">
          <el-col>
            <!-- 查询 -->
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="园所">
                <el-select v-model="queryParams.school_id" placeholder="请选择园所" clearable filterable
                remote style="width: 240px">
                  <el-option v-for="school in schoolList" :key="school._id" :label="school.name" :value="school._id" />
                </el-select>
              </el-form-item>
              <el-form-item label="年级">
                <el-select v-model="queryParams.grade" placeholder="年级" clearable style="width: 240px">
                  <el-option label="小班" :value="0" />
                  <el-option label="中班" :value="1" />
                  <el-option label="大班" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <!-- 批量操作 -->
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="Upload"
                    @click="handleImport1"
                >导出</el-button>
              </el-col>
            </el-row>

            <el-table v-loading="loading" :data="userList">
              <el-table-column type="index" label="序号" width="60" align="center"
                :index="(index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1" />
              <el-table-column label="学校名称" align="center" key="schoolName" prop="schoolName" />
              <el-table-column label="年级" align="center" width="100">
                <template #default="scope">
                  <span>
                    {{
                      scope.row.grade === 0 ? '小班' :
                      scope.row.grade === 1 ? '中班' :
                      scope.row.grade === 2 ? '大班' :
                      '未知'
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="已付款人数" align="center" key="paidCount" prop="paidCount" />
              <el-table-column label="未付款人数" align="center" key="unpaidCount" prop="unpaidCount" />
              <el-table-column label="已付款金额" align="center" key="paidMoney" prop="paidMoney" />
              <el-table-column label="未付款金额" align="center" key="unpaidMoney" prop="unpaidMoney" />
            </el-table>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 学校统计 -->
      <el-tab-pane label="学校统计" name="second">
        <el-row :gutter="20">
          <el-col>
            <!-- 查询 -->
            <el-form :model="queryParams" ref="queryRef2" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="园所">
                <el-select v-model="queryParams.school_id" placeholder="请选择园所" clearable filterable
                remote style="width: 240px">
                  <el-option v-for="school in schoolList" :key="school._id" :label="school.name" :value="school._id" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery2">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery2">重置</el-button>
              </el-form-item>
            </el-form>

            <!-- 批量操作 -->
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="Upload"
                    @click="handleImport2"
                >导出</el-button>
              </el-col>
            </el-row>

            <el-table v-loading="loading" :data="userList">
              <el-table-column type="index" label="序号" width="60" align="center"
                :index="(index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1" />
              <el-table-column label="学校名称" align="center" key="schoolName" prop="schoolName" />
              <el-table-column label="已付款人数" align="center" key="paidCount" prop="paidCount" />
              <el-table-column label="未付款人数" align="center" key="unpaidCount" prop="unpaidCount" />
              <el-table-column label="已付款金额" align="center" key="paidMoney" prop="paidMoney" />
              <el-table-column label="未付款金额" align="center" key="unpaidMoney" prop="unpaidMoney" />
            </el-table>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize" @pagination="getList2" />
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { callCloudFunction } from "@/api/cloud";
import { ref, reactive, toRefs, getCurrentInstance, watch } from "vue";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const schoolList = ref([]);
const activeName = ref("first");

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    school_id: null,
    grade: null,
  },
});
const { queryParams } = toRefs(data);

/** 公共参数过滤 */
function buildParams() {
  const params = {};
  for (const [key, value] of Object.entries(queryParams.value)) {
    if (value !== null && value !== "" && value !== undefined) {
      params[key] = value;
    }
  }
  return params;
}

/** 获取学校列表 */
async function getSchoolList() {
  try {
    const { data } = await proxy.$models.wx_school.list({
      filter: { where: {} },
      pageSize: 10000,
      pageNumber: 1,
      getCount: true,
      envType: "prod",
    });
    schoolList.value = data.records;
  } catch (err) {
    console.error("获取学校列表失败", err);
  }
}

/** 年级统计 */
async function getList() {
  loading.value = true;
  try {
    const res = await callCloudFunction("database", {
      page: "payment",
      action: "findPaymentPage",
      data: buildParams(),
    });
    userList.value = res.records;
    total.value = res.total;
  } catch (err) {
    console.error("查询失败", err);
  } finally {
    loading.value = false;
  }
}

/** 学校统计 */
async function getList2() {
  loading.value = true;
  try {
    const res = await callCloudFunction("database", {
      page: "payment",
      action: "findPaymentPageBySchool",
      data: buildParams(),
    });
    userList.value = res.records;
    total.value = res.total;
  } catch (err) {
    console.error("查询失败", err);
  } finally {
    loading.value = false;
  }
}

/** 搜索按钮 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
function handleQuery2() {
  queryParams.value.pageNum = 1;
  getList2();
}

/** 重置按钮 */
function resetQuery() {
  queryParams.value.school_id = null;
  queryParams.value.grade = null;
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery2() {
  queryParams.value.school_id = null;
  queryParams.value.grade = null;
  queryParams.value.pageNum = 1;
  getList2();
}

/** 年级导出 */
async function handleImport1() {
  try {
    loading.value = true;
    // 获取所有年级统计数据，不分页
    const res = await callCloudFunction("database", {
      page: "payment",
      action: "findPaymentAll",
      data: buildParams(),
    });

    console.log(res, 'resresresresresresres');

    const data = res.records.map(item => ({
      "学校名称": item.schoolName,
      "年级": item.grade === 0 ? '小班' : item.grade === 1 ? '中班' : item.grade === 2 ? '大班' : '未知',
      "已付款人数": item.paidCount,
      "未付款人数": item.unpaidCount,
      "已付款金额": item.paidMoney,
      "未付款金额": item.unpaidMoney,
    }));

    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "年级统计");
    const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
    saveAs(new Blob([wbout], { type: "application/octet-stream" }), "年级统计.xlsx");
  } catch (err) {
    console.error("导出失败", err);
  } finally {
    loading.value = false;
  }
}

/** 学校导出 */
async function handleImport2() {
  try {
    loading.value = true;
    // 获取所有学校统计数据，不分页
    const res = await callCloudFunction("database", {
      page: "payment",
      action: "findPaymentAllBySchool",
      data: buildParams(),
    });

    const data = res.records.map(item => ({
      "学校名称": item.schoolName,
      "已付款人数": item.paidCount,
      "未付款人数": item.unpaidCount,
      "已付款金额": item.paidMoney,
      "未付款金额": item.unpaidMoney,
    }));

    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "学校统计");
    const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
    saveAs(new Blob([wbout], { type: "application/octet-stream" }), "学校统计.xlsx");
  } catch (err) {
    console.error("导出失败", err);
  } finally {
    loading.value = false;
  }
}

/** 监听 tab 切换，自动刷新 */
watch(activeName, (val) => {
  queryParams.value.pageNum = 1;
  if (val === "first") {
    getList();
  } else {
    getList2();
  }
});

// 初始化
getSchoolList();
getList();
</script>
