<template>
  <div class="mod-config">
    <basic-container>
      <el-form :inline="true" :model="dataForm" @keyup.enter="getDataList()"  ref="searchFormRef">
        <el-form-item label="招生计划" prop="groupId">
          <el-select v-model="dataForm.groupId" filterable clearable placeholder="请选择招生计划" size="small" @change="chanMajor" style="width: 150px;">
            <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="请选择学院"  size="small" style="width: 130px;">
            <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 size="small"
                          :disabled-date="startDateDisabled"  type="date" style="width: 200px;" ></el-date-picker>
          -
          <el-date-picker v-model="dataForm.endDate"  format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable size="small"
                          :disabled-date="endDateDisabled"   type="date" style="width: 200px;" ></el-date-picker>
        </el-form-item>

        <el-form-item label="录取专业" prop="confirmedMajor">
          <el-select v-model="dataForm.confirmedMajor" filterable clearable placeholder="请选择录取专业"  size="small" >
            <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="请选择录取专业"  size="small" >
            <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="search">
          <el-input v-model="dataForm.search" clearable placeholder="唯一号/姓名/身份证号/学校名称" size="small"></el-input>
        </el-form-item>
        <el-form-item label="文化程度" prop="degreeOfEducation">
          <el-select v-model="dataForm.degreeOfEducation" filterable clearable placeholder="请选择文化程度"  size="small" style="width: 120px;">
            <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="请选择是否住宿"  size="small" style="width: 120px;" >
            <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="请选择是否低保"  size="small" style="width: 120px;" >
            <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 clearable placeholder="请选择经办人"  size="small" style="width: 120px;">
            <el-option
              v-for="item in auditorList"
              :key="item.username"
              :label="item.realName"
              :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缴费状态" prop="paystatus">
          <el-select v-model="dataForm.paystatus" filterable clearable placeholder="请选择缴费状态"  size="small" style="width: 120px;" >
            <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="请选择新市民材料已上传"  size="small" style="width: 120px;" >
            <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="请选择毕业证已上传"  size="small" style="width: 120px;">
            <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="请选择推送状态"  size="small" style="width: 120px;" >
            <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="请选择来源"  size="small" style="width: 120px;" >
            <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="请选择是否打印"  size="small" style="width: 120px;" >
            <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="请选择是否同步学工"  size="small" style="width: 120px;" >
            <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="classNo">
          <el-select filterable clearable v-model="dataForm.classCode" size="small" placeholder="请选择班级" >
            <el-option
              v-for="item in classList"
              :key="item.classCode"
              :label="item.classNo"
              :value="item.classCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button  :icon="Search" type="primary" size="small"
                      @click="handleFilter()">查询
          </el-button>
          <el-button :icon="Delete" type="default" plain size="small"
                     @click="resetForm('searchFormRef')">清空
          </el-button>

          <el-button type="warning"
                     :icon="Download"
                     size="small"
                     @click="handleExport()">分班导出</el-button>
        <el-button type="danger"
                   v-if="permissions.recruit_banding"
                   size="small"
                   @click="oneClassHandle()">一键分班</el-button>
          <el-button type="danger"
                     v-if="permissions.recruit_banding"
                     size="small"
                     @click="oneStuNoHandle()">一键分学号</el-button>
        <el-button type="success"
                   v-if="permissions.recruit_synchronous_stuwork"
                   size="small"
                   @click="tbStuWorkHandle()">同步学工</el-button>
        </el-form-item>

      </el-form>


      <div class="avue-crud">
        <el-table
          :data="dataList"
          border
          stripe
          v-loading="dataListLoading">

          <el-table-column
            prop="serialNumber"
            header-align="center"
            align="center"
            label="唯一号">
          </el-table-column>
          <el-table-column
            prop="name"
            header-align="center"
            align="center"
            label="姓名">
          </el-table-column>
          <el-table-column
            prop="gender"
            header-align="center"
            align="center"
            label="性别">
            <template #default="scope">
              {{getGender(scope.row.gender)}}
            </template>
          </el-table-column>
          <el-table-column
            prop="idNumber"
            header-align="center"
            align="center"
            label="身份证号">
          </el-table-column>
          <el-table-column
            prop="confirmedMajor"
            header-align="center"
            align="center"
            label="录取专业">
            <template #default="scope" >
              <span v-if="scope.row.auditStatus==20">{{getLabelValueByPropes2(planMajorList,scope.row.confirmedMajor,{'key':'majorCode','value':'majorName'})}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="xy"
            header-align="center"
            align="center"
            label="学院">

            <template #default="scope">
              <span v-if="scope.row.auditStatus==20">{{getLabelValueByPropes(deptList,scope.row.xy,{'key':'deptCode','value':'deptName'})}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="classNo"
            header-align="center"
            align="center"
            label="班号">
          </el-table-column>
          <el-table-column
            prop="stuNo"
            header-align="center"
            align="center"
            label="学号">
          </el-table-column>

          <el-table-column
            prop="isTb"
            header-align="center"
            align="center"
            label="是否同步">
            <template #default="scope">
              <span v-if="scope.row.isTb=='0'" style="color: red">否</span>
              <span v-if="scope.row.isTb=='1'" style="color: green">是</span>
            </template>
          </el-table-column>

          <el-table-column
            header-align="center"
            align="center"
            label="操作">
            <template #default="scope">
              <el-button type="primary" link size="small"  @click="addOrUpdateHandle(scope.row.id,0)"  :icon="ZoomIn" plain>查看</el-button>
              <el-button type="primary" link size="small"  @click="changeclass(scope.row)"  v-if="permissions.recruit_banding && scope.row.isTb=='0' && scope.row.classNo !=null" :icon="Edit" plain>调整班级</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="avue-crud__pagination">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          background
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
      <!-- 弹窗, 新增 / 修改 -->
      <TableForm v-if="addOrUpdateVisible" ref="addOrUpdateRef" @refreshDataList="getDataList" ></TableForm>

      <MajorChange v-if="majorChangeVisible" ref="majorChangeRef" @refreshDataList="getDataList"></MajorChange>

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

      <el-dialog title="支付二维码" v-model="dialogFormVisible" width="800px"
                 @close="dialogFormVisible=false">
          <el-table :data="tableData" border>
            <el-table-column label="唯一号" prop="serialNumber" align="center"></el-table-column>
            <el-table-column label="姓名" prop="name" align="center"></el-table-column>
            <el-table-column label="家长手机号" prop="parentTelOne" align="center"></el-table-column>
            <el-table-column label="操作" prop="" align="center">
              <template #default>
                <el-button @click="updateFS()" :icon="Search" type="danger" size="small">立即查询</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="padding-top: 20px;">
            <div id="payQrcode1" style="display: inline-block;" >
              {{payQrcode1Msg}}
            </div>
            <vue-qr :text="payQrcode1" :size="200" v-if="showPrise1" style="display: inline-block"></vue-qr>

            <div id="payQrcode2" style="display: inline-block">
              {{payQrcode2Msg}}
            </div>
            <vue-qr :text="payQrcode2" :size="200" v-if="showPrise2" style="display: inline-block"></vue-qr>

            <div id="payQrcode3" style="display: inline-block">
              {{payQrcode3Msg}}
            </div>
            <vue-qr :text="payQrcode3" :size="200" v-if="showPrise3" style="display: inline-block"></vue-qr>
          </div>
        <span style="color: red;padding-top: 20px;">** 此界面为查询学生缴款二维码，如有收不到微信推送，或手机号填错的，可直接在此扫码支付，支付成功后，请手动点击"立即查询"按钮，查询该生的缴费情况;因财政收费系统有一定的滞后性，如点击"立即查询"后任显示未交费，请稍后再继续查询，或重新点击"立即查询"按钮 **</span>

      </el-dialog>

      <el-dialog title="延迟缴费" v-model="delayPayTimeVisible" width="300px"
                 @close="delayPayTimeVisible=false">

          <el-date-picker v-model="delayPayTime"  format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" clearable type="datetime"  ></el-date-picker>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="delayPayTimeVisible=false">关 闭</el-button>
            <el-button @click="updateInfoHandle" type="primary">保存</el-button>
          </div>
        </template>
      </el-dialog>


      <el-dialog title="录取通知书" v-model="lqtzsVisible" width="80%"
                 @close="lqtzsVisible=false">

        <div style="height:  60vh">
          <iframe id="iframeid" :src="pdfPath" ref="iframeRef" frameborder="0" style="width:100%;height:100%;"></iframe>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="lqtzsVisible=false">关 闭</el-button>
            <el-button @click="suerLQTZ" v-if="permissions.sureLQTZ && lqtzsShow" type="primary">确认已打印</el-button>
          </div>
        </template>
      </el-dialog>


      <el-dialog title="班级调整" v-model="changeClassVisible" width="500px"
                 @close="changeClassVisible=false">
        <el-form ref="formRef" :model="changeForm" label-width="80px">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="原班级">
                <el-select v-model="changeForm.oldClass" size="small" placeholder="请选择班级" disabled >
                  <el-option
                    v-for="item in classList"
                    :key="item.classCode"
                    :label="item.classNo"
                    :value="item.classCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="新班级">
                <el-select v-model="changeForm.classNo" filterable size="small" placeholder="请选择新班级"  >
                  <el-option
                    v-for="item in changeClassList"
                    :key="item.classNo"
                    :label="item.classNo"
                    :value="item.classNo">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="changeClassVisible=false">关 闭</el-button>
            <el-button @click="changeClassInfoHandle" type="primary">保存</el-button>
          </div>
        </template>
      </el-dialog>
      <DormFW v-if="dormFWRefVisible" ref="dormFWRef"></DormFW>
      <ShowMap v-if="baiduMapVisible" ref="baiduMapRef"></ShowMap>
    </basic-container>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, onMounted } from 'vue'
import { defineAsyncComponent } from 'vue'
import { Search, Delete, Download, ZoomIn, Edit } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useUserInfo } from '/@/stores/userInfo'
import { useMessage } from '/@/hooks/message'
import { useMessageBox } from '/@/hooks/message'
import axios from 'axios'
import { list } from '@/api/recruit/recruitstudentplangroup'
import {
  delObj,
  exportZip,
  classPage,
  leaveSchool,
  rePush,
  updateInfo,
  yjOut,
  toWord,
  sureLQTZ,
  tbStuWork,
  sendImg,
  oneClass,
  oneStuNo,
  changeClassInfo, getMajorClass
} from '@/api/recruit/recruitstudentsignup'
import global from '@/components/tools/commondict'
import { getClassListByRole, getDeptList, queryAllClassByInfo } from "@/api/basic/basicclass"
import {listPlanByCondition as planMajor} from "@/api/recruit/recruitstudentplan"
import { getTypeValue } from "@/api/admin/dict"
import { getUserListByRole } from "@/api/admin/user"
import { ROLE_CODE } from "@/config/global"
import { updateFs } from "@/api/finance/financenormalstu"
import { showLoading, hideLoading } from '@/api/asset/loading'

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'))

