<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <search-form 
        v-show="showSearch" 
        :model="dataForm" 
        ref="searchFormRef"
        @keyup-enter="handleFilter"
      >
        <template #default="{ visible }">
          <template v-if="visible">
        <el-form-item label="招生计划" prop="groupId">
              <el-select v-model="dataForm.groupId" filterable clearable placeholder="请选择招生计划" @change="chanMajor">
            <el-option
              v-for="item in planList"
              :key="item.id"
              :label="item.groupName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学院" prop="xy">
              <el-select v-model="dataForm.xy" filterable clearable placeholder="请选择学院">
            <el-option
              v-for="item in deptList"
              :key="item.deptCode"
              :label="item.deptName"
              :value="item.deptCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报名时段" prop="startDate">
              <el-date-picker 
                v-model="dataForm.startDate" 
                format="yyyy-MM-dd" 
                value-format="yyyy-MM-dd" 
                clearable
                :disabled-date="startDateDisabledDate" 
                type="date"
              />
              <span style="margin: 0 8px;">-</span>
              <el-date-picker 
                v-model="dataForm.endDate" 
                format="yyyy-MM-dd" 
                value-format="yyyy-MM-dd" 
                clearable
                :disabled-date="endDateDisabledDate" 
                type="date"
              />
        </el-form-item>
        <el-form-item label="录取时段" prop="lqStartDate">
              <el-date-picker 
                v-model="dataForm.lqStartDate" 
                format="yyyy-MM-dd" 
                value-format="yyyy-MM-dd" 
                clearable
                type="date"
              />
              <span style="margin: 0 8px;">-</span>
              <el-date-picker 
                v-model="dataForm.lqEndDate" 
                format="yyyy-MM-dd" 
                value-format="yyyy-MM-dd" 
                clearable
                type="date"
              />
        </el-form-item>
        <el-form-item label="录取专业" prop="confirmedMajor">
              <el-select v-model="dataForm.confirmedMajor" filterable clearable placeholder="请选择录取专业">
            <el-option
              v-for="item in planMajorList"
              :key="item.majorCode"
              :label="item.majorName+'('+item.learnYear+'年制)'"
              :value="item.majorCode">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="拟报专业" prop="wishMajorOne">
              <el-select v-model="dataForm.wishMajorOne" filterable clearable placeholder="请选择录取专业">
            <el-option
              v-for="item in planMajorList"
              :key="item.majorCode"
              :label="item.majorName+'('+item.learnYear+'年制)'"
              :value="item.majorCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="录取状态" prop="auditStatus">
              <el-select v-model="dataForm.auditStatus" filterable clearable placeholder="请选择录取状态">
            <el-option
              v-for="item in auditStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="唯一号/姓名/身份证号/学校名称" prop="search">
              <el-input v-model="dataForm.search" clearable placeholder="唯一号/姓名/身份证号/学校名称"></el-input>
        </el-form-item>
        <el-form-item label="文化程度" prop="degreeOfEducation">
              <el-select v-model="dataForm.degreeOfEducation" filterable clearable placeholder="请选择文化程度">
            <el-option
              v-for="item in eduList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否住宿" prop="isAccommodation">
              <el-select v-model="dataForm.isAccommodation" filterable clearable placeholder="请选择是否住宿">
            <el-option
              v-for="item in yesNoList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否低保" prop="isMinimumLivingSecurity">
              <el-select v-model="dataForm.isMinimumLivingSecurity" filterable clearable placeholder="请选择是否低保">
            <el-option
              v-for="item in yesNoList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经办人" prop="auditor">
          <el-select
            v-model="dataForm.auditor"
            filterable
            remote
            clearable
            reserve-keyword
            placeholder="请选择经办人"
            :remote-method="remoteTeacherByQuery">
            <el-option
              v-for="item in teacherList"
              :key="item.teacherNo"
              :label="item.realName"
              :value="item.teacherNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缴费状态" prop="paystatus">
              <el-select v-model="dataForm.paystatus" filterable clearable placeholder="请选择缴费状态">
            <el-option
              v-for="item in paystatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="新市民材料已上传" prop="isNewCity">
              <el-select v-model="dataForm.isNewCity" filterable clearable placeholder="请选择新市民材料已上传">
            <el-option
              v-for="item in yesNoList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="毕业证已上传" prop="graPic">
              <el-select v-model="dataForm.graPic" filterable clearable placeholder="请选择毕业证已上传">
            <el-option
              v-for="item in yesNoList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推送状态" prop="pushed">
              <el-select v-model="dataForm.pushed" filterable clearable placeholder="请选择推送状态">
            <el-option
              v-for="item in pushedList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="来源" prop="isOut">
              <el-select v-model="dataForm.isOut" filterable clearable placeholder="请选择来源">
            <el-option
              v-for="item in isOutList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证书发放" prop="isBackTz">
              <el-select v-model="dataForm.isBackTz" filterable clearable placeholder="请选择是否发放">
            <el-option
              v-for="item in isBackTzList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否同步学工" prop="isTb">
              <el-select v-model="dataForm.isTb" filterable clearable placeholder="请选择是否同步学工">
            <el-option
              v-for="item in yesNoList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="市局审核" prop="cityExamType">
              <el-select v-model="dataForm.cityExamType" filterable clearable placeholder="请选择市局审核状态">
            <el-option
              v-for="item in cityExamTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="面试结果" prop="interview">
              <el-select v-model="dataForm.interview" filterable clearable placeholder="请选择面试结果">
            <el-option
              v-for="item in interviewDicList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资料审核状态" prop="zlsh">
              <el-select v-model="dataForm.zlsh" filterable clearable placeholder="请选择资料审核状态">
            <el-option
              v-for="item in zlshList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

          </template>
        </template>

        <!-- 操作按钮 -->
        <template #actions>
          <el-form-item>
            <el-button type="primary" @click="handleFilter" icon="Search">查询</el-button>
            <el-button type="primary" plain @click="resetForm('searchForm')" icon="Refresh" class="ml10">重置</el-button>
          </el-form-item>
        </template>
      </search-form>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb15" style="width: 100%;">
          <el-button 
            type="primary"
            icon="FolderAdd"
            @click="addOrUpdateHandle()"
            v-if="permissions.recruit_recruitstudentsignup_add">新 增
          </el-button>
          <el-button 
            class="ml10"
            type="warning"
            plain
            v-if="permissions.zipExport"
            icon="Download"
            @click="downZip()">招生名单打包导出
          </el-button>
          <el-button 
            class="ml10"
            type="warning"
            plain
            icon="Download"
            @click="handleExport()">名单导出
          </el-button>
          <el-button 
            class="ml10"
            type="primary"
            plain
            icon="UploadFilled"
            v-if="permissions.recruit_send_img"
            @click="handleSendImg()">图片同步
          </el-button>
        </div>
      </el-row>

      <!-- 表格 -->
        <el-table
        ref="tableRef"
          :data="dataList"
        v-loading="dataListLoading"
          border
        :cell-style="tableStyle?.cellStyle"
        :header-cell-style="tableStyle?.headerCellStyle">

          <el-table-column
            header-align="center"
            align="center"
            label="操作">
            <template #default="scope">
              <el-button type="text" size="small" icon="el-icon-view" @click="addOrUpdateHandle(scope.row.id,0)">查看
              </el-button>
              <el-button v-if="permissions.recruit_recruitstudentsignup_edit" type="text" size="small"
                         icon="el-icon-edit" @click="edit(scope.row.id)">补材料
              </el-button>

              <el-button
                v-if="permissions.recruit_recruitstudentsignup_interview && scope.row.degreeOfEducation == '3'"
                type="text" size="small"
                icon="el-icon-check" @click="interviewForm(scope.row)">面试
              </el-button>

              <el-button v-if="permissions.recruit_recruitstudentsignup_edit && scope.row.auditStatus=='0'"
                         type="text" size="small" icon="iconfont icon-rizhiguanli"
                         @click="addOrUpdateHandle(scope.row.id,1)">审核
              </el-button>

              <el-button
                v-if="permissions.recruit_recruitstudentsignup_leaveSchool && scope.row.auditStatus=='20' && scope.row.isMajorChange!='1'"
                type="text" size="small" icon="el-icon-circle-close"
                @click="handleUpdate(scope.row.id,scope.row.groupId,scope.row.feeAgency)">退学
              </el-button>
              <el-button v-if="permissions.recruit_recruitstudentsignup_change && scope.row.auditStatus=='20' "
                         type="text" size="small" icon="iconfont iconbanjiguanli1" @click="majorChange(scope.row.id)">
                调整专业
              </el-button>
              <el-button
                v-if="permissions.recruit_recruitstudentsignup_show && scope.row.pushed=='1' && scope.row.paiedOffline!='10'"
                type="text" icon="el-icon-tickets" size="small" plain @click="showPayCode(scope.row)">支付二维码
              </el-button>
              <!--                  <el-button v-if="permissions.recruit_recruitstudentsignup_show && scope.row.pushed=='1' && scope.row.paiedOffline=='0' && scope.row.auditStatus=='20'" type="text" icon="el-icon-check" size="small" @click="delayPayTimeSet(scope.row)">延迟收费</el-button>-->
              <el-button
                v-if="permissions.recruit_recruitstudentsignup_rePush && scope.row.pushed=='0' && scope.row.auditStatus=='20'"
                type="text" icon="el-icon-check" size="small" plain @click="handleRePush(scope.row)">重新推送
              </el-button>

              <el-button
                v-if="permissions.recruit_recruitstudentsignup_show && ((scope.row.degreeOfEducation=='1'&& scope.row.isOut=='1' && scope.row.auditStatus=='20')
                || (scope.row.degreeOfEducation=='1'&& scope.row.isOut=='0' && scope.row.paiedOffline!='0' && scope.row.auditStatus=='20')
                || (scope.row.degreeOfEducation=='2' && scope.row.isGradePic=='1' && scope.row.paiedOffline!='0' && scope.row.auditStatus=='20')
                || (scope.row.degreeOfEducation=='3' && scope.row.isGradePic=='1' && scope.row.paiedOffline!='0' && scope.row.auditStatus=='20')
                ) "
                type="text" icon="el-icon-check" size="small" plain @click="lqtz(scope.row)">录取通知书
              </el-button>
              <el-button
                v-if="permissions.recruit_recruitstudentsignup_show && scope.row.paiedOffline!='0' && scope.row.auditStatus=='20'"
                type="text" icon="el-icon-check" size="small" plain @click="infoTable(scope.row)">信息表
              </el-button>
              <el-button v-if="permissions.recruit_recruitstudentsignup_push && scope.row.auditStatus=='20'" type="text"
                         icon="el-icon-upload" size="small" plain @click="handlePushCity(scope.row.id)">推送市局
              </el-button>
            </template>
          </el-table-column>

          <el-table-column
            prop="serialNumber"
            header-align="center"
            align="center"
            width="120"
            label="唯一号">
          </el-table-column>
          <el-table-column
            prop="name"
            header-align="center"
            align="center"
            width="120"
            label="姓名">
          </el-table-column>

          <el-table-column
            prop="name"
            header-align="center"
            align="left"
            width="250"
            label="资料检测">
            <template #default="scope">
                <div v-if="scope.row.isOut=='0'">
                  <span >资料审核状态:</span>
                  <span style="color: #b4bccc" v-if="scope.row.zlsh=='0'">未填写</span>
                  <span style="color: green" v-if="scope.row.zlsh=='2' && scope.row.isOut=='0'">通过</span>
                  <span style="color: #ff9900" v-if="scope.row.zlsh=='1' && scope.row.isOut=='0'">待审核</span>
                  <span style="color: red" v-if="scope.row.zlsh=='3' && scope.row.isOut=='0'">驳回</span>
                  <br/>
                  <span v-if="scope.row.zlsh !='2'">材料状态:</span>
                  <span style="color: #ff9900" v-if="!scope.row.graPic && scope.row.zlsh !='2'">缺少毕业证</span>
                  <span style="color: #3c763d" v-if="scope.row.degreeOfEducation == '1' && scope.row.isOut == '1'">无需上传</span>
                  <span style="color: #ff9900" v-if="scope.row.degreeOfEducation == '1' && scope.row.zlsh !='2' && !scope.row.yyPic  && !scope.row.housePic && !scope.row.sbPic">, 缺新市民材料</span>
                  <br />
                  <span v-if="scope.row.zlsh=='3' && scope.row.zlshRemark !='' && scope.row.zlshRemark !=null">资料审核意见:</span>
                  <span style="color: red" v-if="scope.row.zlsh=='3' && scope.row.zlshRemark !='' && scope.row.zlshRemark !=null">{{scope.row.zlshRemark}}</span>
                </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="confirmedMajor"
            header-align="center"
            align="left"
            label="录取专业">
            <template #default="scope">
              <span>录取状态：</span>
              <span v-if="scope.row.auditStatus==0"
                    style="color: orange">{{ getLabelValue(auditStatusList, scope.row.auditStatus) }}</span>
              <span v-if="scope.row.auditStatus==20"
                    style="color: green">{{ getLabelValue(auditStatusList, scope.row.auditStatus) }}</span>
              <span v-if="scope.row.auditStatus==-20"
                    style="color: red">{{ getLabelValue(auditStatusList, scope.row.auditStatus) }}</span>
              <br/>
              <div v-if="scope.row.auditStatus==20">
                录取专业：
                {{ getMajorLabelWithYears(planMajorList, scope.row.confirmedMajor, { key: 'majorCode', value: 'majorName' }) }}<br/>
              </div>
              <div v-if="scope.row.auditStatus==20">
                录取时间：{{ dateFormat(scope.row.auditTime) }}
              </div>
              <div v-if="scope.row.degreeOfEducation == '3'">
                面试结果：{{ getLabelValue(interviewDicList, scope.row.interview) }}
                <span v-if="scope.row.interview == '-1' && scope.row.interviewReason"
                      style="color: #ff9900">({{ scope.row.interviewReason }})</span>
              </div>
              <div v-if="scope.row.confirmedMajor">
                证书发放：
                <span v-if="scope.row.isBackTz=='0'" style="color: red">未发放</span>
                <span v-if="scope.row.isBackTz=='1'" style="color: green">已发放</span>
              </div>
              <div v-if="scope.row.confirmedMajor">
                发放人：
                <span v-if="scope.row.isBackTz=='0'" style="color: red"></span>
                <span v-if="scope.row.isBackTz=='1'" style="color: green">{{ scope.row.sendUserName }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="xy"
            header-align="center"
            align="center"
            width="120"
            label="学院(经办人)">

            <template #default="scope">
              <span v-if="scope.row.auditStatus==20">
                {{ getLabelValueByProps(deptList, scope.row.xy, { key: 'deptCode', value: 'deptName' }) }}
              </span> <br/>
              <span v-if="scope.row.auditStatus==20">
                ({{scope.row.auditorName}})
              </span>

            </template>
          </el-table-column>

          <el-table-column
            prop="paiedOffline"
            header-align="center"
            align="center"
            width="90"
            label="缴费状态">
            <template #default="scope">
              {{ getStatus(scope.row.paiedOffline) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="pushed"
            header-align="center"
            align="center"
            width="90"
            label="推送状态">
            <template #default="scope">
              <span v-if="scope.row.pushed==0" style="color: red">{{ getPushed(scope.row.pushed) }}</span>
              <span v-if="scope.row.pushed==1" style="color: green">{{ getPushed(scope.row.pushed) }}</span>
            </template>
          </el-table-column>

        </el-table>

      <!-- 分页 -->
      <pagination
        v-bind="pagination"
          @current-change="currentChangeHandle"
        @size-change="sizeChangeHandle"
      />
      <!-- 弹窗, 新增 / 修改 -->
      <table-form v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></table-form>

      <major-change v-if="majorChangeVisible" ref="majorChange" @refreshDataList="getDataList"></major-change>

      <update v-if="updateVisible" ref="update" @refreshDataList="getDataList"></update>

      <!-- 支付二维码弹窗 -->
      <pay-qrcode-dialog ref="payQrcodeDialogRef" @refresh="getDataList"></pay-qrcode-dialog>

      <!-- 延迟缴费弹窗 -->
      <delay-pay-time-dialog ref="delayPayTimeDialogRef" @refresh="getDataList"></delay-pay-time-dialog>


      <!-- 录取通知书弹窗 -->
      <admission-notice-dialog ref="admissionNoticeDialogRef" :permissions="permissions" @refresh="getDataList"></admission-notice-dialog>

      <dorm-f-w v-if="dormFWRefVisible" ref="dormFWRef"></dorm-f-w>
      <show-map v-if="baiduMapVisible" ref="baiduMapRef"></show-map>
      <interview-form ref="interviewFormRef" @refresh="getDataList"></interview-form>
    </div>
  </div>
</template>

<script setup lang="ts" name="recruitstudentsignup">
import { ref, reactive, computed, onMounted, nextTick, defineAsyncComponent, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserInfo } from '/@/stores/userInfo'
import { useMessage, useMessageBox } from '/@/hooks/message'
import axios from 'axios'
import { list } from '/@/api/recruit/recruitstudentplangroup'
import {
  delObj,
  exportZip,
  fetchList,
  leaveSchool,
  rePush as rePushApi,
  yjOut,
  oneClass,
  oneStuNo,
  tbStuWork,
  sendImg,
  pushCity as pushCityApi
} from '/@/api/recruit/recruitstudentsignup'
import { getLabelValue, getLabelValueByProps, getMajorLabelWithYears } from '/@/utils/dictLabel'
import {getDeptList} from "/@/api/basic/basicclass";
import {listPlanByCondition as planMajor} from "/@/api/recruit/recruitstudentplan";
import {getTypeValue, getDictsByTypes} from "/@/api/admin/dict";
import {getUserListByRole} from "/@/api/admin/user";
import {queryTeacherBaseByNo} from "/@/api/professional/professionaluser/teacherbase";

// ROLE_CODE 常量定义
const ROLE_CODE = {
  ROLE_RECRUIT_SECOND: 'ROLE_RECRUIT_SECOND',
  ROLE_RECRUIT: 'ROLE_RECRUIT'
}

// Loading 函数（如果模块不存在，使用空函数）
const showLoading = () => {}
const hideLoading = () => {}

// 定义组件
const TableForm = defineAsyncComponent(() => import('./detaiform.vue'))
const MajorChange = defineAsyncComponent(() => import('./majorChange.vue'))
const Update = defineAsyncComponent(() => import('./update.vue'))
const DormFW = defineAsyncComponent(() => import('./dormFW.vue'))
const ShowMap = defineAsyncComponent(() => import('./showMap.vue'))
const InterviewForm = defineAsyncComponent(() => import('/@/views/recruit/recruitstudentsignup/interviewForm.vue'))
const PayQrcodeDialog = defineAsyncComponent(() => import('./PayQrcodeDialog.vue'))
const DelayPayTimeDialog = defineAsyncComponent(() => import('./DelayPayTimeDialog.vue'))
const AdmissionNoticeDialog = defineAsyncComponent(() => import('./AdmissionNoticeDialog.vue'))

// 使用 Pinia store
const userInfoStore = useUserInfo()
const { userInfos } = storeToRefs(userInfoStore)

// 创建权限对象
const permissions = computed(() => {
  const perms: Record<string, boolean> = {}
  userInfos.value.authBtnList.forEach((perm: string) => {
    perms[perm] = true
  })
  return perms
})

// 消息提示 hooks
const message = useMessage()
const messageBox = useMessageBox()

// 表格引用
const tableRef = ref()
const searchFormRef = ref()
const addOrUpdateRef = ref()
const majorChangeRef = ref()
const updateRef = ref()
const dormFWRef = ref()
const baiduMapRef = ref()
const interviewFormRef = ref()
const payQrcodeDialogRef = ref()
const delayPayTimeDialogRef = ref()
const admissionNoticeDialogRef = ref()

// 搜索表单显示状态
const showSearch = ref(true)

// 表单数据
const dataForm = reactive({
  zlsh: '',
        groupId: '',
  xy: '',
  confirmedMajor: '',
  degreeOfEducation: '',
  isAccommodation: '',
  isMinimumLivingSecurity: '',
  search: '',
  auditor: '',
  isNewCity: '',
  startDate: '',
  endDate: '',
        lqStartDate: '',
        lqEndDate: '',
  paystatus: '',
  graPic: '',
  pushed: '',
  wishMajorOne: '',
        isTb: '',
  cityExamType: '',
  interview: '',
  type: '',
  auditStatus: '',
  isOut: '',
  isBackTz: ''
})

// 数据列表
const dataList = ref<any[]>([])
const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)
const dataListLoading = ref(false)

// 分页对象（用于 pagination 组件）
const pagination = computed(() => ({
  current: pageIndex.value,
  size: pageSize.value,
  total: totalPage.value
}))

// 表格样式（可选）
const tableStyle = ref({
  cellStyle: {},
  headerCellStyle: {}
})

// 弹窗状态
const addOrUpdateVisible = ref(false)
const majorChangeVisible = ref(false)
const updateVisible = ref(false)
const dormFWRefVisible = ref(false)
const baiduMapVisible = ref(false)

// 列表数据
const auditorList = ref<any[]>([])
const planList = ref<any[]>([])
const eduList = ref<any[]>([])
const planMajorList = ref<any[]>([])
const deptList = ref<any[]>([])
const teacherList = ref<any[]>([])
const interviewDicList = ref<any[]>([])
const zlshList = ref<any[]>([])
const paystatusList = ref<any[]>([])

// 静态数据
const isBackTzList = [{ label: '未发放', value: '0' }, { label: '已发放', value: '1' }]
const auditStatusList = [{ label: '未录取', value: '-20' }, { label: '待审核', value: '0' }, { label: '已录取', value: '20' }]
const yesNoList = [{ label: '否', value: '0' }, { label: '是', value: '1' }]
const cityExamTypeList = [{ label: '待审核', value: '0' }, { label: '通过', value: '1' }, { label: '驳回', value: '2' }]
const pushedList = [{ label: '未推送', value: '0' }, { label: '已推送', value: '1' }]
const isOutFwList = [{ label: '待确认', value: '0' }, { label: '范围内', value: '1' }, { label: '范围外', value: '2' }]
const isOutList = [{ label: '学校', value: '0' }, { label: '市平台', value: '1' }]

// 日期格式化
const dateFormat = (date: string | null | undefined) => {
  if (!date) return ''
      // return formatDate(date, format)
  return date
}

// 日期选择器禁用日期
const startDateDisabledDate = (time: Date) => {
  if (dataForm.endDate) {
    return new Date(dataForm.endDate).getTime() < time.getTime()
  }
  return false
}

const endDateDisabledDate = (time: Date) => {
  if (dataForm.startDate) {
    return new Date(dataForm.startDate).getTime() > time.getTime()
  }
  return false
}
// 检索教师
const remoteTeacherByQuery = (query: string) => {
  teacherList.value = []
      if (query !== '') {
        setTimeout(() => {
      queryTeacherBaseByNo(query).then((response: any) => {
        teacherList.value = response.data || []
      }).catch(() => {
        teacherList.value = []
      })
    }, 200)
  }
}

// 发送图片
const handleSendImg = () => {
  messageBox.confirm('是否确认同步招生图片到市平台？请谨慎操作').then(() => {
        return sendImg()
  }).then(() => {
    message.success('同步图片请求已发起,请耐心等待')
  }).catch(() => {
        hideLoading()
      })
}

// 同步学工
const handleTbStuWork = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
        return
      }
  messageBox.confirm('是否确认同步学工？请谨慎操作').then(() => {
        showLoading()
    return tbStuWork(dataForm)
  }).then(() => {
    hideLoading()
    message.success('同步完成')
  }).catch(() => {
        hideLoading()
      })
}

