package com.ruoyi.project.sems.safecheck.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.Texts;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.document.ZipUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.officeConvert.OfficeConvertController;
import com.ruoyi.project.sems.safecheck.mapper.TSpecDailycheckMapper;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import io.jsonwebtoken.lang.Assert;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.sems.safecheck.domain.TSpecDailycheck;
import com.ruoyi.project.sems.safecheck.service.ITSpecDailycheckService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 每日安全检查Controller
 *
 * @author Li
 * @date 2023-08-17
 */
@RestController
@RequestMapping("/safecheck/dailycheck")
public class TSpecDailycheckController extends BaseController {
    @Autowired
    private ITSpecDailycheckService tSpecDailycheckService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private OfficeConvertController officeConvertController;
    @Autowired
    private TSpecDailycheckMapper tSpecDailycheckMapper;
    /**
     * 查询每日安全检查列表
     */
    @PreAuthorize("@ss.hasPermi('safecheck:dailycheck:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSpecDailycheck tSpecDailycheck) {
        startPage();
        List<TSpecDailycheck> list = tSpecDailycheckService.selectTSpecDailycheckList(tSpecDailycheck);
        return getDataTable(list);
    }

    /**
     * 查询每日安全检查列表
     */
    @PreAuthorize("@ss.hasPermi('safecheck:dailycheck:list')")
    @GetMapping("/myList")
    public TableDataInfo myList(TSpecDailycheck tSpecDailycheck)
    {
        long userId = getUserId();
        tSpecDailycheck.setCheckerId(userId);
        startPage();
        List<TSpecDailycheck> list = tSpecDailycheckMapper.selectMyList(tSpecDailycheck);
        return getDataTable(list);
    }

    /**
     * 导出每日安全检查列表
     */
    @PreAuthorize("@ss.hasPermi('safecheck:dailycheck:export')")
    @Log(title = "每日安全检查", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSpecDailycheck tSpecDailycheck) {
        List<TSpecDailycheck> list = tSpecDailycheckService.selectTSpecDailycheckList(tSpecDailycheck);
        ExcelUtil<TSpecDailycheck> util = new ExcelUtil<TSpecDailycheck>(TSpecDailycheck.class);
        return util.exportExcel(list, "dailycheck");
    }

    /**
     * 获取每日安全检查详细信息
     */
    @PreAuthorize("@ss.hasPermi('safecheck:dailycheck:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tSpecDailycheckService.selectTSpecDailycheckById(id));
    }

    /**
     * 新增每日安全检查
     */
    @PreAuthorize("@ss.hasPermi('safecheck:dailycheck:add')")
    @Log(title = "每日安全检查", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSpecDailycheck tSpecDailycheck) {
        long userId = getUserId();
        tSpecDailycheck.setCheckerId(userId);
        tSpecDailycheck.setCreaterCode(userId);
        return toAjax(tSpecDailycheckService.insertTSpecDailycheck(tSpecDailycheck));
    }

    /**
     * 修改每日安全检查
     */
    @PreAuthorize("@ss.hasPermi('safecheck:dailycheck:edit')")
    @Log(title = "每日安全检查", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSpecDailycheck tSpecDailycheck) {
        return toAjax(tSpecDailycheckService.updateTSpecDailycheck(tSpecDailycheck));
    }

    /**
     * 修改每日安全检查
     */
    @PreAuthorize("@ss.hasPermi('safecheck:weekcheck:edit')")
    @Log(title = "每日安全检查确认", businessType = BusinessType.UPDATE)
    @GetMapping("batchConfirm/{ids}")
    public AjaxResult batchConfirm(@PathVariable Long[] ids)
    {
        return toAjax(tSpecDailycheckMapper.batchConfirmByids(ids));
    }

    /**
     * 修改每日安全检查
     */
    @PreAuthorize("@ss.hasPermi('safecheck:weekcheck:edit')")
    @Log(title = "每日安全检查确认取消", businessType = BusinessType.UPDATE)
    @GetMapping("batchCancel/{ids}")
    public AjaxResult batchCancel(@PathVariable Long[] ids)
    {
        return toAjax(tSpecDailycheckMapper.batchCancel(ids));
    }