// 使用 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 getLabelValueByPropes = (list: any[], key: string, props: { key: string, value: string }) => {
  return global.getLabelValueByPropes(list, key, props)
}

const getLabelValueByPropes2 = (list: any[], key: string, props: { key: string, value: string }) => {
  return global.getLabelValueByPropes2(list, key, props)
}

// 表单引用
const searchFormRef = ref()
const formRef = ref()
const addOrUpdateRef = ref()
const majorChangeRef = ref()
const updateRef = ref()
const dormFWRef = ref()
const baiduMapRef = ref()
const iframeRef = ref()

// 响应式数据
const changeForm = reactive({
  id: '',
  oldClass: "",
  classCode: "",
  classNo: ""
})

const dataForm = reactive({
  groupId: '',
  xy: "",
  confirmedMajor: "",
  degreeOfEducation: "",
  isAccommodation: "",
  isMinimumLivingSecurity: "",
  search: "",
  auditor: "",
  isNewCity: "",
  startDate: "",
  endDate: "",
  paystatus: "",
  graPic: "",
  pushed: "",
  wishMajorOne: "",
  isTb: '',
  classCode: "",
  auditStatus: "",
  type: "",
  isOut: "",
  isBackTz: ""
})

const id = ref("")
const pdfPath = ref("")
const delayPayTime = ref("")
const auditorList = ref<any[]>([])
const isBackTzList = [{ label: "未打印", value: "0" }, { label: "已打印", value: "1" }]
const paystatusList = [{ label: "已缴费", value: "10" }, { label: "未缴费", value: "0" }, { label: "部分缴费", value: "5" }]
const planList = ref<any[]>([])
const eduList = ref<any[]>([])
const planMajorList = ref<any[]>([])
const auditStatusList = [{ label: "未录取", value: "-20" }, { label: "待审核", value: "0" }, { label: "已录取", value: "20" }]
const yesNoList = [{ label: "否", value: "0" }, { label: "是", value: "1" }]
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 deptList = ref<any[]>([])
const dataList = ref<any[]>([])
const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)
const lqtzsShow = ref(false)
const dataListLoading = ref(false)
const addOrUpdateVisible = ref(false)
const changeClassVisible = ref(false)
const majorChangeVisible = ref(false)
const lqtzsVisible = ref(false)
const updateVisible = ref(false)