// 一键分配班级和学号
const handleOneClassAndStuNo = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
        return
      }
  messageBox.confirm('是否确认一键分配班级和学号？请谨慎操作').then(() => {
        showLoading()
    return Promise.all([oneClass(dataForm), oneStuNo(dataForm)])
  }).then(() => {
    hideLoading()
    message.success('分配完成')
  }).catch(() => {
        hideLoading()
      })
}

// 下载zip
const downZip = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
        return
      }
  showLoading()
  exportZip(dataForm).then(res => {
    hideLoading()
    const blob = new Blob([res.data])
    const elink = document.createElement('a')
    elink.download = '招生名单.zip'
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }).catch(() => {
    hideLoading()
  })
}

// 百度地图
const baiduMap = (row: any) => {
  baiduMapVisible.value = true
  nextTick(() => {
    baiduMapRef.value?.init(row)
  })
}

// 设置宿舍
const setDormFW = () => {
  dormFWRefVisible.value = true
  nextTick(() => {
    dormFWRef.value?.init()
  })
}

// 一键判断是否超出住宿范围
const handleYjOut = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
        return
      }
  messageBox.confirm('是否确认一键判断是否超出住宿范围？请谨慎操作').then(() => {
    return yjOut({ groupId: dataForm.groupId })
  }).then(() => {
    message.success('操作成功')
    getDataList()
  })
}

