package com.srs.web.controller.routine;

import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.srs.dormitory.domain.DmsOutsideAccommodationApply;
import com.srs.routine.domain.dto.RtEnlistmentReserveExportDto;
import com.srs.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.*;
import org.springframework.security.access.prepost.PreAuthorize;

import com.srs.routine.domain.RtEnlistmentReserve;
import com.srs.routine.service.IRtEnlistmentReserveService;
import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.poi.ExcelUtil;
import com.srs.common.enums.BusinessType;
import com.srs.common.annotation.Log;
import com.srs.common.core.page.TableDataInfo;

/**
 * 应征入伍保留学籍申请Controller
 *
 * @author srs
 * @date 2025-10-31
 */
@RestController
@RequestMapping("/routine/enlistmentReserve")
@Api(value = "应征入伍保留学籍申请管理", tags = "应征入伍保留学籍申请管理")
public class RtEnlistmentReserveController extends BaseController {
    @Autowired
    private IRtEnlistmentReserveService rtEnlistmentReserveService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询应征入伍保留学籍申请列表
     */
    @PreAuthorize("@ss.hasPermi('routine:enlistmentReserve:list')")
    @GetMapping("/list")
    @ApiOperation("查询应征入伍保留学籍申请列表")
    public TableDataInfo list(RtEnlistmentReserve rtEnlistmentReserve) {
        startPage();
        List<RtEnlistmentReserve> list = rtEnlistmentReserveService.selectRtEnlistmentReserveList(rtEnlistmentReserve);
        return getDataTable(list);
    }

    /**
     * 导出应征入伍保留学籍申请列表
     */
    @PreAuthorize("@ss.hasPermi('routine:enlistmentReserve:export')")
    @Log(title = "应征入伍保留学籍申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出应征入伍保留学籍申请列表")
    public void export(HttpServletResponse response, RtEnlistmentReserve rtEnlistmentReserve) {
        // 1. 查询原始数据列表
        List<RtEnlistmentReserve> originalList = rtEnlistmentReserveService.selectRtEnlistmentReserveList(rtEnlistmentReserve);

        // 2. 转换为导出DTO + 中文值转换
        List<RtEnlistmentReserveExportDto> exportList = originalList.stream()
                .map(this::convertToExportDto)
                .collect(Collectors.toList());

        // 3. 导出Excel（使用DTO的@Excel注解配置中文表头）
        ExcelUtil<RtEnlistmentReserveExportDto> util = new ExcelUtil<>(RtEnlistmentReserveExportDto.class);
        util.exportExcel(response, exportList, "应征入伍保留学籍申请数据");
    }
    /**
     * 原始实体转换为导出DTO，并处理值的中文转换
     */
    private RtEnlistmentReserveExportDto convertToExportDto(RtEnlistmentReserve source) {
        RtEnlistmentReserveExportDto dto = new RtEnlistmentReserveExportDto();

        // 1. 基础字段赋值（一一映射）
        dto.setApplyNo(source.getApplyNo());
        dto.setTeacherName(source.getTeacherName());
        dto.setStudentName(source.getStudentName());
        dto.setNation(sysDictDataService.selectDictLabel("rt_nation", source.getNation()));
        dto.setGrade(source.getGrade());
        dto.setStudentNo(source.getStudentNo());
        dto.setClassName(source.getClassName());
        dto.setMajor(source.getMajor());
        dto.setFamilyAddress(source.getFamilyAddress());
        dto.setParentPhone(source.getParentPhone());
        dto.setApplyReason(source.getApplyReason());
        dto.setReserveNo(source.getReserveNo());
        dto.setReserveStartDate(source.getReserveStartDate());
        dto.setReserveEndDate(source.getReserveEndDate());
//        dto.setApprovalNo(source.getApprovalNo());

        // 2. 核心：0/1等值转换为中文
        // 性别转换（1-男 0-女）
        if (source.getGender() != null) {
            dto.setGender("1".equals(source.getGender()) ? "男" : "0".equals(source.getGender()) ? "女" : source.getGender());
        }

        // 申请状态转换（0-草稿，1=待辅导员审批...7=驳回）
        if (source.getApplyStatus() != null) {
            dto.setApplyStatus(convertApplyStatus(source.getApplyStatus()));
        }

        return dto;
    }

    /**
     * 申请状态值转换为中文描述（适配String类型）
     */
    private String convertApplyStatus(Long status) {
        return switch (status.intValue()) {
            case 0 -> "草稿";
            case 1 -> "待辅导员审批";
            case 2 -> "待学务审批";
            case 3 -> "待二级学院审批";
            case 4 -> "待学籍管理科审批";
            case 5 -> "待教务处主管领导审批";
            case 6 -> "审批通过";
            case 7 -> "驳回";
            default -> status.toString();
        };
    }