const payQrcode1 = ref("")
const showPrise1 = ref(false)
const payQrcode1Msg = ref("")
const payQrcode2 = ref("")
const payQrcode2Msg = ref("")
const showPrise2 = ref(false)
const payQrcode3 = ref("")
const payQrcode3Msg = ref("")
const showPrise3 = ref(false)
const dialogFormVisible = ref(false)
const delayPayTimeVisible = ref(false)
const dormFWRefVisible = ref(false)
const baiduMapVisible = ref(false)
const tableData = ref<any[]>([])
const classList = ref<any[]>([])
const changeClassList = ref<any[]>([])

// 日期禁用函数
const startDateDisabled = (time: Date) => {
  if (dataForm.endDate) {
    return new Date(dataForm.endDate).getTime() < time.getTime()
  }
  return false
}

const endDateDisabled = (time: Date) => {
  if (dataForm.startDate) {
    return new Date(dataForm.startDate).getTime() > time.getTime()
  }
  return false
}
// 方法定义
// 查找所有班级
const getClassData = () => {
  getClassListByRole().then((data: any) => {
    classList.value = data.data
  })
}
const sendImgHandle = () => {
  useMessageBox().confirm('是否确认同步招生图片到市平台？请谨慎操作').then(() => {
    return sendImg()
  }).then(() => {
    message.success('同步图片请求已发起,请耐心等待')
  }).catch(() => {
    hideLoading()
  })
}
const tbStuWorkHandle = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
    return
  }
  useMessageBox().confirm('是否确认同步学工？请谨慎操作').then(() => {
    showLoading()
    return tbStuWork(dataForm)
  }).then(() => {
    hideLoading()
    message.success('同步完成')
    getDataList()
  }).catch(() => {
    hideLoading()
  })
}
const oneClassHandle = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
    return
  }
  useMessageBox().confirm('是否确认一键分配班级？请谨慎操作').then(() => {
    showLoading()
    return oneClass(dataForm)
  }).then(() => {
    hideLoading()
    message.success('分配完成')
    getDataList()
  }).catch(() => {
    hideLoading()
  })
}
const oneStuNoHandle = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
    return
  }
  useMessageBox().confirm('是否确认一键分配学号？请谨慎操作').then(() => {
    showLoading()
    return oneStuNo(dataForm)
  }).then(() => {
    hideLoading()
    message.success('分配完成')
    getDataList()
  }).catch(() => {
    hideLoading()
  })
}
const downZip = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
    return
  }
  showLoading()
  exportZip(dataForm).then((res: any) => {
    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 yjOutHandle = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
    return
  }
  useMessageBox().confirm('是否确认一键判断是否超出住宿范围？请谨慎操作').then(() => {
    return yjOut({ groupId: dataForm.groupId })
  }).then(() => {
    message.success('操作成功')
    getDataList()
  })
}

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

