<template>
  <div class="app-page">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" label-width="100px">
      <!-- 第一行：卡号段、卡类型、卡分配日期 -->
      <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="开始卡号" />
              <span class="text-gray-500 text-sm">-</span>
              <el-input v-model="queryParams.end" type="text" maxlength="11" class="w-[85px]!" placeholder="结束卡号" />
            </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 />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <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-row>
      <!-- 其他表单项：每行4个 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="省份筛选" prop="provinceId">
            <el-cascader class="w-[180px]!" :options="area.list" :props="cascaderProps" v-model="area.selected" clearable />
          </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-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-col :span="6">
          <el-form-item label="平台机构" prop="deptId">
            <ie-institution-select v-model="queryParams.deptId" class="w-[180px]!" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <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="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-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="姓名" prop="nickName">
            <el-input v-model="queryParams.nickName" type="text" class="w-[180px]!" placeholder="请输入姓名" clearable />
          </el-form-item>
        </el-col>
        <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 />
          </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 />
          </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-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="使用状态" prop="status">
            <ie-select v-model="queryParams.status" :options="CARD_STATUS" class="w-[180px]!" clearable />
          </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 />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结算状态" prop="isSettlement">
            <ie-select v-model="queryParams.isSettlement" :options="card_settlement_status" class="w-[180px]!" clearable />
          </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 />
          </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" />
    <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>
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,
} = useSchool({ loadCampus: true, loadCampusClass: true, loadClass: true });
const {
  exam_type,
  card_distribute_status,
  card_time_status,
  card_settlement_status,
  card_pay_status,
  card_type,
} = proxy.useDict("exam_type", "card_distribute_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;
  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 = () => {
  relateDialogRef.value.open()
}

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 = () => {
  assignDialogRef.value.open()
}

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


onMounted(() => {
  handleQuery();
})
</script>
<style lang="scss" scoped></style>