<template>
  <div class="app-page">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" label-width="100px" @submit.prevent="handleQuery">
      <!-- 其他表单项：每行4个 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="省份筛选" prop="location">
            <!-- <el-cascader class="w-[180px]!" :options="area.list" :props="cascaderProps" v-model="area.selected" clearable @change="handleAreaChange" /> -->
            <ie-select v-model="area.selected" v-model:selectedItem="area.selectedItem" :options="area.list" label-key="areaName" value-key="areaId" clearable filterable class="w-[180px]!"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="注册学校" prop="schoolId">
            <ie-select v-model="selectedSchool" :options="schoolList" label-key="name" value-key="id" filterable clearable
                       class="w-[180px]!" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="注册班级" prop="classId">
            <ie-select v-model="selectedClass" :options="classList" label-key="name" value-key="classId" filterable
                       clearable class="w-[180px]!" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分配学校" prop="assignSchoolId">
            <ie-select v-model="selectedAssignSchool" :options="schoolList" label-key="name" value-key="id" filterable
                       clearable class="w-[180px]!" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="培训校区" prop="campusId">
            <ie-select v-model="selectedCampus" :options="campusList" label-key="name" value-key="id" filterable clearable
                       class="w-[180px]!" @change="handleCampusChange" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="校区班级" prop="campusClassId">
            <ie-select v-model="selectedCampusClass" :options="campusClassList" label-key="name" value-key="classId"
                       clearable filterable class="w-[180px]!" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="平台机构" prop="deptId">
            <ie-institution-select v-model="queryParams.deptId" class="w-[180px]!" clearable filterable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="代理商" prop="agentId">
            <ie-agent-select v-model="queryParams.agentId" class="w-[180px]!" filterable clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第一行：卡号段、卡类型、卡分配日期 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="卡号段" prop="begin">
            <div class="flex items-center gap-x-1">
              <el-input v-model="queryParams.begin" type="text" maxlength="11" class="w-[85px]!" placeholder="开始卡号" @keyup.enter="handleQuery" />
              <span class="text-gray-500 text-sm">-</span>
              <el-input v-model="queryParams.end" type="text" maxlength="11" class="w-[85px]!" placeholder="结束卡号" @keyup.enter="handleQuery" />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="卡类型" prop="type">
            <ie-select v-model="queryParams.type" :options="card_type" class="w-[180px]!" clearable filterable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="考生类型" prop="examType">
            <ie-select v-model="queryParams.examType" :options="exam_type" class="w-[180px]!" clearable filterable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="学生姓名" prop="nickName">
            <el-input v-model="queryParams.nickName" type="text" class="w-[180px]!" placeholder="请输入姓名" clearable filterable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="queryParams.phonenumber" type="text" v-number maxlength="11" class="w-[180px]!"
                      placeholder="请输入手机号码" clearable filterable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分配状态" prop="distributeStatus">
            <ie-select v-model="queryParams.distributeStatus" :options="card_distribute_status" class="w-[180px]!"
              clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="使用状态" prop="status">
            <ie-select v-model="queryParams.status" :options="card_status" class="w-[180px]!" clearable filterable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="过期状态" prop="timeStatus">
            <ie-select v-model="queryParams.timeStatus" :options="card_time_status" class="w-[180px]!" clearable filterable/>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="结算状态" prop="isSettlement">
            <ie-select v-model="queryParams.isSettlement" :options="card_settlement_status" class="w-[180px]!" clearable filterable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="缴费状态" prop="payStatus">
            <ie-select v-model="queryParams.payStatus" :options="card_pay_status" class="w-[180px]!" clearable filterable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="卡分配日期" prop="assignTimeRange">
            <el-date-picker v-model="queryParams.assignTimeRange" type="daterange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" class="w-[180px]!" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <div class="flex gap-x-2">
              <el-button type="primary" icon="Search" @click="handleQuery" class="w-[80px]">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery" class="w-[80px]">重置</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row :gutter="20">
        <el-col :span="6">
          <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-col>
      </el-row> -->
    </el-form>
    <el-row class="mt-2">
      <CustomButton icon="plus" v-hasPermi="['dz:cards:issue']" @click="handleAddCard">制卡</CustomButton>
      <CustomButton color="#67c23a" v-hasPermi="['dz:cards:assign']" @click="handleAssign">
        <svg-icon icon-class="peoples" class="mr-1" style="font-size: 12px" />
        分配卡
      </CustomButton>
      <CustomButton color="#E6A23C" v-hasPermi="['dz:cards:pay']" :disabled="batchDisabled" @click="handlePay">
        <svg-icon icon-class="money" class="mr-1" style="font-size: 12px" />
        缴费
      </CustomButton>
      <CustomButton color="#F56C6C" v-hasPermi="['dz:cards:close']" :disabled="batchDisabled" @click="handleClose">
        <svg-icon icon-class="lock" class="mr-1" style="font-size: 12px" />
        关卡
      </CustomButton>
      <CustomButton color="#67C23A" v-hasPermi="['dz:cards:reopen']" :disabled="batchDisabled" @click="handleReopen">
        <svg-icon icon-class="enter" class="mr-1" style="font-size: 12px" />
        重开
      </CustomButton>
      <CustomButton color="#E6A23C" v-hasPermi="['dz:cards:refund']" :disabled="batchDisabled" @click="handleRefund">
        <svg-icon icon-class="money" class="mr-1" style="font-size: 12px" />
        退费
      </CustomButton>
      <CustomButton color="#9C27B0" v-hasPermi="['dz:cards:associateCampus']" @click="handleRelateCampus">
        <svg-icon icon-class="link" class="mr-1" style="font-size: 12px" />
        关联校区
      </CustomButton>
      <!-- <CustomButton color="#00BCD4" v-hasPermi="['dz:cards:openFinished']" @click="handleOpenCard">
        <svg-icon icon-class="enter" class="mr-1" style="font-size: 12px" />
        直接开卡
      </CustomButton> -->
      <!-- <CustomButton icon="delete" color="#F56C6C" v-hasPermi="['dz:cards:remove']" :disabled="batchDisabled"
        @click="handleDeleteBatch" v-if="false">
        删除
      </CustomButton> -->
      <CustomButton color="#FFC107" v-hasPermi="['dz:cards:settlement']"  :disabled="batchDisabled" @click="handleSettle">
        <svg-icon icon-class="chart" class="mr-1" style="font-size: 12px" />
        结算
      </CustomButton>
      <CustomButton color="#009688" :disabled="batchDisabled" @click="handleRenew">
        <svg-icon icon-class="time" class="mr-1" style="font-size: 14px" />
        续期
      </CustomButton>
      <CustomButton color="#673AB7" v-hasPermi="['dz:cards:updateuser']"  :disabled="editDisabled" @click="handleEdit">
        <svg-icon icon-class="edit" class="mr-1" style="font-size: 12px" />
        修改
      </CustomButton>
      <CustomButton color="#606266" v-hasPermi="['dz:cards:export']" @click="handleExport">
        <svg-icon icon-class="download" class="mr-1" style="font-size: 14px" />
        导出
      </CustomButton>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <card-table :data="cardList" :loading="loading" :hide-actions="true" @selectionChange="handleSelectionChange"
      @delete="handleDelete" @refresh="getList" />
    <div class="flex justify-end">
      <Pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <MakeDialog ref="makeDialogRef" @refresh="getList" />
    <OpenDialog ref="openDialogRef" @refresh="getList" />
    <AssignDialog ref="assignDialogRef" @refresh="getList" />
    <EditDialog ref="editDialogRef" @refresh="getList" />
    <RelateDialog ref="relateDialogRef" @refresh="getList" />
  </div>