const handleExport = () => {
  if (dataForm.groupId == '') {
    message.warning('招生计划不能为空')
    return
  }
  exportExcel(dataForm, '/recruit/recruitstudentsignup/exportShift').then((res: any) => {
    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 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: any) => {
    const blob = new Blob([res.data])
    let fileName = ""
    if (type == 1) {
      fileName = '延迟缴费名单导出.xlsx'
    } else {
      fileName = '超时缴费名单导出.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 init = () => {
  // 查询二级学院信息
  getDeptList().then((data: any) => {
    deptList.value = data.data
  })
  getClassData()
  list().then((data: any) => {
    planList.value = data.data
    if (planList.value.length > 0) {
      dataForm.groupId = planList.value[0].id
    }
    getDataList()
    chanMajor()
  })
  getTypeValue('finance_student_source').then((res: any) => {
    eduList.value = res.data
  })
  // 所有经办人
  getUserListByRole(ROLE_CODE.ROLE_RECRUIT_SECOND).then((res: any) => {
    auditorList.value = res.data
    getUserListByRole(ROLE_CODE.ROLE_RECRUIT).then((re: any) => {
      re.data.forEach((r: any) => {
        auditorList.value.push(r)
      })
      auditorList.value = unique(auditorList.value)
    })
  })
}

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 = []
  planMajor({ groupId: dataForm.groupId }).then((data: any) => {
    planMajorList.value = data.data
  })
}

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

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

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

// 当前页
const currentChangeHandle = (val: number) => {
  pageIndex.value = val
  getDataList()
}
const changeclass = (row: any) => {
  changeClassList.value = []
  getMajorClass(row).then((response: any) => {
    changeClassList.value = response.data
    changeClassVisible.value = true
    changeForm.id = row.id
    changeForm.classCode = ''
    changeForm.classNo = ''
    changeForm.oldClass = row.classCode
  })
}

// 新增 / 修改
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 majorChangeHandle = (id: string) => {
  majorChangeVisible.value = true
  nextTick(() => {
    majorChangeRef.value?.init(id)
  })
}

const changeClassInfoHandle = () => {
  if (changeForm.classNo == '') {
    message.error('调整班级不能空')
    return
  }

  changeClassList.value.forEach((e: any) => {
    if (e.classNo == changeForm.classNo) {
      changeForm.classCode = e.classCode
    }
  })
  if (changeForm.oldClass == changeForm.classCode) {
    message.error('调整班级不能和原班级相同')
    return
  }
  useMessageBox().confirm('是否确认调整班级操作？请谨慎操作').then(() => {
    return changeClassInfo(changeForm)
  }).then(() => {
    message.success('操作成功')
    changeClassVisible.value = false
    getDataList()
  })
}

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

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

const resetForm = (formName: string) => {
  if (formName === 'searchFormRef') {
    searchFormRef.value?.resetFields()
  } else if (formName === 'formRef') {
    formRef.value?.resetFields()
  }
}
// 使用插槽  缴费状态
const getStatus = (type: string) => {
  if (type == '0') {
    return '未缴费'
  } else if (type == '5') {
    return '部分缴费'
  } else if (type == '10') {
    return '已缴费'
  }
  return ''
}

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

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

const lqtz = (row: any) => {
  id.value = row.id
  pdfPath.value = ""
  if (row.isBackTz == '0') {
    lqtzsShow.value = true
  } else {
    lqtzsShow.value = false
  }
  toWord(row).then((res: any) => {
    pdfPath.value = "/recruit/file/previewPdf?filePath=" + encodeURIComponent(res.data)
    lqtzsVisible.value = true
  })
}

const infoTable = (row: any) => {
  window.open("printRecruitedStu.html?appId=" + row.id)
}

const suerLQTZ = () => {
  useMessageBox().confirm('是否确认已打印本通知书？请谨慎操作').then(() => {
    return sureLQTZ({ id: id.value })
  }).then(() => {
    message.success('保存成功')
    lqtzsVisible.value = false
    getDataList()
  })
}

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

const delayPayTimeSet = (row: any) => {
  delayPayTime.value = ''
  id.value = row.id
  if (row.delayPaymentTime) {
    delayPayTime.value = row.delayPaymentTime
  }
  delayPayTimeVisible.value = true
}

const updateInfoHandle = () => {
  useMessageBox().confirm('是否确认进度延迟收费操作？请谨慎操作').then(() => {
    return updateInfo({ delayPaymentTime: delayPayTime.value, id: id.value })
  }).then(() => {
    delayPayTimeVisible.value = false
    message.success('延迟收费修改成功')
    getDataList()
  })
}

const updateFS = () => {
  updateFs({ "serialNumber": tableData.value[0].serialNumber.substring(1, tableData.value[0].serialNumber.length) }).then(() => {
    ElNotification.success({
      title: '成功',
      message: '已提交查询请求，请等待1分钟后重新查询'
    })
    dialogFormVisible.value = false
    getDataList()
  })
}

const showPayCode = (row: any) => {
  showPrise1.value = false
  showPrise2.value = false
  showPrise3.value = false

  // 置空
  payQrcode1.value = ""
  payQrcode2.value = ""
  payQrcode3.value = ""

  if (row.clfPayCode == "" || row.clfPayCode == undefined) {
    payQrcode1Msg.value = ""
    showPrise1.value = false
  } else {
    payQrcode1Msg.value = "材料费、代办费"
    showPrise1.value = true
    payQrcode1.value = 'https://jscz.govpay.ccb.com/online/fsjf?PyF_BillNo=' + row.clfPayCode + '&Verf_CD=blank&Admn_Rgon_Cd=320400'
  }

  if (row.xfPayCode == "" || row.xfPayCode == undefined) {
    payQrcode2Msg.value = ""
    showPrise2.value = false
  } else {
    payQrcode2Msg.value = "学费"
    showPrise2.value = true
    payQrcode2.value = 'https://jscz.govpay.ccb.com/online/fsjf?PyF_BillNo=' + row.xfPayCode + '&Verf_CD=blank&Admn_Rgon_Cd=320400'
  }

  if (row.zdbPayCode == "" || row.zdbPayCode == undefined) {
    payQrcode3Msg.value = ""
    showPrise3.value = false
  } else {
    payQrcode3Msg.value = "中德班学费"
    showPrise3.value = true
    payQrcode3.value = 'https://jscz.govpay.ccb.com/online/fsjf?PyF_BillNo=' + row.zdbPayCode + '&Verf_CD=blank&Admn_Rgon_Cd=320400'
  }

  tableData.value = []
  tableData.value.push(row)
  dialogFormVisible.value = true
}

// 初始化
onMounted(() => {
  init()
})
</script>
