package jnpf.culture.controller;

import com.github.pagehelper.PageInfo;
import jnpf.base.ActionResult;
import jnpf.base.vo.DownloadVO;
import jnpf.base.vo.PageListVO;
import jnpf.culture.service.CultureTextSettingService;
import jnpf.model.culture.dto.CultureTextSettingDto;
import jnpf.model.culture.dto.SettingQueryDto;
import jnpf.model.culture.vo.CultureTextSettingVo;
import jnpf.model.culture.vo.UploadInfoVo;
import jnpf.util.FtbUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 文化打卡 - 文字配置
 *
 * @author yanwenfu
 * @create 2025-12-23
 */
@RestController
@RequestMapping(value = "/culture/text-setting")
public class CultureTextSettingController {

    @Resource
    private CultureTextSettingService cultureTextSettingService;

    /**
     * 查询文字配置数量
     * @return jnpf.base.ActionResult<java.lang.Integer>
     */
    @GetMapping(value = "/count")
    public ActionResult<Integer> getCultureTextSettingCount() {

        Integer num = cultureTextSettingService.getCultureTextSettingCount();
        return ActionResult.success(num);
    }

    /**
     * 文字配置 - 列表(分页)
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.model.culture.vo.CultureTextSettingVo>
     */
    @GetMapping(value = "/page")
    public ActionResult<PageListVO<CultureTextSettingVo>> getCultureTextSettingList(SettingQueryDto queryDto) {

        PageInfo<CultureTextSettingVo> page = cultureTextSettingService.getCultureTextSettingList(queryDto);
        return ActionResult.page(page.getList(), FtbUtil.getPagination(page));
    }

    /**
     * 文字配置 - 新增
     * @param textSettingDto 文案设置dto
     * @return jnpf.base.ActionResult<java.lang.Object>
     */
    @PostMapping
    public ActionResult<Object> addTextSetting(@RequestBody @Valid CultureTextSettingDto textSettingDto) throws Exception {

        cultureTextSettingService.addTextSetting(textSettingDto);
        return ActionResult.success();
    }

    /**
     * 文字配置 - 编辑
     * @param textSettingDto 文案设置dto
     * @return jnpf.base.ActionResult<java.lang.Object>
     */
    @PutMapping(value = "/{id}")
    public ActionResult<Object> updateTextSetting(@PathVariable(value = "id") String id, @RequestBody @Valid CultureTextSettingDto textSettingDto) throws Exception {

        cultureTextSettingService.updateTextSetting(id, textSettingDto);
        return ActionResult.success();
    }

    /**
     * 文字配置 - 批量删除
     * @param ids 文案ids(英文逗号分隔)
     * @return jnpf.base.ActionResult<java.lang.Object>
     */
    @DeleteMapping(value = "/batch")
    public ActionResult<Object> deleteTextSettingBatch(@RequestParam(value = "ids") String ids) throws Exception {

        String[] split;
        try {
            split = ids.split(",");
        } catch (Exception e) {
            return ActionResult.fail("请选择要删除的文字配置");
        }
        cultureTextSettingService.deleteTextSettingBatch(List.of(split));
        return ActionResult.success();
    }

    /**
     * 文字配置 - 模板下载
     * @return jnpf.base.ActionResult<jnpf.base.vo.DownloadVO>
     */
    @GetMapping(value = "/template-download")
    public ActionResult<DownloadVO> templateDownload() {
        DownloadVO vo = DownloadVO.builder().build();
        try {
            vo.setName("文化打卡导入模板" + System.currentTimeMillis() + ".xlsx");
            vo.setUrl("https://jnpf-resource-1304460613.cos.ap-chengdu.myqcloud.com/jnpf-resources/TemplateFile/文化打卡导入模板.xlsx");
        } catch (Exception e) {
            return ActionResult.fail("下载模板失败...");
        }
        return ActionResult.success(vo);
    }

    /**
     * 文字配置 - 导入
     * @param file 文件
     * @return jnpf.base.ActionResult<java.lang.Object>
     */
    @PostMapping(value = "/import")
    public ActionResult<UploadInfoVo> textSettingImport(@RequestParam MultipartFile file) throws Exception {

        if (file == null || file.isEmpty()) {
            return ActionResult.fail("请上传文件");
        }

        // 校验文件后缀
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null ||
                !(originalFilename.endsWith(".xlsx") || originalFilename.endsWith(".xls"))) {
            return ActionResult.fail("文件格式错误，仅支持 .xlsx 或 .xls");
        }

        // 校验 Content-Type（防止随便改后缀）
        String contentType = file.getContentType();
        if (!isExcelContentType(contentType)) {
            return ActionResult.fail("文件类型非法，请上传 Excel 文件");
        }
        UploadInfoVo uploadInfo = cultureTextSettingService.textSettingImport(file);
        return ActionResult.success(uploadInfo);
    }

    private boolean isExcelContentType(String contentType) {
        if (contentType == null) {
            return false;
        }
        return contentType.equals("application/vnd.ms-excel")
                || contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    }
}
