<!--
  -    Copyright (c) 2018-2025, cyweb All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  -
  -->

<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <el-form :model="queryForm" inline ref="searchFormRef">
        <el-form-item label="招生计划" prop="groupId">
          <el-select v-model="queryForm.groupId" filterable clearable placeholder="请选择招生计划">
            <el-option
              v-for="item in planList"
              :key="item.id"
              :label="item.groupName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="唯一号/姓名/身份证号" prop="search">
          <el-input v-model="queryForm.search" clearable placeholder="唯一号/姓名/身份证号/学校名称" />
        </el-form-item>
        <el-form-item label="异动审核" prop="isMajorChange">
          <el-select v-model="queryForm.isMajorChange" filterable clearable placeholder="请选择异动审核">
            <el-option
              v-for="item in majorChangeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getDataList">查询</el-button>
          <el-button icon="Refresh" class="ml10" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        ref="tableRef"
        :data="state.dataList"
        v-loading="state.loading"
        border
        stripe
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="type" label="异动类型" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ getTypeLabel(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名[唯一号]" width="140" align="center" show-overflow-tooltip />
        <el-table-column prop="majorChangeInfo" label="专业变更情况" align="center" show-overflow-tooltip />
        <el-table-column label="学费变更情况" align="center">
          <el-table-column prop="dbName" label="费用类型" align="center" show-overflow-tooltip />
          <el-table-column prop="dbOldValue" label="原费用" align="center" show-overflow-tooltip />
          <el-table-column prop="dbNewValue" label="新费用" align="center" show-overflow-tooltip />
          <el-table-column prop="dbType" label="变更类型" align="center" show-overflow-tooltip />
          <el-table-column prop="dbChangeValue" label="变更金额" align="center" show-overflow-tooltip />
        </el-table-column>
        <el-table-column label="分数变更情况" align="center">
          <el-table-column prop="scoreName" label="分数类型" align="center" show-overflow-tooltip />
          <el-table-column prop="scoreOldValue" label="原分值" align="center" show-overflow-tooltip />
          <el-table-column prop="scoreNewValue" label="新分值" align="center" show-overflow-tooltip />
        </el-table-column>
        <el-table-column prop="createBy" label="异动发起人" align="center" show-overflow-tooltip />
        <el-table-column prop="createDate" label="异动时间" align="center" show-overflow-tooltip />
        <el-table-column prop="remarks" label="备注信息" align="center" show-overflow-tooltip />
        <el-table-column prop="isMajorChange" label="异动审核" width="110" align="center" show-overflow-tooltip>
          <template #default="scope">
            <AuditState :state="scope.row.isMajorChange" :options="auditStateOptions" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button
              v-if="permissions.recruit_recruitstudentsignupturnover_edit && scope.row.isMajorChange == '1'"
              type="primary"
              link
              icon="EditPen"
              @click="majorchange(scope.row.id, scope.row.groupId)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-bind="state.pagination"
        @current-change="currentChangeHandle"
        @size-change="sizeChangeHandle"
      />

      <!-- 异动审核弹窗 -->
      <el-dialog v-model="majorChangeVisible" title="异动审核" width="600px"> 
        <el-form :model="exarmForm" ref="exarmFormRef" label-width="80px" :rules="dataRule">
          <el-form-item label="审核结果" prop="isMajorChange">
            <el-select v-model="exarmForm.isMajorChange" filterable clearable placeholder="请选择审核结果" style="width: 100%">
              <el-option
                v-for="item in isMajorChangeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审核意见" prop="remarks">
            <el-input 
              type="textarea" 
              placeholder="请输入审核内容" 
              :autosize="{ minRows: 2, maxRows: 4 }" 
              style="width: 100%" 
              v-model="exarmForm.remarks" 
              maxlength="20"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="update">保存</el-button>
            <el-button @click="cancelPlace">关闭</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts" name="recruitstudentsignupturnover">
import { ref, reactive, computed, onMounted, defineAsyncComponent } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserInfo } from '/@/stores/userInfo'
import { BasicTableProps, useTable } from '/@/hooks/table'
import { useMessage } from '/@/hooks/message'
import { fetchList, putObj } from '/@/api/recruit/recruitstudentsignupturnover'
import { getList } from '/@/api/recruit/recruitstudentplangroup'
import type { StateOption } from '/@/components/AuditState/index.vue'