</template>

<script setup name="Cards">
defineOptions({ name: 'Cards' })
import useSchool from '@/hooks/useSchool';
import IeSelect from '@/components/IeSelect/index.vue';
import IeAgentSelect from '@/components/IeAgentSelect/index.vue';
import IeInstitutionSelect from '@/components/IeInstitutionSelect/index.vue';
import CardTable from './components/CardTable.vue';
import Pagination from '@/components/Pagination/index.vue';
import CustomButton from './components/CustomButton.vue';
import MakeDialog from './components/MakeDialog.vue';
import OpenDialog from './components/OpenDialog.vue';
import AssignDialog from './components/AssignDialog.vue';
import EditDialog from './components/EditDialog.vue';
import RelateDialog from './components/RelateDialog.vue';
import { listCards, delCards, payCard, closeCard, reopenCard, refundCard, settleCard, renewCard } from '@/api/dz/cards';
import { CARD_STATUS, EnumCardType } from '@/common/enum';
import { getCurrentInstance, nextTick } from 'vue';

const { proxy } = getCurrentInstance();
const {
  reset,
  area,
  // areaList,
  // selectedArea,
  schoolList,
  selectedSchool,
  selectedAssignSchool,
  classList,
  selectedClass,
  campusList,
  selectedCampus,
  campusClassList,
  selectedCampusClass,
  getSchoolList,
  getCampusList,
  getAreaList,
} = useSchool({ loadCampus: true, loadCampusClass: true, loadClass: true });
const {
  exam_type,
  card_distribute_status,
  card_status,
  card_time_status,
  card_settlement_status,
  card_pay_status,
  card_type,
} = proxy.useDict("exam_type", "card_distribute_status", "card_status", "card_time_status", "card_settlement_status", "card_pay_status", "card_type");
const cascaderProps = {
  label: "areaName",
  value: "areaId",
  checkStrictly: true,
}
const queryParams = ref({
  pageNum: 1,
  pageSize: 20
})
const showSearch = ref(true)
const cardList = ref([])
const total = ref(0)
const selectedRows = ref([])
const loading = ref(false)