// 导出审核
const handleExportAudit = (type: number) => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
        return
      }
  downFile(type)
}

// 导出Excel
const exportExcel = (form: any, url: string) => {
  return axios({
        method: 'post',
    url: url,
    data: form,
    responseType: 'blob',
        headers: {
          'Content-Type': 'application/json'
        }
      })
}

// 导出文件
const downFile = (type: number) => {
  dataForm.type = String(type)
  exportExcel(dataForm, '/recruit/recruitstudentsignup/exportExcel').then(res => {
    const blob = new Blob([res.data])
    const fileName = type == 1 ? '延迟缴费名单导出.xlsx' : '超时缴费名单导出.xlsx'
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }).catch(() => {})
}

// 导出
const handleExport = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
    return
  }
  exportExcel(dataForm, '/recruit/recruitstudentsignup/exportData').then(res => {
    const blob = new Blob([res.data])
    const elink = document.createElement('a')
    elink.download = '招生名单导出.xls'
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }).catch(() => {})
}
// 去重
const unique = (arr: any[]) => {
  const rese = new Map()
  return arr.filter((item) => !rese.has(item.username) && rese.set(item.username, 1))
}

// 性别
const getGender = (gender: string) => {
  if (gender == '2') return '女'
  if (gender == '1') return '男'
  return ''
}

