package com.cpms.project.training.controller;

import com.cpms.common.annotation.Log;
import com.cpms.common.config.RuoYiConfig;
import com.cpms.common.core.controller.BaseController;
import com.cpms.common.core.domain.AjaxResult;
import com.cpms.common.core.page.TableDataInfo;
import com.cpms.common.enums.BusinessType;
import com.cpms.common.utils.DateUtils;
import com.cpms.common.utils.StringUtils;
import com.cpms.common.utils.file.FileUploadUtils;
import com.cpms.common.utils.poi.ExcelUtil;
import com.cpms.project.plant.domain.TStaffmgr;
import com.cpms.project.plant.service.ITStaffmgrService;
import com.cpms.project.training.domain.TTrainRoster;
import com.cpms.project.training.service.ITTrainRosterService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.Tables;
import com.deepoove.poi.data.Texts;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 培训签字Controller
 *
 * @author ruoyi
 * @date 2023-08-03
 */
@RestController
@RequestMapping("/training/roster")
public class TTrainRosterController extends BaseController {
    @Autowired
    private ITTrainRosterService tTrainRosterService;
    @Autowired
    private ITStaffmgrService tStaffmgrService;

    /**
     * 查询培训签字列表
     */
    @PreAuthorize("@ss.hasPermi('training:roster:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTrainRoster tTrainRoster) {
        startPage();
        List<TTrainRoster> list = tTrainRosterService.selectTTrainRosterList(tTrainRoster);
        return getDataTable(list);
    }

    /**
     * 导出培训签字列表
     */
    @PreAuthorize("@ss.hasPermi('training:roster:export')")
    @Log(title = "培训签字", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TTrainRoster tTrainRoster) {
        List<TTrainRoster> list = tTrainRosterService.selectTTrainRosterList(tTrainRoster);
        ExcelUtil<TTrainRoster> util = new ExcelUtil<TTrainRoster>(TTrainRoster.class);
        util.exportExcel(list, "培训签字数据");
    }

    /**
     * 获取培训签字详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:roster:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTrainRosterService.selectTTrainRosterById(id));
    }

    /**
     * 新增培训签字
     */
    @PreAuthorize("@ss.hasPermi('training:roster:add')")
    @Log(title = "培训签字", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTrainRoster tTrainRoster) {
        return toAjax(tTrainRosterService.insertTTrainRoster(tTrainRoster));
    }

    /**
     * 修改培训签字
     */
    @PreAuthorize("@ss.hasPermi('training:roster:edit')")
    @Log(title = "培训签字", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTrainRoster tTrainRoster) {
        return toAjax(tTrainRosterService.updateTTrainRoster(tTrainRoster));
    }

    /**
     * 删除培训签字
     */
    @PreAuthorize("@ss.hasPermi('training:roster:remove')")
    @Log(title = "培训签字", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tTrainRosterService.deleteTTrainRosterByIds(ids));
    }

    @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查询并生成
        TTrainRoster tTrainRoster = tTrainRosterService.selectTTrainRosterById(id);
        return this.createMeetingWord(tTrainRoster);
    }

    public String createMeetingWord(TTrainRoster tTrainRoster) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tTrainRoster);
        // 模板路径

        String templatePath;
        if (tTrainRoster.getExportType() == 1) {
            templatePath = "static/word/train.docx";
        } else {
            templatePath = "static/word/train2.docx";
        }
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "meeting";
        // 生成word的文件名称
        String fileName = DateUtils.dateTime() + "_培训签字表.docx";
        return createWord(templatePath, fileDir, fileName, params);
    }

    public Map<String, Object> getWordData(TTrainRoster tTrainRoster) {
        Map<String, Object> params = new HashMap<>();
        params.put("date", Texts.of(DateUtils.parseDateToStr("yyyy-MM-dd", tTrainRoster.getTrainStartDate()) + " ~ " + DateUtils.parseDateToStr("yyyy-MM-dd", tTrainRoster.getTrainEndDate())).fontSize(10).bold().create());
        params.put("time", Texts.of(tTrainRoster.getTrainDuration()).fontSize(10).bold().create());
        params.put("topic", Texts.of(String.valueOf(tTrainRoster.getTopic())).fontSize(10).bold().create());
        params.put("material", Texts.of(tTrainRoster.getMaterial()).fontSize(10).bold().create());
        params.put("trainer", Texts.of(tTrainRoster.getTrainer()).fontSize(10).bold().create());
        params.put("participants", Texts.of(tTrainRoster.getParticipants()).fontSize(10).bold().create());
        params.put("content", Texts.of(tTrainRoster.getContent()).fontSize(10).bold().create());
        if (tTrainRoster.getExportType() == 1)
            params.put("table", replaceTextInParagraph(tTrainRoster));
        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("/" + "meeting"), fileName);
    }

    private Object replaceTextInParagraph(TTrainRoster tTrainRoster) {
        ArrayList<RowRenderData> rowDatas = new ArrayList<>();
        // 表头
        if (StringUtils.isNotEmpty(tTrainRoster.getTeams())) {
            TStaffmgr staffmgr = new TStaffmgr();
            for (String team : tTrainRoster.getTeams().split(",")) {
                staffmgr.setTeam(team);
                List<TStaffmgr> tStaffmgrs = tStaffmgrService.selectStaffByTeam(staffmgr);
                if (CollectionUtils.isNotEmpty(tStaffmgrs)) {
                    rowDatas.add(Rows.of(tStaffmgrs.get(0).getTeam(), "", "", "").center().textFontSize(10).create());
                    for (int i = 0; i < tStaffmgrs.size(); i++) {
                        if (tStaffmgrs.size() - 1 == i)
                            rowDatas.add(Rows.of(tStaffmgrs.get(i).getName(), "", "", "").center().textFontSize(10).create());
                        else
                            rowDatas.add(Rows.of(tStaffmgrs.get(i).getName(), "", tStaffmgrs.get(i + 1).getName(), "").center().textFontSize(10).create());
                        i++;
                    }
                }
                rowDatas.add(Rows.of("", "", "", "").textFontSize(10).create());
                rowDatas.add(Rows.of("", "", "", "").textFontSize(10).create());
            }
        }
        if (StringUtils.isNotEmpty(tTrainRoster.getNameList())) {
//            rowDatas.add(Rows.of("参与培训的人员名单", "", "", "").center().textBold().textFontSize(10).create());
            String[] strings = tTrainRoster.getNameList().split("，");
            for (int i = 0; i < strings.length; i++) {
                if (strings.length - 1 == i)
                    rowDatas.add(Rows.of(strings[i], "", "", "").center().textFontSize(10).create());
                else
                    rowDatas.add(Rows.of(strings[i], "", strings[i + 1], "").center().textFontSize(10).create());
                i++;
            }
            rowDatas.add(Rows.of("", "", "", "").textFontSize(10).create());
            rowDatas.add(Rows.of("", "", "", "").textFontSize(10).create());
        }
        return Tables.of(rowDatas.toArray(new RowRenderData[0])).width(18.29, new double[]{18.29 * 0.25, 18.29 * 0.25, 18.29 * 0.25, 18.29 * 0.25}).create();
    }
}