const ids = computed(() => {
  return selectedRows.value.map(item => item.cardId);
})
const batchDisabled = computed(() => {
  return selectedRows.value.length === 0;
})
const editDisabled = computed(() => {
  return selectedRows.value.length !== 1;
})

watchEffect(() => {
  queryParams.value.areaIds = area.selected;
  // 使用 location 进行搜索
  queryParams.value.location = area.selectedItem?.shortName || area.selectedItem?.areaName || null;
  queryParams.value.schoolId = selectedSchool.value;
  queryParams.value.assignSchoolId = selectedAssignSchool.value;
  queryParams.value.classId = selectedClass.value;
  queryParams.value.campusId = selectedCampus.value;
  queryParams.value.campusClassId = selectedCampusClass.value;
})

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
}

const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 20
  };
  reset();
  handleQuery();
}

const getList = () => {
  const params = {
    ...queryParams.value,
    assignTimeBegin: queryParams.value.assignTimeRange?.[0],
    assignTimeEnd: queryParams.value.assignTimeRange?.[1],
  };
  delete params.assignTimeRange;
  listCards(params).then(res => {
    cardList.value = res.rows;
    total.value = res.total;
  }).finally(() => {
    loading.value = false;
  })
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
}

const makeDialogRef = ref(null);
const handleAddCard = () => {
  makeDialogRef.value.open()
}

const handleDelete = (row) => {
  proxy.$modal.confirm(`是否确认删除学习卡号为"${row.cardNo}"的数据项？`).then(() => {
    delCards(row.cardId).then(() => {
      proxy.$modal.msgSuccess('删除成功')
      getList()
    })
  });
}

const handleDeleteBatch = () => {
  proxy.$modal.confirm(`是否确认删除所选数据 (${ids.value.length}项) ？`).then(() => {
    delCards(ids.value).then(() => {
      proxy.$modal.msgSuccess('删除成功')
      getList()
    })
  });
}

const relateDialogRef = ref(null);
const handleRelateCampus = () => {
  // 如果有选中的卡片，传递cardIds；否则传递null（使用卡号段方式）
  const selectedCardIds = selectedRows.value.length > 0 ? ids.value : null
  relateDialogRef.value.open(selectedCardIds)
}

const openDialogRef = ref(null);
const handleOpenCard = () => {
  openDialogRef.value.open()
}

