package com.ruoyi.project.shiftmgr.controller;


import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.Texts;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.project.shiftmgr.domain.TShiftLog;
import com.ruoyi.project.shiftmgr.service.ITShiftLogService;
import com.ruoyi.system.service.ISysUserService;
import io.jsonwebtoken.lang.Assert;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 轮班日志Controller
 *
 * @author ruoyi
 * @date 2023-08-17
 */
@RestController
@RequestMapping("/shiftmgr/log")
public class TShiftLogController extends BaseController {
    @Autowired
    private ITShiftLogService tShiftLogService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询轮班日志列表
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:log:list')")
    @GetMapping("/list")
    public AjaxResult list(TShiftLog tShiftLog) {
        startPage();
        List<TShiftLog> list = tShiftLogService.selectTShiftLogList(tShiftLog);
        return AjaxResult.success(getUserId().toString(), getDataTable(list));
    }

    @PreAuthorize("@ss.hasPermi('shiftmgr:log:list')")
    @GetMapping("/lastData")
    public AjaxResult lastData(TShiftLog tShiftLog) {
        tShiftLog.setToShiftSup(getUserId().toString());
        List<TShiftLog> list = tShiftLogService.selectTShiftLogList(tShiftLog);
        if (CollectionUtils.isNotEmpty(list)) {
            return AjaxResult.success(list.get(0));
        }
        return AjaxResult.success();
    }

    /**
     * 导出轮班日志列表
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:log:export')")
    @Log(title = "轮班日志", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TShiftLog tShiftLog) {
        List<TShiftLog> list = tShiftLogService.selectTShiftLogList(tShiftLog);
        ExcelUtil<TShiftLog> util = new ExcelUtil<TShiftLog>(TShiftLog.class);
        util.exportExcel(list, "轮班日志数据");
    }

    /**
     * 获取轮班日志详细信息
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:log:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tShiftLogService.selectTShiftLogById(id));
    }

    /**
     * 新增轮班日志
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:log:add')")
    @Log(title = "轮班日志", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TShiftLog tShiftLog) {
        tShiftLog.setCreaterCode(String.valueOf(getUserId()));
        tShiftLog.setCreatedate(new Date());
        return toAjax(tShiftLogService.insertTShiftLog(tShiftLog));
    }

    /**
     * 修改轮班日志
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:log:edit')")
    @Log(title = "轮班日志", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TShiftLog tShiftLog) {
        tShiftLog.setUpdaterCode(String.valueOf(getUserId()));
        tShiftLog.setUpdatedate(new Date());
        if (tShiftLog.getStatus() == 1)
            tShiftLog.setGiveOverTime(new Date());
        return toAjax(tShiftLogService.updateTShiftLog(tShiftLog));
    }

    /**
     * 删除轮班日志
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:log:remove')")
    @Log(title = "轮班日志", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tShiftLogService.deleteTShiftLogByIds(ids));
    }


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

    /**
     * @return
     * @throws IOException
     */
    public String PreView(Long id) throws IOException {
        //根据ID查询并生成
        TShiftLog tShiftLog = tShiftLogService.selectTShiftLogById(id);
        return this.createMeetingWord(tShiftLog);
    }

    public String createMeetingWord(TShiftLog tShiftLog) throws IOException {
        //生成word
        // 模板路径
        String templatePath;
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "shiftLog";
        // 生成word的文件名称
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");

        String fileName = format.format(tShiftLog.getTakeOverTime()) + "~" + format.format(tShiftLog.getGiveOverTime()) + "_交接班_轮班日志.docx";
        //渲染文本
        Map<String, Object> params = getWordData(tShiftLog);
        templatePath = "static/word/shiftLog.docx";
        return createWord(templatePath, fileDir, fileName, params);
    }

