package com.zjrs.zwnw.sxgl.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.mohrss.leaf.core.framework.persistens.PageResult;
import org.mohrss.leaf.core.framework.web.controller.AjaxResponse;
import com.zjrs.zwnw.sxgl.bpo.JcsxqdkBPO;
import com.zjrs.zwnw.sxgl.dto.SxExportQueryDTO;
import com.zjrs.zwnw.sxgl.dto.SxpzxxXsUpdateDTO;
import com.zjrs.zwnw.sxgl.dto.SxtempQueryDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;

@Api("基础事项清单库")
@RestController
@RequestMapping("/api/sxgl/jcsxqdk")
public class JcsxqdkController {
    private static final Logger LOG = LoggerFactory.getLogger(JcsxqdkController.class);

    @Resource
    private JcsxqdkBPO jcsxqdkBPO;

    @ApiOperation(value = "获取导入结果统计", notes = "获取导入结果统计")
    @PostMapping("/getDrjgtj")
    public AjaxResponse getDrjgtj(@RequestBody @Valid SxtempQueryDTO dto) {
        LOG.info("获取导入结果统计开始");
        AjaxResponse ajaxResponse = new AjaxResponse();
        Integer pagenum = dto.getPagenum();
        Integer pagesize = dto.getPagesize();
        try {
            PageResult pageResult = this.jcsxqdkBPO.getDrjgtj(dto, pagenum, pagesize);
            ajaxResponse.setData("data", pageResult);
            ajaxResponse.setData("pagesize", pagesize);
            ajaxResponse.setData("pagenum", pagenum);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
        }
        LOG.info("获取导入结果统计结束");
        return ajaxResponse;
    }

    @ApiOperation(value = "获取导入事项list", notes = "获取导入事项list")
    @PostMapping("/getDrjgList")
    public AjaxResponse getDrjgList(@RequestBody @Valid SxtempQueryDTO dto) {
        LOG.info("获取导入事项列表开始");
        AjaxResponse ajaxResponse = new AjaxResponse();
        Integer pagenum = dto.getPagenum();
        Integer pagesize = dto.getPagesize();
        try {
            PageResult pageResult = this.jcsxqdkBPO.getDrjgList(dto, pagenum, pagesize);
            ajaxResponse.setData("data", pageResult);
            ajaxResponse.setData("pagesize", pagesize);
            ajaxResponse.setData("pagenum", pagenum);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
        }
        LOG.info("获取导入事项列表结束");
        return ajaxResponse;
    }

    @ApiOperation(value = "导出事项列表", notes = "导出事项列表")
    @PostMapping("/exportSx")
    public void exportSx(@RequestBody SxExportQueryDTO dto, HttpServletResponse res) throws IOException {
        LOG.info("导出事项列表开始");
        this.jcsxqdkBPO.exportSx(dto, res);
        LOG.info("导出事项列表结束");
    }

    @ApiOperation(value = "导入事项列表", notes = "导入事项列表")
    @PostMapping("/importSx")
    @ResponseBody
    public AjaxResponse importSx(MultipartFile file, HttpServletRequest request) {
        LOG.info("导入事项列表开始");
        AjaxResponse ajaxResponse = new AjaxResponse();
        if (file == null) {
            ajaxResponse.setAppcode("1");
            ajaxResponse.setMsg("导入失败，导入的文件无效。");
        } else {
            try {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) {
                    ajaxResponse.setAppcode("1");
                    ajaxResponse.setMsg("导入失败，导入的文件无效，文件格式只能为：xls或xlsx。");

                } else if (file.getSize() > 2 * 1048576) {
                    ajaxResponse.setAppcode("1");
                    ajaxResponse.setMsg("导入失败，导入的文件大小不能超过2M。");
                } else {
                    InputStream is = file.getInputStream();
                    Map<String, String> resultMap = this.jcsxqdkBPO.importSx(is);
                    ajaxResponse.setAppcode(resultMap.get("code"));
                    ajaxResponse.setMsg(resultMap.get("msg"));
                    ajaxResponse.setData("data", resultMap);
                }
            } catch (Exception e) {
                LOG.error(e.getMessage());
                ajaxResponse.setAppcode("1");
                ajaxResponse.setErrorMsg("导入失败，请检查导入文件是否正确。");
            }
        }
        LOG.info("导入事项列表结束");
        return ajaxResponse;
    }

    @ApiOperation(value = "下载导入模板", notes = "下载导入模板")
    @GetMapping(value = "/downloadTemplate")
    public void downloadTemplate(HttpServletRequest request, HttpServletResponse res) throws IOException {
        LOG.info("下载导入模板开始");
        InputStream is = JcsxqdkController.class.getClassLoader()
                .getResourceAsStream("templates" + File.separator + "sxgl" + File.separator + "import.xls");
        res.setContentType("application/octet-stream; charset=UTF-8");
        res.setHeader("Content-disposition",
                "attachment;filename=" + URLEncoder.encode("事项导入模板.xls", "UTF-8"));
        try {
            StreamUtils.copy(is, res.getOutputStream());
        } catch (IOException e) {
            LOG.error(e.getMessage());
        } finally {
            if (is != null) {
                is.close();
            }
            if (res.getOutputStream() != null) {
                res.getOutputStream().close();
            }
        }
        LOG.info("下载导入模板结束");
    }

    @ApiOperation(value = "保存事项基本信息", notes = "保存事项基本信息")
    @PostMapping("/saveSxjbxx")
    public AjaxResponse saveSxjbxx(@RequestBody SxpzxxXsUpdateDTO dto) {
        LOG.info("保存事项基本信息开始");
        AjaxResponse ajaxResponse = new AjaxResponse();
        try {
            Map<String, String> resultMap = this.jcsxqdkBPO.saveSxjbxx(dto);
            ajaxResponse.setAppcode(resultMap.get("code"));
            ajaxResponse.setMsg(resultMap.get("msg"));
        } catch (Exception e) {
            LOG.error(e.getMessage());
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
        }
        LOG.info("保存事项基本信息结束");
        return ajaxResponse;
    }
}
