package org.dromara.main.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.main.domain.bo.MainStudentBo;
import org.dromara.main.domain.vo.MainStudentVo;
import org.dromara.main.service.IMainStudentService;
import org.dromara.system.service.ISysOssService;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.factory.OssFactory;
import org.dromara.common.translation.constant.TransConstant;
import org.dromara.main.domain.vo.MainStudentAppendixVo;
import org.dromara.system.domain.vo.SysOssVo;
import org.springframework.http.MediaType;
import org.dromara.common.core.utils.file.FileUtils;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.web.bind.annotation.*;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/main/student")
public class MainStudentController extends BaseController {

    private final IMainStudentService mainStudentService;
    private final ISysOssService sysOssService;

    /**
     * 查询学员列表
     */
//    @SaCheckPermission("main:student:list")
    @GetMapping("/list")
    public TableDataInfo<MainStudentVo> list(MainStudentBo bo, PageQuery pageQuery) {
        return mainStudentService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出学员列表
     */
//    @SaCheckPermission("main:student:export")
    @Log(title = "学员管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MainStudentBo bo, HttpServletResponse response) {
        List<MainStudentVo> list = mainStudentService.queryList(bo);
        ExcelUtil.exportExcel(list, "学员信息", MainStudentVo.class, response);
    }

    /**
     * 获取学员详细信息
     *
     * @param id 主键
     */
//    @SaCheckPermission("main:student:query")
    @GetMapping("/{id}")
    public R<MainStudentVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(mainStudentService.queryById(id));
    }

    /**
     * 新增学员
     */
//    @SaCheckPermission("main:student:add")
    @Log(title = "学员管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody MainStudentBo bo) {
        return toAjax(mainStudentService.insertByBo(bo));
    }

    /**
     * 修改学员
     */
//    @SaCheckPermission("main:student:edit")
    @Log(title = "学员管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody MainStudentBo bo) {
        return toAjax(mainStudentService.updateByBo(bo));
    }

    /**
     * 删除学员
     *
     * @param ids 主键串
     */
//    @SaCheckPermission("main:student:remove")
    @Log(title = "学员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(mainStudentService.deleteWithValidByIds(List.of(ids), true));
    }


    /**
     * 更新学员状态
     */
//    @SaCheckPermission("main:student:edit")
    @Log(title = "学员管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatus")
    public R<Void> updateStatus(@RequestBody MainStudentBo bo) {
        return toAjax(mainStudentService.updateStatus(bo.getId(), bo.getStatus()));
    }

    /**
     * 更新学员用户类型（黑名单管理）
     */
//    @SaCheckPermission("main:student:edit")
    @Log(title = "学员管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateUserType")
    public R<Void> updateUserType(@RequestBody MainStudentBo bo) {
        return toAjax(mainStudentService.updateUserType(bo.getId(), bo.getUserType()));
    }



    /**
     * 导出单人在线简历 (Excel)
     */
    @Log(title = "学员管理", businessType = BusinessType.EXPORT)
    @GetMapping("/exportResume/{id}")
    public void exportResume(@PathVariable Long id, HttpServletResponse response) {
        MainStudentVo vo = mainStudentService.queryById(id);
        if (vo == null) {
            throw new ServiceException("学员不存在");
        }
        // 包装成单行列表进行导出
        List<MainStudentVo> list = List.of(vo);
        ExcelUtil.exportExcel(list, vo.getName() + "_在线简历", MainStudentVo.class, response);
    }


    @Log(title = "学员管理", businessType = BusinessType.EXPORT)
    @GetMapping("/downloadResume/{studentId}")
    public void downloadResume(@PathVariable Long studentId, HttpServletResponse response) throws java.io.IOException {
        MainStudentVo vo = mainStudentService.queryById(studentId);
        if (vo == null || (vo.getResumeFile() == null && ObjectUtil.isEmpty(vo.getAppendixList()))) {
            throw new ServiceException("该学员未上传简历附件");
        }

        List<MainStudentAppendixVo> appendixList = vo.getAppendixList();
        if (ObjectUtil.isEmpty(appendixList)) {
            // 兜底逻辑：如果 appendixList 为空但 resumeFile 有值
            sysOssService.download(vo.getResumeFile(), response);
            return;
        }

        if (appendixList.size() == 1) {
            // 只有一个附件，直接下载原始文件
            sysOssService.download(appendixList.get(0).getOssId(), response);
        } else {
            // 多个附件，打包下载
            String zipName = vo.getName() + "_简历附件.zip";
            FileUtils.setAttachmentResponseHeader(response, zipName);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");

            try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
                for (MainStudentAppendixVo appendix : appendixList) {
                    SysOssVo sysOss = sysOssService.getById(appendix.getOssId());
                    if (sysOss != null) {
                        ZipEntry entry = new ZipEntry(sysOss.getFileName());
                        zos.putNextEntry(entry);
                        OssClient storage = OssFactory.instance(sysOss.getService());
                        // 使用 FilterOutputStream 包装，防止 storage.download 关闭 zos
                        storage.download(sysOss.getFileName(), new FilterOutputStream(zos) {
                            @Override
                            public void close() throws IOException {
                                // 忽略 close 调用，由外部 ZipOutputStream 控制
                            }
                        }, null);
                        zos.closeEntry();
                    }
                }
                zos.finish();
            }
        }
    }
}
