<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="deptCode">
          <el-select v-model="dataForm.deptCode" 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="startDateDisabled" 
            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="endDateDisabled" 
            type="date"
          />
        </el-form-item>
        <el-form-item label="班级" prop="classNo">
          <el-select filterable clearable v-model="dataForm.classCode" placeholder="请选择班级">
            <el-option
              v-for="item in classList"
              :key="item.classCode"
              :label="item.classNo"
              :value="item.classCode">
            </el-option>
          </el-select>
        </el-form-item>
          </template>
          <!-- 可折叠的高级筛选条件 -->
          <template v-if="!visible">
        <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="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 yes_no_type"
              :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 yes_no_type"
              :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="请选择经办人">
            <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="请选择缴费状态">
            <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 yes_no_type"
              :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 yes_no_type"
              :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="isTb">
          <el-select v-model="dataForm.isTb" filterable clearable placeholder="请选择是否同步学工">
            <el-option
              v-for="item in yes_no_type"
              :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 @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="warning"
            plain
            icon="Download"
            @click="handleExport()">分班导出
          </el-button>
          <el-button
            v-if="hasAuth('recruit_banding')"
            class="ml10"
            type="danger"
            plain
            icon="Promotion"
            @click="oneClassHandle()">一键分班
          </el-button>
          <el-button
            v-if="hasAuth('recruit_banding')"
            class="ml10"
            type="danger"
            plain
            icon="Promotion"
            @click="oneStuNoHandle()">一键分学号
          </el-button>
          <el-button
            v-if="hasAuth('recruit_synchronous_stuwork')"
            class="ml10"
            type="primary"
            plain
            icon="Connection"
            @click="tbStuWorkHandle()">同步学工
          </el-button>
        </div>
      </el-row>

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

          <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"
            width="90"
            label="性别">
            <template #default="scope">
              <GenderTag :sex="scope.row.gender" />
            </template>
          </el-table-column>
          <el-table-column
            prop="idNumber"
            header-align="center"
            align="center"
            min-width="180"
            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="deptCode"
            header-align="center"
            align="center"
            label="学院">

            <template #default="scope">
              <span v-if="scope.row.auditStatus==20">{{getLabelValueByPropes(deptList,scope.row.deptCode,{'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"
            width="100"
            label="是否已同步">
            <template #default="scope">
              <el-tag :type="getYesNoType(scope.row.isTb)?.type">
                {{ getYesNoType(scope.row.isTb)?.label }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            header-align="center"
            align="center"
            width="180"
            label="操作">
            <template #default="scope">
              <el-button type="primary" link icon="Document" @click="addOrUpdateHandle(scope.row.id,0)">
                查看
              </el-button>
              <el-button
                v-if="hasAuth('recruit_banding') && scope.row.isTb=='0' && scope.row.classNo !=null"
                type="primary"
                link
                icon="Switch"
                @click="changeclass(scope.row)">
                调整班级
              </el-button>
            </template>
          </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-bind="state.pagination"
        @current-change="currentChangeHandle"
        @size-change="sizeChangeHandle"
      />
      <!-- 弹窗, 新增 / 修改 -->
      <TableForm ref="addOrUpdateRef" @refreshDataList="getDataList" ></TableForm>

      <el-dialog title="班级调整" v-model="changeClassVisible" width="600px"
                 @close="changeClassVisible=false">
        <el-form ref="formRef" :model="changeForm" label-width="80px">
            <el-form-item label="原班级">
              <el-select v-model="changeForm.oldClass" 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-form-item label="新班级">
              <el-select v-model="changeForm.classNo" filterable 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-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>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted, defineAsyncComponent } from 'vue'
import { useAuth } from '/@/hooks/auth'
import { useMessage } from '/@/hooks/message'
import { useMessageBox } from '/@/hooks/message'
import { BasicTableProps, useTable } from '/@/hooks/table'
import axios from 'axios'
import { getList } from '/@/api/recruit/recruitstudentplangroup'
import {
  classPage,
  tbStuWork,
  oneClass,
  oneStuNo,
  changeClassInfo,
  getMajorClass,
  queryAllRecruitUser
} from '/@/api/recruit/recruitstudentsignup'
import { getLabelValueByProps } from '/@/utils/dictLabel'
import { getClassListByRole, getDeptList } from "/@/api/basic/basicclass"
import {listPlanByCondition as planMajor} from "/@/api/recruit/recruitstudentplan"
import { getDictsByTypes } from "/@/api/admin/dict"
import { PUSHED_STATUS_LIST, PAY_STATUS_LIST, getStatusConfig } from "/@/config/global"
import { showLoading, hideLoading } from '/@/api/asset/loading'
import { useDict } from '/@/hooks/dict'

const TableForm = defineAsyncComponent(() => import('./detaiform.vue'))
const GenderTag = defineAsyncComponent(() => import('/@/components/GenderTag/index.vue'))
const { hasAuth } = useAuth()
// 使用 hooks
const message = useMessage()

// 辅助函数
const getLabelValueByPropes = (list: any[], key: string, props: { key: string, value: string }) => {
  return getLabelValueByProps(list, key, props)
}

const getLabelValueByPropes2 = (list: any[], key: string, props: { key: string, value: string }) => {
  if (!list || !Array.isArray(list)) return ''
  const item = list.find((it: any) => String(it[props.key]) === String(key))
  if (!item) return ''
  const majorName = item[props.value] ?? ''
  const years = item.learnYear != null ? `${item.learnYear}年制` : ''
  return years ? `${majorName}(${years})` : majorName
}

// 表单引用
const searchFormRef = ref()
const formRef = ref()
const tableRef = ref()
const addOrUpdateRef = ref()

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

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

const auditorList = ref<any[]>([])            // 缴费状态（字典 - 仅搜索表单使用）
// 搜索表单显示状态
const showSearch = ref(true)

// 列表数据
const planList = ref<any[]>([])
const eduList = ref<any[]>([])
const planMajorList = ref<any[]>([])
const deptList = ref<any[]>([])

// 缴费状态
const paystatusList = PAY_STATUS_LIST
// 来源
const isOutList = ref<any[]>([])
// 推送状态
const pushedList = PUSHED_STATUS_LIST

// 字典数据
const { yes_no_type } = useDict('yes_no_type')


// 表格状态
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: dataForm,
  pageList: async (params: any) => {
    params.auditStatus = '20'
    const response = await classPage(params)
    return {
      data: {
        records: response.data.records || [],
        total: response.data.total || 0
      }
    }
  },
  createdIsNeed: false
})

// 使用 table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, tableStyle } = useTable(state)
const changeClassVisible = ref(false)
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 getYesNoType = (status: string) => {
  let result: any = getStatusConfig(yes_no_type.value, status)
  result.value == '1' ? result.type = 'success' : result.type = 'danger'
  return result
}

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 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 init = () => {
  // 查询二级学院信息
  getDeptList().then((data: any) => {
    deptList.value = data.data
  })
  getClassData()
  getList().then((data: any) => {
    planList.value = data.data
    if (planList.value.length > 0) {
      dataForm.groupId = planList.value[0].id
    }
    getDataList()
    chanMajor()
  })
  
  // 批量获取字典数据
  getDictsByTypes(['finance_student_source', 'recruit_data_source']).then((res) => {
    eduList.value = res.data.finance_student_source || []
    isOutList.value = res.data.recruit_data_source || []
  })
  
  // 所有经办人
  queryAllRecruitUser().then((res: any) => {
    auditorList.value = res.data || []
  })
}

const chanMajor = () => {
  planMajorList.value = []
  planMajor({ groupId: dataForm.groupId }).then((data: any) => {
    planMajorList.value = data.data
  })
}

const handleFilter = () => {
  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) => {
  nextTick(() => {
    addOrUpdateRef.value?.init(id, type)
  })
}

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 resetForm = (formName: string) => {
  if (formName === 'searchForm') {
    searchFormRef.value?.formRef?.resetFields()
  } else if (formName === 'formRef') {
    formRef.value?.resetFields()
  }
}

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