// 切换专业
const chanMajor = () => {
  planMajorList.value = []
  if (dataForm.groupId) {
    planMajor({ groupId: dataForm.groupId }).then(data => {
      planMajorList.value = data.data
    })
  }
}

// 查询
const handleFilter = () => {
  pageIndex.value = 1
  getDataList()
}

    // 获取数据列表
const getDataList = () => {
  dataList.value = []
  dataListLoading.value = true
  fetchList({
    current: pageIndex.value,
    size: pageSize.value,
    ...dataForm
  }).then(response => {
    dataList.value = response.data.records
    totalPage.value = response.data.total
    dataListLoading.value = false
  }).catch(() => {
    dataListLoading.value = false
  })
}

    // 每页数
const sizeChangeHandle = (val: number) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}

    // 当前页
const currentChangeHandle = (val: number) => {
  pageIndex.value = val
  getDataList()
}

    // 新增 / 修改
const addOrUpdateHandle = (id?: string, type?: number) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id, type)
  })
}

// 编辑
const edit = (id: string) => {
  updateVisible.value = true
  nextTick(() => {
    updateRef.value?.init(id)
  })
}

// 专业调整
const majorChange = (id: string) => {
  majorChangeVisible.value = true
  nextTick(() => {
    majorChangeRef.value?.init(id)
  })
}