    /**
     * 删除每日安全检查
     */
    @PreAuthorize("@ss.hasPermi('safecheck:dailycheck:remove')")
    @Log(title = "每日安全检查", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tSpecDailycheckService.deleteTSpecDailycheckByIds(ids));
    }

    /**
     * @return
     * @throws IOException
     */
    @RequestMapping("/downloadDailycheck")
    public AjaxResult downloadDailycheck(@RequestParam String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] ids = id.split(",");
        OutputStream out = null;
        out = response.getOutputStream();
        //存放所有文件路径
        List<String> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            String url = PreView(Long.parseLong(ids[i]));
            // 将路径字符串转换为Path对象
            Path path = Paths.get(url);
            // 获取文件名
            String fileName = path.getFileName().toString();
            list.add(fileName);
        }
        logger.info(JSON.toJSONString(list));
        return ZipUtil.createZip(RuoYiConfig.getProfile() + "/sems/dailycheck/", "",  "每日安全检查报告.zip", list, response);

    }

    /**
     * @return
     * @throws IOException
     */
    @RequestMapping("/downloadDailycheckPdf")
    public AjaxResult downloadDailycheckPdf(@RequestParam String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] ids = id.split(",");
        OutputStream out = null;
        out = response.getOutputStream();
        //存放所有文件路径
        List<String> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            String url = PreView(Long.parseLong(ids[i]));
            // 将路径字符串转换为Path对象
            Path path = Paths.get(url);
            // 获取文件名
            String fileName = path.getFileName().toString();
            fileName = officeConvertController.wordTransPdf(url);
            String newFilePath=fileName.replace("/profile","");
            logger.info("fileName:" + newFilePath);
            list.add(newFilePath);
        }
        logger.info(JSON.toJSONString(list));
        return ZipUtil.createZip(RuoYiConfig.getProfile() + "", "",  "每日安全检查报告PDF.zip", list, response);

    }

    /**
     * @param id
     * @return
     * @throws IOException
     */
    @GetMapping("/wordView/{id}")
    public AjaxResult wordView(@PathVariable Long id) throws IOException {
        //根据ID查询并生成
        String url = PreView(id);
        return AjaxResult.success(url);
    }

    /**
     * @param id 生成文件名
     * @return
     * @throws IOException
     */
    public String PreView(Long id) throws IOException {
        //根据ID查询并生成
        TSpecDailycheck t = tSpecDailycheckService.selectTSpecDailycheckById(id);
        String url = this.createcheck(t);
        return url;
    }

    /**
     * 生成wordt
     */
    public String createcheck(TSpecDailycheck tSpecDailycheck) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tSpecDailycheck);
        // 模板路径
        String templatePath = "static/word/sems/check/dailycheck.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "sems/dailycheck";
        // 生成word的文件名称
        String fileName =tSpecDailycheck.getPlantCode() +  "_" + DateUtils.dateTime(tSpecDailycheck.getCheckDate())+ "_" + tSpecDailycheck.getId() + ".docx";
        String wordPath = this.createWord(templatePath, fileDir, fileName, params);
        return wordPath;
    }

    /**
     * 获取word数据
     */
    public Map<String, Object> getWordData(TSpecDailycheck tSpecDailycheck) {
        Map<String, Object> params = new HashMap<>();
        params.put("plantCode", Texts.of(tSpecDailycheck.getPlantCode()).fontSize(11).bold().create());
        params.put("checkDate", Texts.of(DateUtils.dateTime(tSpecDailycheck.getCheckDate())).fontSize(11).bold().create());
        params.put("cPerson", Texts.of(tSpecDailycheck.getcPerson()).fontSize(10).bold().create());
        params.put("cDevice", Texts.of(tSpecDailycheck.getcDevice()).fontSize(10).bold().create());
        params.put("cSafety", Texts.of(tSpecDailycheck.getcSafety()).fontSize(10).bold().create());
        params.put("cEnv", Texts.of(tSpecDailycheck.getcEnv()).fontSize(10).bold().create());
        params.put("cGov", Texts.of(tSpecDailycheck.getcGov()).fontSize(10).bold().create());
        params.put("cComplaint", Texts.of(tSpecDailycheck.getcComplaint()).fontSize(10).bold().create());
        params.put("cOpinion", Texts.of(tSpecDailycheck.getcOpinion()).fontSize(10).bold().create());
        params.put("cOther", Texts.of(tSpecDailycheck.getcOther()).fontSize(10).bold().create());
        params.put("explain", Texts.of(tSpecDailycheck.getExplain()).fontSize(10).bold().create());

        SysUser sysUser = userService.selectUserById(tSpecDailycheck.getCheckerId());
        if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
            params.put("checkerNameP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(80, 40).create());
        } else {
            params.put("checkerName", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
        }
        if (!StringUtils.isEmpty(tSpecDailycheck.getAgentName())) {
            params.put("agentName", Texts.of(" 代 " + tSpecDailycheck.getAgentName()).fontSize(10).bold().create());
        }

        // 渲染文本
        return params;
    }

    /**
     * @param templatePath word模板文件路径
     * @param fileDir      生成的文件存放地址
     * @param fileName     生成的文件名
     * @param paramMap     参数集合
     * @return 返回word生成的路径
     */
    public String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) throws IOException {
        Assert.notNull(templatePath, "word模板文件路径不能为空");
        Assert.notNull(fileDir, "生成的文件存放地址不能为空");
        Assert.notNull(fileName, "生成的文件名不能为空");
        File dir = new File(fileDir);
        if (!dir.exists()) {
            logger.info("目录不存在，创建文件夹{}!", fileDir);
            dir.mkdirs();
        }
        fileName = fileName.replaceAll("/", "_"); //替换文件中敏感字段
        logger.info("目录文件{}!", fileName);
        String filePath = fileDir + "/" + fileName;
        logger.info("目录{}!", filePath);
        // 读取模板渲染参数
        InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath);
        XWPFTemplate template = XWPFTemplate.compile(is).render(paramMap);
        try {
            // 将模板参数写入路径
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }
        String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getFilePath("/" + "sems/dailycheck"), fileName);
        return pathFileName;
    }

    /**
     * @param
     * @return 映射签名的文件名
     * @throws IOException
     */
    public String fileName(String filepath) {
        String newFilePath = filepath.replace("/profile", "");
        String pathName = RuoYiConfig.getProfile() + newFilePath;
        return pathName;
    }
}
