<template>
  <div class="app-container">
    <!-- 搜索表单组件 -->
    <SearchForm v-show="showSearch" :config="searchConfig" :model-value="queryParams"
      @update:model-value="handleSearchFormUpdate" :on-search="handleQuery" :on-reset="resetQuery" :show-expand="true"
      :expand-count="6" label-width="68px" />

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['dz:cards:add']">制卡</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain @click="handleAssignCard" v-hasPermi="['dz:cards:assign']"
          style="border-color: #67c23a; color: #67c23a; font-weight: 500">
          <svg-icon icon-class="peoples" class="mr-1" style="font-size: 16px" />
          分配卡
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['dz:cards:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain :disabled="multiple" @click="handlePayment" v-hasPermi="['dz:cards:pay']"
          style="border-color: #e6a23c; color: #e6a23c; font-weight: 500">
          <svg-icon icon-class="money" class="mr-1" style="font-size: 16px" />
          缴费
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="multiple" @click="handleCloseCard" v-hasPermi="['dz:cards:close']"
          style="border-color: #f56c6c; color: #f56c6c; font-weight: 500">
          <svg-icon icon-class="lock" class="mr-1" style="font-size: 16px" />
          关卡
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain :disabled="multiple" @click="handleReopenCard" v-hasPermi="['dz:cards:reopen']"
          style="border-color: #13c2c2; color: #13c2c2; font-weight: 500">
          <svg-icon icon-class="enter" class="mr-1" style="font-size: 16px" />
          重开
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="multiple" @click="handleRefund" v-hasPermi="['dz:cards:refund']"
          style="border-color: #ff4d4f; color: #ff4d4f; font-weight: 500">
          <svg-icon icon-class="money" class="mr-1" style="font-size: 16px" />
          退费
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleAssociateCampus" v-hasPermi="['dz:cards:associateCampus']"
          style="border-color: #1890ff; color: #1890ff; font-weight: 500">
          <svg-icon icon-class="link" class="mr-1" style="font-size: 16px" />
          关联校区
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain @click="handleApplyCard" v-hasPermi="['dz:cards:openFinished']"
          style="border-color: #52c41a; color: #52c41a; font-weight: 500">
          <svg-icon icon-class="edit" class="mr-1" style="font-size: 16px" />
          直接开卡
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="multiple" icon="Delete" @click="handleDelete"
          v-hasPermi="['dz:cards:remove']" style="border-color: #ff4d4f; color: #ff4d4f; font-weight: 500">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Download" @click="handleExport" v-hasPermi="['dz:cards:export']"
          style="border-color: #722ed1; color: #722ed1; font-weight: 500">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- Table组件 -->
    <Table :data="cardsList" :columns="tableColumns" :actions="tableActions" :loading="loading" :total="total"
      :queryParams="queryParams" v-bind="tableProps" @action="handleTableAction"
      @selection-change="handleSelectionChange" @getList="getList">
      <!-- 序号插槽 -->
      <template #index="{ row, $index }">
        {{ getRowIndex($index) }}
      </template>

      <!-- 姓名-手机插槽 -->
      <template #studentInfo="{ row }">
        <div class="student-info">
          <div class="student-name">{{ row.nickName || "-" }}</div>
          <div class="student-phone">{{ row.phonenumber || "-" }}</div>
        </div>
      </template>
    </Table>

    <!-- 弹窗组件 -->
    <CardGenerationDialog v-model="cardGenerationOpen" :institution-list="institutionList" :school-list="schoolList"
      :card-type-options="card_type" @success="handleDialogSuccess" />

    <AssignCardDialog v-model="assignCardOpen" :selected-cards="selectedRows" :school-list="schoolList"
      :card-type-options="card_type" @success="handleDialogSuccess" />

    <EditStudentDialog v-model="open" :card-id="currentCardId" :class-list="classList" @success="handleDialogSuccess" />

    <PaymentDialog v-model="paymentOpen" :card-no="currentCardNo" :card-ids="selectedCardIds"
      :selected-cards="selectedRows" @success="handlePaymentSuccess" />

    <CloseCardDialog v-model="closeCardOpen" :card-no="currentCloseCardNo" :card-ids="selectedCardIds"
      @success="handleCloseCardSuccess" />

    <ReopenCardDialog v-model="reopenCardOpen" :card-no="currentReopenCardNo" :card-ids="selectedCardIds"
      @success="handleReopenCardSuccess" />

    <RefundDialog v-model="refundOpen" :card-no="currentRefundCardNo" @confirm="handleRefundConfirm" />

    <AssociateCampusDialog v-model="associateCampusOpen" :selected-cards="selectedRows"
      @success="handleAssociateCampusSuccess" />

    <ApplyCardDialog v-model="applyCardOpen" :selected-cards="selectedRows" @success="handleApplyCardSuccess" />
  </div>
</template>

<style scoped>
.student-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.student-name {
  font-weight: 500;
  margin-bottom: 2px;
}

.student-phone {
  font-size: 12px;
  color: #909399;
}
</style>

<script setup name="Cards">
import {
  listCards,
  getCards,
  delCards,
  addCards,
  updateCards,
} from "@/api/dz/cards";
import SearchForm from "@/components/SearchForm/index.vue";
import Table from "@/components/Table/index.vue";
import CardGenerationDialog from "./components/CardGenerationDialog.vue";
import AssignCardDialog from "./components/AssignCardDialog.vue";
import EditStudentDialog from "./components/EditStudentDialog.vue";
import PaymentDialog from "./components/PaymentDialog.vue";
import CloseCardDialog from "./components/CloseCardDialog.vue";
import ReopenCardDialog from "./components/ReopenCardDialog.vue";
import RefundDialog from "./components/RefundDialog.vue";
import AssociateCampusDialog from "./components/AssociateCampusDialog.vue";
import ApplyCardDialog from "./components/ApplyCardDialog.vue";
import formInfo from "./config/form.js";
import tableConfig from "./config/table.js";
// import { listUniversity } from "@/api/dz/school";
import { assignCard, issueCard, getCampusSchoolList } from "@/api/dz/cards";
import { listDept } from "@/api/system/dept";
import { listAgent } from "@/api/dz/agent";
import { getClassesBySchoolId } from "@/api/dz/classes";

const { proxy } = getCurrentInstance();
const {
  exam_type,
  card_status,
  card_distribute_status,
  card_time_status,
  bool_values,
  card_pay_status,
  card_type,
} = proxy.useDict(
  "exam_type",
  "card_status",
  "card_distribute_status",
  "card_time_status",
  "bool_values",
  "card_pay_status",
  "card_type"
);

const cardsList = ref([]);
const schoolList = ref([]);
const campusList = ref([]); // 校区列表
const classList = ref([]); // 班级列表
const open = ref(false);
const cardGenerationOpen = ref(false); // 制卡对话框
const assignCardOpen = ref(false); // 分配卡对话框
const paymentOpen = ref(false); // 缴费对话框
const closeCardOpen = ref(false); // 关卡对话框
const reopenCardOpen = ref(false); // 重开对话框
const refundOpen = ref(false); // 退费对话框
const associateCampusOpen = ref(false); // 关联校区对话框
const applyCardOpen = ref(false); // 直接开卡对话框
const currentCardNo = ref([]); // 当前缴费的卡号（支持数组）
const currentCloseCardNo = ref([]); // 当前关卡的卡号（支持数组）
const currentReopenCardNo = ref([]); // 当前重开的卡号（支持数组）
const currentRefundCardNo = ref(""); // 当前退费的卡号
const agentList = ref([]); // 代理商列表
const institutionList = ref([]); // 机构列表
const selectedRows = ref([]); // 选中的行
const selectedCardIds = computed(() =>
  selectedRows.value.map((row) => row.cardId)
); // 选中的卡ID列表
const currentCardId = ref(null); // 当前编辑的卡片ID
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 搜索配置
const searchConfig = computed(() => {
  const config = [...formInfo.info];

  // 动态设置选项数据
  config.forEach((item) => {
    switch (item.name) {
      case "type":
        item.option = card_type.value || [];
        break;
      case "status":
        item.option = card_status.value || [];
        break;
      case "distributeStatus":
        item.option = card_distribute_status.value || [];
        break;
      // 移除registerSchoolId，实体类中不存在
      case "timeStatus":
        item.option = card_time_status.value || [];
        break;
      case "payStatus":
        item.option = card_pay_status.value || [];
        break;
      case "isSettlement":
        item.option = bool_values.value || [];
        break;
      case "assignSchoolId":
        item.option = schoolList.value || [];
        break;
      case "registerSchoolId":
        item.option = schoolList.value || [];
        break;
      case "campusId":
        item.option = campusList.value || [];
        break;
      case "examType":
        item.option = exam_type.value || [];
        break;
    }
  });

  return config;
});

// 表格配置
const tableColumns = computed(() => {
  const columns = [...tableConfig.columns];

  // 动态设置字典选项
  columns.forEach((column) => {
    switch (column.prop) {
      case "type":
        column.options = card_type.value || [];
        break;
      case "status":
        column.options = card_status.value || [];
        break;
      case "distributeStatus":
        column.options = card_distribute_status.value || [];
        break;
      case "timeStatus":
        column.options = card_time_status.value || [];
        break;
      case "payStatus":
        column.options = card_pay_status.value || [];
        break;
      case "isSettlement":
        column.options = bool_values.value || [];
        break;
      // 移除studentCategory，实体类中不存在
      case "registerSchoolId":
      case "assignSchoolId":
        column.options = schoolList.value || [];
        break;
      case "studentCategory":
      case "classId":
      case "schoolClassId":
      case "campusId":
        column.options = []; // 需要从相应API获取
        break;
    }
  });

  return columns;
});

const tableActions = computed(() => tableConfig.actions);
const tableProps = computed(() => tableConfig.tableProps);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // 搜索表单字段
    areaIds: [],
    assignSchoolId: null,
    registerSchoolId: null,
    campusId: null,
    agentId: null,
    cardNo: null,
    password: null,
    cardNoRange: null,
    begin: null,
    end: null,
    type: null,
    studentCategory: null, // 分配考生类型
    studentName: null, // 学生姓名
    phone: null, // 手机号
    registerSchoolId: null, // 注册学校
    schoolClassId: null, // 校区班级
    distributeStatus: null,
    status: null,
    timeStatus: null,
    isSettlement: null,

    // 其他字段（用于数据传输）
    cardNo: null,
    password: null,
    payStatus: null,
    isSettlement: null,
    deptId: null,
    leftAgentId: null,
    schoolId: null,
    classId: null,
    year: null,
    endYear: null,
    openId: null,
    distributeTime: null,
    outDate: null,
    openTime: null,
    payTime: null,
    activeTime: null,
    settlementTime: null,
    refundTime: null,
    closeTime: null,
    createTime: null,
    updateTime: null,
  },
  rules: {
    schoolId: [{ required: true, message: "学校不能为空", trigger: "change" }],
    classId: [{ required: true, message: "班级不能为空", trigger: "change" }],
    nickName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号",
        trigger: "blur",
      },
    ],
    chineseMathEnglish: [
      { required: true, message: "语数英成绩不能为空", trigger: "blur" },
    ],
    vocationalSkills: [
      { required: true, message: "职业技能成绩不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form } = toRefs(data);

// 监听queryParams的原始变化
watch(
  () => data.queryParams,
  (newParams) => {
    if (newParams.areaIds && newParams.areaIds.length > 0) {
      getSchoolList();
    }
  },
  { immediate: true, deep: true }
);

/** 获取行序号 */
function getRowIndex(index) {
  const pageNum = queryParams.value?.pageNum || 1;
  const pageSize = queryParams.value?.pageSize || 10;
  return (pageNum - 1) * pageSize + index + 1;
}

/** 查询学习卡列表 */
function getList() {
  loading.value = true;
  listCards(queryParams.value).then((response) => {
    cardsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取学校列表 */
function getSchoolList() {
  // 如果没有选择省市区，则不获取学校列表
  if (!queryParams.value.areaIds || queryParams.value.areaIds.length === 0) {
    schoolList.value = [];
    return;
  }

  // 构造location参数：如果有省市区选择，取最后一个值（区）作为location
  const location =
    queryParams.value.areaIds[queryParams.value.areaIds.length - 1];

  // 传递pageNum和pageSize参数
  const requestParams = {
    location,
    pageNum: 1,
    pageSize: 9999, // 获取所有学校选项
  };

  // listUniversity(requestParams)
  //   .then((response) => {
  //     // 根据API返回数据结构处理
  //     let schoolData = [];
  //     if (response.data) {
  //       schoolData = Array.isArray(response.data)
  //         ? response.data
  //         : response.data.rows || response.data.list || [];
  //     } else if (response.rows) {
  //       schoolData = response.rows;
  //     } else if (response.list) {
  //       schoolData = response.list;
  //     } else if (Array.isArray(response)) {
  //       schoolData = response;
  //     }
  //
  //     // 确保数据格式符合配置要求
  //     schoolData = schoolData.map((item) => {
  //       // 如果API返回的是 {id, name, ...} 格式，直接使用
  //       if (item.id && item.name) {
  //         return item;
  //       }
  //       // 如果是其他格式，需要转换
  //       return {
  //         id: item.id || item.value || item.schoolId,
  //         name: item.name || item.label || item.schoolName || item.title,
  //       };
  //     });
  //
  //     schoolList.value = schoolData;
  //   })
  //   .catch((error) => {
  //     console.error("获取学校列表失败:", error);
  //     schoolList.value = [];
  //   });
}

/** 获取校区列表 */
function getCampusListData() {
  getCampusSchoolList({
    campus: true,
    pageNum: 1,
    pageSize: 9999, // 获取所有校区
  })
    .then((response) => {
      if (response.code === 200) {
        // 处理API返回的数据结构
        let campusData = [];
        if (response.data) {
          campusData = Array.isArray(response.data) ? response.data : [];
        } else if (response.rows) {
          campusData = response.rows;
        } else if (response.list) {
          campusData = response.list;
        }

        // 确保数据格式符合配置要求
        campusData = campusData.map((item) => {
          // 如果API返回的是 {id, name, ...} 格式，直接使用
          if (item.id && item.name) {
            return item;
          }
          // 如果是其他格式，需要转换
          return {
            id: item.id || item.value || item.campusId,
            name: item.name || item.label || item.campusName || item.title,
          };
        });

        campusList.value = campusData;
      }
    })
    .catch((error) => {
      console.error("获取校区列表失败:", error);
      campusList.value = [];
    });
}

// 取消按钮
// 处理弹窗成功事件
function handleDialogSuccess(message) {
  proxy.$modal.msgSuccess(message);
  getList(); // 刷新列表
}

// 获取机构列表
async function getInstitutionList() {
  try {
    const response = await listDept({});
    institutionList.value = response.data || response.rows || response || [];
  } catch (error) {
    console.error("获取机构列表失败:", error);
    institutionList.value = [];
  }
}

// 获取班级列表
async function getClassList() {
  try {
    // 这里应该调用获取班级列表的API
    // 暂时使用模拟数据
    classList.value = [
      { id: 1, name: "2501" },
      { id: 2, name: "2502" },
      { id: 3, name: "2503" },
    ];
  } catch (error) {
    console.error("获取班级列表失败:", error);
    classList.value = [];
  }
}

// 获取代理商列表
async function getAgentList() {
  try {
    const response = await listAgent({});
    const agentData = response.data || response.rows || response || [];

    // 确保数据格式符合前端期望
    agentList.value = agentData.map((item) => ({
      id: item.agentId,
      name: item.name,
    }));
  } catch (error) {
    console.error("获取代理商列表失败:", error);
    agentList.value = [];
  }
}

function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    cardId: null,
    cardNo: null,
    password: null,
    type: null,
    status: null,
    distributeStatus: null,
    timeStatus: null,
    payStatus: null,
    isSettlement: null,
    deptId: null,
    agentId: null,
    leftAgentId: null,
    campusId: null,
    assignSchoolId: null,
    schoolId: null,
    classesId: null,
    year: null,
    endYear: null,
    openId: null,
    remark: null,
    distributeTime: null,
    outDate: null,
    openTime: null,
    payTime: null,
    activeTime: null,
    settlementTime: null,
    refundTime: null,
    closeTime: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("cardsRef");
}

/** 搜索按钮操作 */
/** 表格操作处理 */
function handleTableAction(action, row) {
  switch (action.key) {
    case "edit":
      handleUpdate(row); // 修改时获取行数据
      break;
    case "delete":
      handleDelete(row);
      break;
    default:
      console.warn("Unknown action:", action.key);
  }
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 处理SearchForm组件的update:model-value事件 */
function handleSearchFormUpdate(newData) {
  Object.assign(data.queryParams, newData);
}

// 多选框选中数据
function handleSelectionChange(selection) {
  console.log("Selection changed:", selection);
  selectedRows.value = selection;
  ids.value = selection.map((item) => item.cardId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 制卡按钮操作 */
function handleAdd() {
  cardGenerationOpen.value = true;
  getInstitutionList(); // 获取机构列表
}

/** 缴费按钮操作 */
function handlePayment() {
  if (selectedRows.value.length === 0) {
    proxy.$modal.msgWarning("请选择要缴费的卡片");
    return;
  }

  // 获取所有选中卡片的卡号数组
  const cardNos = selectedRows.value.map(
    (card) => card.cardNo || card.id || "未知"
  );
  currentCardNo.value = cardNos;
  paymentOpen.value = true;
}

// 处理缴费成功
function handlePaymentSuccess(message) {
  proxy.$modal.msgSuccess(message);
  getList(); // 刷新列表
}

// 处理缴费确认（保留兼容性）
function handlePaymentConfirm(cardNo) {
  proxy.$modal.msgSuccess(`缴费成功！卡号：${cardNo}`);
  getList(); // 刷新列表
}

/** 关卡按钮操作 */
function handleCloseCard() {
  if (selectedRows.value.length === 0) {
    proxy.$modal.msgWarning("请选择要关卡的卡片");
    return;
  }

  // 获取所有选中卡片的卡号数组
  const cardNos = selectedRows.value.map(
    (card) => card.cardNo || card.id || "未知"
  );
  currentCloseCardNo.value = cardNos;
  closeCardOpen.value = true;
}

// 处理关卡成功
function handleCloseCardSuccess(message) {
  proxy.$modal.msgSuccess(message);
  getList(); // 刷新列表
}

// 处理关卡确认（保留兼容性）
function handleCloseCardConfirm(cardNo) {
  proxy.$modal.msgSuccess(`关卡成功！卡号：${cardNo}`);
  getList(); // 刷新列表
}

/** 重开按钮操作 */
function handleReopenCard() {
  if (selectedRows.value.length === 0) {
    proxy.$modal.msgWarning("请选择要重开的卡片");
    return;
  }

  // 获取所有选中卡片的卡号数组
  const cardNos = selectedRows.value.map(
    (card) => card.cardNo || card.id || "未知"
  );
  currentReopenCardNo.value = cardNos;
  reopenCardOpen.value = true;
}

// 处理重开成功
function handleReopenCardSuccess(message) {
  proxy.$modal.msgSuccess(message);
  getList(); // 刷新列表
}

// 处理重开确认（保留兼容性）
function handleReopenCardConfirm(cardNo) {
  proxy.$modal.msgSuccess(`重开成功！卡号：${cardNo}`);
  getList(); // 刷新列表
}

/** 退费按钮操作 */
function handleRefund() {
  if (selectedRows.value.length === 0) {
    proxy.$modal.msgWarning("请选择要退费的卡片");
    return;
  }

  // 获取第一个选中卡片的卡号
  const firstCard = selectedRows.value[0];
  currentRefundCardNo.value = firstCard.cardNo || firstCard.id || "未知";
  refundOpen.value = true;
}

// 处理退费确认
function handleRefundConfirm(cardNo) {
  proxy.$modal.msgSuccess(`退费成功！卡号：${cardNo}`);
  getList(); // 刷新列表
}

/** 关联校区按钮操作 */
function handleAssociateCampus() {
  if (selectedRows.value.length === 0) {
    // proxy.$modal.msgWarning("请选择要关联校区的卡片");
    // return;
  }
  associateCampusOpen.value = true;
}

// 处理关联校区成功
function handleAssociateCampusSuccess(message) {
  proxy.$modal.msgSuccess(message);
  getList();
}

// 处理关联校区确认
function handleAssociateCampusConfirm(data) {
  proxy.$modal.msgSuccess(
    `关联校区成功！卡号段：${data.beginCardNo}-${data.endCardNo}`
  );
  getList(); // 刷新列表
}

// 获取代理商列表
async function getAgentListData() {
  try {
    const response = await getAgentList({ pageNum: 1, pageSize: 1000 });
    if (response.code === 200) {
      agentList.value = response.data || [];
    }
  } catch (error) {
    console.error("获取代理商列表失败:", error);
    agentList.value = [];
  }
}

/** 直接开卡按钮操作 */
function handleApplyCard() {
  if (selectedRows.value.length === 0) {
    // proxy.$modal.msgWarning("请选择要申请开卡的卡片");
    // return;
  }
  applyCardOpen.value = true;
}

// 处理直接开卡成功
function handleApplyCardSuccess(message) {
  proxy.$modal.msgSuccess(message);
  getList();
}

// 处理直接开卡确认
function handleApplyCardConfirm(data) {
  proxy.$modal.msgSuccess(
    `直接开卡成功！卡号段：${data.beginCardNo}-${data.endCardNo}`
  );
  getList(); // 刷新列表
}

/** 分配卡按钮操作 */
function handleAssignCard() {
  console.log("分配卡按钮点击，当前选中的行:", selectedRows.value);
  assignCardOpen.value = true;
  getInstitutionList(); // 获取机构列表
  getAgentList(); // 获取代理商列表
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _cardId = row.cardId || ids.value;
  currentCardId.value = _cardId;

  try {
    // 获取学习卡详细信息
    const response = await getCards(_cardId);
    if (response.code === 200) {
      const cardData = response.data;

      // 将后端数据对应到表单字段
      form.value = {
        cardId: cardData.cardId,
        cardNo: cardData.cardNo,
        password: cardData.password,
        type: cardData.type,
        status: cardData.status,
        distributeStatus: cardData.distributeStatus,
        timeStatus: cardData.timeStatus,
        payStatus: cardData.payStatus,
        isSettlement: cardData.isSettlement,
        deptId: cardData.deptId,
        agentId: cardData.agentId,
        leftAgentId: cardData.leftAgentId,
        campusId: cardData.campusId,
        assignSchoolId: cardData.assignSchoolId,
        schoolId: cardData.schoolId,
        classId: cardData.classId,
        year: cardData.year,
        endYear: cardData.endYear,
        openId: cardData.openId,
        nickName: cardData.nickName,
        mobile: cardData.mobile,
        chineseMathEnglish: cardData.chineseMathEnglish,
        vocationalSkills: cardData.vocationalSkills,
        studentCategory: cardData.studentCategory,
        assignExamType: cardData.assignExamType,
        areaIds: cardData.areaIds,
        remark: cardData.remark,
      };

      // 获取班级列表
      await getClassList();

      // 打开编辑弹窗
      open.value = true;
    } else {
      proxy.$modal.msgError("获取学习卡信息失败");
    }
  } catch (error) {
    console.error("获取学习卡详细信息失败:", error);
    proxy.$modal.msgError("获取学习卡信息失败");
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["cardsRef"].validate((valid) => {
    if (valid) {
      if (form.value.cardId != null) {
        updateCards(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCards(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _cardIds = row.cardId || ids.value;
  const cardIdsArray = Array.isArray(_cardIds) ? _cardIds : [_cardIds];

  if (cardIdsArray.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的数据");
    return;
  }

  const message =
    cardIdsArray.length === 1
      ? `是否确认删除学习卡编号为"${cardIdsArray[0]}"的数据项？`
      : `是否确认删除选中的${cardIdsArray.length}条学习卡数据？`;

  proxy.$modal
    .confirm(message)
    .then(function () {
      return delCards(cardIdsArray);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "dz/cards/export",
    {
      ...queryParams.value,
    },
    `cards_${new Date().getTime()}.xlsx`
  );
}

getList();
getCampusListData(); // 获取校区列表

// 监听地址选择变化，自动获取学校列表
watch(
  () => queryParams.value.areaIds,
  (newAreaIds) => {
    if (newAreaIds && newAreaIds.length > 0) {
      getSchoolList();
    } else {
      schoolList.value = [];
    }
  },
  { immediate: true, deep: true }
);
</script>