// 退学
const handleUpdate = (id: string, groupId: string, feeAgency: string) => {
  messageBox.confirm('是否确认办理退学操作？请谨慎操作').then(() => {
    return leaveSchool({ id, groupId, feeAgency })
  }).then(() => {
    message.success('操作成功')
    getDataList()
  })
}

// 删除
const deleteHandle = (id: string) => {
  messageBox.confirm('是否确认删除本条数据？请谨慎操作').then(() => {
        return delObj(id)
  }).then(() => {
    message.success('删除成功')
    getDataList()
  })
}

// 重置表单
const resetForm = (formName: string) => {
  if (formName === 'searchForm') {
    searchFormRef.value?.formRef?.resetFields()
  }
}

// 缴费状态
const getStatus = (type: string) => {
  if (type == '0') return '未缴费'
  if (type == '5') return '部分缴费'
  if (type == '10') return '已缴费'
  return ''
}

// 推送状态
const getPushed = (type: string) => {
  if (type == '0') return '未推送'
  if (type == '1') return '已推送'
  return ''
}

// 专业状态
const getMajor = (type: string) => {
  if (type == '0') return '未申请'
  if (type == '1') return '待审核'
  if (type == '2') return '驳回'
  if (type == '3') return '已通过'
  return ''
}

// 录取通知书
const lqtz = (row: any) => {
  nextTick(() => {
    admissionNoticeDialogRef.value?.init(row)
  })
}