const AuditState = defineAsyncComponent(() => import('/@/components/AuditState/index.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 tableRef = ref()
const searchFormRef = ref()
const exarmFormRef = ref()

// 弹窗状态
const majorChangeVisible = ref(false)

// 数据
const planList = ref<any[]>([])
const typeList = ref([{ label: '专业变更', value: '1' }, { label: '退学', value: '2' }])

// 审核状态选项配置（用于 AuditState 组件和检索条件）
const auditStateOptions = ref<StateOption[]>([
  { value: '1', label: '待审核', type: 'warning', icon: 'fa-regular fa-clock', effect: 'light' },
  { value: '2', label: '驳回', type: 'danger', icon: 'fa-solid fa-circle-xmark', effect: 'dark' },
  { value: '3', label: '通过', type: 'success', icon: 'fa-solid fa-circle-check', effect: 'dark' }
])

// 从 auditStateOptions 派生检索条件列表（只包含 label 和 value）
const majorChangeList = computed(() => {
  return auditStateOptions.value.map(item => ({
    label: item.label,
    value: item.value
  }))
})

// 审核弹窗中的选项（只包含通过和驳回）
const isMajorChangeList = computed(() => {
  return auditStateOptions.value
    .filter(item => item.value === '2' || item.value === '3')
    .map(item => ({
      label: item.label,
      value: item.value
    }))
})

// 查询表单
const queryForm = reactive({
  groupId: '',
  search: '',
  isMajorChange: ''
})

// 审核表单
const exarmForm = reactive({
  id: '',
  isMajorChange: '',
  examRemark: '',
  groupId: '',
  remarks: ''
})

// 表单验证规则
const dataRule = {
  isMajorChange: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ]
}

// 获取异动类型标签
const getTypeLabel = (type: string) => {
  const item = typeList.value.find(item => item.value === type)
  return item ? item.label : ''
}


// 表格状态
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: queryForm,
  pageList: async (params: any) => {
    const response = await fetchList(params)
    return {
      data: {
        records: response.data.records,
        total: response.data.total
      }
    }
  },
  createdIsNeed: false
})

// 使用 table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, tableStyle } = useTable(state)

// 初始化
const init = async () => {
  try {
    const data = await getList()
    planList.value = data.data || []
    if (planList.value.length > 0) {
      queryForm.groupId = planList.value[0].id
    }
    getDataList()
  } catch (error) {
    message.error('初始化失败')
  }
}

// 打开审核弹窗
const majorchange = (id: string, groupId: string) => {
  exarmForm.id = id
  exarmForm.groupId = groupId
  exarmForm.isMajorChange = ''
  exarmForm.remarks = ''
  majorChangeVisible.value = true
}

// 取消审核
const cancelPlace = () => {
  majorChangeVisible.value = false
}

// 保存审核
const update = async () => {
  try {
    const valid = await exarmFormRef.value?.validate().catch(() => {})
    if (!valid) return
    
    await putObj(exarmForm)
    message.success('审核成功')
    majorChangeVisible.value = false
    getDataList()
  } catch (error: any) {
    message.error(error.msg || '审核失败')
  }
}

// 重置查询
const resetQuery = () => {
  searchFormRef.value?.resetFields()
  queryForm.groupId = ''
  queryForm.search = ''
  queryForm.isMajorChange = ''
  if (planList.value.length > 0) {
    queryForm.groupId = planList.value[0].id
  }
  getDataList()
}

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

<style lang="scss" scoped>
</style>