    public Map<String, Object> getWordData(TShiftLog tShiftLog) {
        Map<String, Object> params = new HashMap<>();
        params.put("shiftTeam", Texts.of(tShiftLog.getShiftTeam()).fontSize(10).create());
        params.put("takeOverTime", Texts.of(DateUtils.parseDateToStr("yyyy年MM月dd日 HH时mm分", tShiftLog.getTakeOverTime())).fontSize(10).create());
        params.put("giveOverTime", Texts.of(DateUtils.parseDateToStr("yyyy年MM月dd日 HH时mm分", tShiftLog.getGiveOverTime())).fontSize(10).create());
        params.put("tocp", Texts.of(tShiftLog.getTocp()).fontSize(10).create());
        params.put("ehs5sBriefing", Texts.of(tShiftLog.getEhs5sBriefing()).fontSize(10).create());
        params.put("soa", Texts.of(tShiftLog.getSoa()).fontSize(10).create());
        params.put("sh", Texts.of(tShiftLog.getSh()).fontSize(10).create());
        params.put("bdoc", Texts.of(tShiftLog.getBdoc()).fontSize(10).create());
        params.put("thfd", Texts.of(tShiftLog.getThfd()).fontSize(10).create());
        params.put("pthfUnit", Texts.of(tShiftLog.getPthfUnit()).fontSize(10).create());
        params.put("dbpd", Texts.of(tShiftLog.getDbpd()).fontSize(10).create());
        params.put("truss", Texts.of(tShiftLog.getTruss()).fontSize(10).create());
        params.put("pthfCus", Texts.of(tShiftLog.getPthfCus()).fontSize(10).create());
        params.put("bipus", Texts.of(tShiftLog.getBipus()).fontSize(10).create());
        params.put("lpgH2", Texts.of(tShiftLog.getLpgH2()).fontSize(10).create());
        params.put("q125601", Texts.of(tShiftLog.getQ125601()).fontSize(10).create());
        params.put("q125602", Texts.of(tShiftLog.getQ125602()).fontSize(10).create());
        params.put("q312018Q1", Texts.of(tShiftLog.getQ312018Q1()).fontSize(10).create());
        params.put("q312018Q2", Texts.of(tShiftLog.getQ312018Q2()).fontSize(10).create());
        params.put("q312018Q3", Texts.of(tShiftLog.getQ312018Q3()).fontSize(10).create());
        params.put("q312018Q4", Texts.of(tShiftLog.getQ312018Q4()).fontSize(10).create());
        params.put("q312000", Texts.of(tShiftLog.getQ312000()).fontSize(10).create());
        params.put("q312001", Texts.of(tShiftLog.getQ312001()).fontSize(10).create());
        params.put("epdOther", Texts.of(tShiftLog.getEpdOther()).fontSize(10).create());
        params.put("ehsOther", Texts.of(tShiftLog.getEhsOther()).fontSize(10).create());
        params.put("qar", Texts.of(tShiftLog.getQar()).fontSize(10).create());
        params.put("maEi", Texts.of(tShiftLog.getMaEi()).fontSize(10).create());
        params.put("maMechanical", Texts.of(tShiftLog.getMaMechanical()).fontSize(10).create());
        params.put("thirdPartyCommunication", Texts.of(tShiftLog.getThirdPartyCommunication()).fontSize(10).create());
        params.put("fampEi", Texts.of(tShiftLog.getFampEi()).fontSize(10).create());
        params.put("fampMechanical", Texts.of(tShiftLog.getFampMechanical()).fontSize(10).create());
        params.put("faop", Texts.of(tShiftLog.getFaop()).fontSize(10).create());
        params.put("comments", Texts.of(tShiftLog.getComments()).fontSize(10).create());
        SysUser ho = sysUserService.selectUserById(Long.valueOf(tShiftLog.getHoShiftSup()));
        SysUser to = sysUserService.selectUserById(Long.valueOf(tShiftLog.getToShiftSup()));
        if (ho != null)
            params.put("hoShiftSup", Texts.of(ho.getNickName()).fontSize(10).create());
        if (to != null)
            params.put("toShiftSup", Texts.of(to.getNickName()).fontSize(10).create());
        params.put("remarks", Texts.of(tShiftLog.getRemarks()).fontSize(10).create());
        return params;
    }

    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 = null;
        if (is != null) {
            template = XWPFTemplate.compile(is).render(paramMap);
        }
        try {
            // 将模板参数写入路径
            if (template != null) {
                template.writeToFile(filePath);
                template.close();
            }
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }
        return FileUploadUtils.getPathFileName(RuoYiConfig.getFilePath("/" + "shiftLog"), fileName);
    }
}