// 信息表
const infoTable = (row: any) => {
  window.open('printRecruitedStu.html?appId=' + row.id)
}

// 推送市局
const handlePushCity = (id: string) => {
  messageBox.confirm('是否确认推送该数据到市局审核？请谨慎操作').then(() => {
    return pushCityApi({ id })
  }).then(() => {
    message.success('推送成功')
    getDataList()
  })
}

// 重新推送
const handleRePush = (row: any) => {
  messageBox.confirm('是否确认重新推送本条数据？请谨慎操作').then(() => {
    return rePushApi({ id: row.id })
  }).then(() => {
    message.success('推送成功')
    getDataList()
  })
}

// 延迟缴费
const delayPayTimeSet = (row: any) => {
  nextTick(() => {
    delayPayTimeDialogRef.value?.init(row)
  })
}

// 支付二维码
const showPayCode = (row: any) => {
  nextTick(() => {
    payQrcodeDialogRef.value?.init(row)
  })
}

// 面试
const interviewForm = (row: any) => {
  interviewFormRef.value?.init(row)
}

// 初始化
const init = async () => {
  // 查询二级学院信息
  getDeptList().then(data => {
    deptList.value = data.data
  })
  
  // 获取招生计划列表
  list().then(data => {
    planList.value = data.data
    if (planList.value.length > 0) {
      dataForm.groupId = planList.value[0].id
      getDataList()
      chanMajor()
    }
  })
  
  // 获取文化程度字典
  getTypeValue('finance_student_source').then(res => {
    eduList.value = res.data
  })
  
  // 批量获取字典数据：面试结果、资料审核状态、缴费状态
  getDictsByTypes(['interview_dic', 'recruit_zlsh', 'recruit_pay_status']).then((res) => {
    interviewDicList.value = res.data.interview_dic || []
    zlshList.value = res.data.recruit_zlsh || []
    paystatusList.value = res.data.recruit_pay_status || []
  })
  
  // 所有经办人
  getUserListByRole(ROLE_CODE.ROLE_RECRUIT_SECOND).then((res: any) => {
    auditorList.value = res.data || []
    getUserListByRole(ROLE_CODE.ROLE_RECRUIT).then((re: any) => {
      if (re.data) {
        re.data.forEach((r: any) => {
          auditorList.value.push(r)
        })
      }
      auditorList.value = unique(auditorList.value)
    })
  })
}

// 监听招生计划变化
watch(() => dataForm.groupId, () => {
  if (dataForm.groupId) {
    chanMajor()
  }
})

onMounted(() => {
  init()
})
</script>

<style lang="scss" scoped>
// 样式内容
</style>