const handlePay = () => {
  // 体验卡禁止缴费
  const isExperienceCard = selectedRows.value.some(item => item.type === EnumCardType.EXPERIENCE);
  if (isExperienceCard) {
    proxy.$modal.msgError('体验卡禁止缴费');
    return;
  }
  proxy.$modal.confirm(`是否确认缴费所选数据 (${ids.value.length}项) ？`).then(() => {
    payCard(ids.value).then(() => {
      proxy.$modal.msgSuccess('缴费成功')
      getList()
    })
  })
}

const handleClose = () => {
  proxy.$modal.confirm(`是否确认关卡所选数据 (${ids.value.length}项) ？`).then(() => {
    closeCard(ids.value).then(() => {
      proxy.$modal.msgSuccess('关卡成功')
      getList()
    })
  })
}

const handleReopen = () => {
  proxy.$modal.confirm(`是否确认重开所选数据 (${ids.value.length}项) ？`).then(() => {
    reopenCard(ids.value).then(() => {
      proxy.$modal.msgSuccess('重开成功')
      getList()
    })
  })
}

const handleRefund = () => {
  // 体验卡禁止退费
  const isExperienceCard = selectedRows.value.some(item => item.type === EnumCardType.EXPERIENCE);
  if (isExperienceCard) {
    proxy.$modal.msgError('体验卡禁止退费');
    return;
  }
  proxy.$modal.confirm(`是否确认退费所选数据 (${ids.value.length}项) ？`).then(() => {
    refundCard(ids.value).then(() => {
      proxy.$modal.msgSuccess('退费成功')
      getList()
    })
  })
}

const handleSettle = () => {
  // 体验卡禁止结算
  const isExperienceCard = selectedRows.value.some(item => item.type === EnumCardType.EXPERIENCE);
  if (isExperienceCard) {
    proxy.$modal.msgError('体验卡禁止结算');
    return;
  }
  proxy.$modal.confirm(`是否确认结算所选数据 (${ids.value.length}项) ？`).then(() => {
    settleCard(ids.value).then(() => {
      proxy.$modal.msgSuccess('结算成功')
      getList()
    })
  })
}

const handleRenew = () => {
  proxy.$modal.confirm(`是否确认续费所选数据 (${ids.value.length}项) ？`).then(() => {
    renewCard(ids.value).then(() => {
      proxy.$modal.msgSuccess('续费成功')
      getList()
    })
  })
}

const editDialogRef = ref(null);
const handleEdit = () => {
  const row = selectedRows.value[0];
  if (row.status !== 30) {
    proxy.$modal.msgError('该卡未绑定用户');
    return;
  }
  editDialogRef.value.open({ ...row });
}

const assignDialogRef = ref(null);
const handleAssign = () => {
  // 如果有选中的卡片，传递cardIds；否则传递null（使用卡号段方式）
  const selectedCardIds = selectedRows.value.length > 0 ? ids.value : null
  assignDialogRef.value.open(selectedCardIds)
}

const handleExport = () => {
  proxy.download('dz/cards/export', {
    ...queryParams.value
  }, `cards_${new Date().getTime()}.xlsx`)
}


// 处理省份变化
const handleAreaChange = () => {
  // 当省份变化时，useSchool hook 中的 watch 会自动调用 getSchoolList 和 getCampusList
  // 这里不需要手动调用，因为 watch 已经处理了
  // 但为了确保数据更新，我们可以显式调用（虽然 watch 已经处理了）
  // 实际上 watch 会自动处理，所以这里可以留空或者添加其他逻辑
}

// 初始化数据加载（只在首次挂载时执行，keep-alive 缓存后不会再次执行）
onMounted(() => {
  // 如果列表数据已存在（keep-alive 缓存），则不重新调用接口
  // if (cardList.value.length > 0 || total.value > 0) {
  //   // 只检查省份数据，如果丢失则重新加载
  //   if (!area.list || area.list.length === 0) {
  //     getAreaList()
  //   }
  //   return
  // }

  // 初始进入页面时，加载分配学校、注册学校、培训校区的数据
  // 即使没有选择省份，也调用接口获取所有数据（areaCode 为 undefined 时接口会返回所有数据）
  getSchoolList()
  getCampusList()

  // 加载列表数据
  handleQuery()
})
</script>
<style lang="scss" scoped></style>