    /**
     * 获取应征入伍保留学籍申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('routine:enlistmentReserve:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取应征入伍保留学籍申请详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(rtEnlistmentReserveService.selectRtEnlistmentReserveById(id));
    }

    /**
     * 获取应征入伍保留学籍申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('routine:enlistmentReserve:query')")
    @GetMapping(value = "/process/{processInstanceId}")
    @ApiOperation("获取应征入伍保留学籍申请详细信息")
    public AjaxResult getInfoByProcessInstanceId(@PathVariable("processInstanceId") String processInstanceId) {
        return success(rtEnlistmentReserveService.selectRtEnlistmentReserveByProcessInstanceId(processInstanceId));
    }

    /**
     * 新增应征入伍保留学籍申请
     */
    @PreAuthorize("@ss.hasPermi('routine:enlistmentReserve:add')")
    @Log(title = "应征入伍保留学籍申请", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ApiOperation("新增应征入伍保留学籍申请")
    public AjaxResult add(@RequestBody RtEnlistmentReserve rtEnlistmentReserve) {
        return success(rtEnlistmentReserveService.insertRtEnlistmentReserve(rtEnlistmentReserve));
    }

    /**
     * 批量插入应征入伍预约信息
     * @param list 预约信息列表
     * @return 插入结果
     */
    @PreAuthorize("@ss.hasPermi('routine:enlistmentReserve:add')")
    @Log(title = "应征入伍保留学籍申请", businessType = BusinessType.INSERT)
    @PostMapping("/batchInsert")
    @ApiOperation("新增应征入伍保留学籍申请")
    public AjaxResult batchInsert(@RequestBody List<RtEnlistmentReserve> list) {
        try {
            // 调用批量插入方法
            int insertCount = rtEnlistmentReserveService.batchInsertRtEnlistmentReserve(list);
            // 若依框架成功返回（带数据）
            return AjaxResult.success("批量插入成功，共插入" + insertCount + "条数据", insertCount);
        } catch (IllegalArgumentException e) {
            // 入参无效异常（如姓名/学号为空）
            return AjaxResult.error(e.getMessage());
        } catch (RuntimeException e) {
            // 重复数据异常
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            // 其他未知异常（若依框架建议记录日志）
            logger.error("批量插入应征入伍预约信息失败", e); // 继承BaseController自带logger
            return AjaxResult.error("批量插入失败：" + e.getMessage());
        }
    }

    /**
     * 修改应征入伍保留学籍申请
     */
    @PreAuthorize("@ss.hasPermi('routine:enlistmentReserve:edit')")
    @Log(title = "应征入伍保留学籍申请", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ApiOperation("修改应征入伍保留学籍申请")
    public AjaxResult edit(@RequestBody RtEnlistmentReserve rtEnlistmentReserve) {
        return toAjax(rtEnlistmentReserveService.updateRtEnlistmentReserve(rtEnlistmentReserve));
    }

    /**
     * 删除应征入伍保留学籍申请
     */
    @PreAuthorize("@ss.hasPermi('routine:enlistmentReserve:remove')")
    @Log(title = "应征入伍保留学籍申请", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    @ApiOperation("删除应征入伍保留学籍申请")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(rtEnlistmentReserveService.deleteRtEnlistmentReserveByIds(ids));
    }


    /**
     * 新增外宿申请
     */
    @PreAuthorize("@ss.hasPermi('dormitory:outsideAccommodationApply:add')")
    @Log(title = "外宿申请", businessType = BusinessType.INSERT)
    @PostMapping("/outsideAccommodationApply/add")
    @ApiOperation("新增外宿申请")
    public AjaxResult add(@RequestBody DmsOutsideAccommodationApply dmsOutsideAccommodationApply)
    {
        return success(rtEnlistmentReserveService.insertDmsOutsideAccommodationApply(dmsOutsideAccommodationApply));
    }

    /**
     * 修改外宿申请
     */
    @PreAuthorize("@ss.hasPermi('dormitory:outsideAccommodationApply:edit')")
    @Log(title = "外宿申请", businessType = BusinessType.UPDATE)
    @PostMapping("/outsideAccommodationApply/update")
    @ApiOperation("修改外宿申请")
    public AjaxResult edit(@RequestBody DmsOutsideAccommodationApply dmsOutsideAccommodationApply)
    {
        return toAjax(rtEnlistmentReserveService.updateDmsOutsideAccommodationApply(dmsOutsideAccommodationApply));
    }
}
