package com.ruoyi.project.training.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.CellStyle;
import com.deepoove.poi.data.style.TableStyle;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.officeConvert.OfficeConvertController;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.training.domain.TTrainingbcc;
import com.ruoyi.project.training.domain.TTrainingbccDevice;
import com.ruoyi.project.training.mapper.TTrainingbccDeviceMapper;
import com.ruoyi.project.training.mapper.TTrainingbccMapper;
import com.ruoyi.project.training.service.ITTrainingbccService;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 装置培训跟踪bController
 *
 * @author ssy
 * @date 2024-06-19
 */
@RestController
@RequestMapping("/training/trainingbcc")
public class TTrainingbccController extends BaseController {
    @Autowired
    private ITTrainingbccService tTrainingbccService;
    @Resource
    private TTrainingbccDeviceMapper tTrainingbccDeviceMapper;
    @Resource
    private TTrainingbccMapper tTrainingbccMapper;
    @Autowired
    private ITStaffmgrService tStaffmgrService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Resource
    private OfficeConvertController officeConvertController;

    /**
     * 查询装置培训跟踪b列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TTrainingbcc tTrainingbcc) {
        startPage();
        List<TTrainingbcc> list = tTrainingbccService.selectTTrainingbccList(tTrainingbcc);
        for (TTrainingbcc t : list
        ) {
            TTrainingbccDevice device = new TTrainingbccDevice();
            device.setRegularId(t.getId());
            int all = tTrainingbccDeviceMapper.countTraining(device);

            device.setExamState(1l);
            int finish = tTrainingbccDeviceMapper.countTraining(device);
            t.setHaveTraining(finish);
            t.setMustTraining(all);
            if (all != 0) {
                String per = String.valueOf(finish * 100 / all);
                t.setTrainingPercent(per);
            } else {
                t.setTrainingPercent("0");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出装置培训跟踪b列表
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:export')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTrainingbcc tTrainingbcc) {
        List<TTrainingbcc> list = tTrainingbccService.selectTTrainingbccList(tTrainingbcc);
        ExcelUtil<TTrainingbcc> util = new ExcelUtil<TTrainingbcc>(TTrainingbcc.class);
        return util.exportExcel(list, "trainingbcc");
    }

    /**
     * 获取装置培训跟踪b详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTrainingbccService.selectTTrainingbccById(id));
    }

    /**
     * 获取装置培训跟踪b详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:query')")
    @GetMapping(value = "/staffIds/{id}")
    public AjaxResult getStaffIds(@PathVariable("id") Long id) {
        TTrainingbcc tTrainingbcc = tTrainingbccService.selectTTrainingbccById(id);
        TTrainingbccDevice param = new TTrainingbccDevice();
        param.setRegularId(id);
        List<TTrainingbccDevice> list = tTrainingbccDeviceMapper.selectTTrainingbccDeviceList(param);
        String staffIds = "";
        for (TTrainingbccDevice t : list
        ) {
            staffIds = staffIds + "," + t.getStaffId();
        }
        tTrainingbcc.setStaffIds(staffIds);
        return AjaxResult.success(tTrainingbcc);
    }


    /**
     * 新增装置培训跟踪b
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:add')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTrainingbcc tTrainingbcc) {
        tTrainingbccService.insertTTrainingbcc(tTrainingbcc);
        //培训岗位人员
        if (tTrainingbcc.getPosition() != null) {
            TStaffmgr s = new TStaffmgr();
            s.setActualposts(tTrainingbcc.getPosition());
            s.setDeptId(103l);
            List<TStaffmgr> trainingStaff = tStaffmgrService.selectAllTStaffmgrList(s);
            try {
                //判断离职
                if (!org.apache.commons.lang.StringUtils.isEmpty(tTrainingbcc.getYears())) {
                    Iterator<TStaffmgr> iterator = trainingStaff.iterator();
                    while (iterator.hasNext()) {
                        TStaffmgr t = iterator.next();
                        if (t.getLeftDate() != null && t.getDelFlag() == 9) {
                            if (t.getLeftDate().getTime() - tTrainingbcc.getCourseStartdate().getTime() < 0l) {
                                logger.debug(t.getName() + "离职时间小于培训时间");
                                iterator.remove();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e.toString());
            }
            for (TStaffmgr staff : trainingStaff) {
                TTrainingbccDevice tTrainingDevice = new TTrainingbccDevice();
                tTrainingDevice.setStaffId(staff.getStaffid());
                tTrainingDevice.setRegularId(tTrainingbcc.getId());
                tTrainingDevice.setStartDate(tTrainingbcc.getCourseStartdate());
                tTrainingDevice.setSupplementary("0");
                tTrainingbccDeviceMapper.insertTTrainingbccDevice(tTrainingDevice);
            }
        }
        return toAjax(1);
    }

    /**
     * 修改装置培训跟踪b
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:edit')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTrainingbcc tTrainingbcc) {
        return toAjax(tTrainingbccService.updateTTrainingbcc(tTrainingbcc));
    }

    /**
     * 修改装置培训跟踪b
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:edit')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/updateStaffIds")
    public AjaxResult updateStaffIds(@RequestBody TTrainingbcc tTrainingbcc) {
        return toAjax(tTrainingbccService.updateStaffIds(tTrainingbcc));
    }


    /**
     * 删除装置培训跟踪b
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:remove')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        tTrainingbccDeviceMapper.deleteTTrainingbccDeviceByTrainingbcc(ids);
        return toAjax(tTrainingbccService.deleteTTrainingbccByIds(ids));
    }

    @Log(title = "附件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadFile/{id}")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @PathVariable Long id) throws IOException {
        if (!file.isEmpty()) {
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 获取年份
            int year = currentDate.getYear();
            // 获取月份
            int month = currentDate.getMonthValue();
            String dir = "/elearn/" + year;
            String url = FileUploadUtils.upload(RuoYiConfig.getFilePath(dir), file);
            TTrainingbcc entity = tTrainingbccService.selectTTrainingbccById(id);
            entity.setFileUrl(url);
            entity.setFileName(file.getOriginalFilename());
            tTrainingbccService.updateTTrainingbcc(entity);
            return AjaxResult.success(id);
        }
        return AjaxResult.error("上传失败，请联系管理员");
    }

    @PreAuthorize("@ss.hasPermi('pssr:subcontent:export')")
    @Log(title = "导出签名表", businessType = BusinessType.EXPORT)
    @GetMapping("/exportSign")
    public AjaxResult exportSign(TTrainingbcc tTrainingbcc) throws Exception {
        TTrainingbcc tTraining = tTrainingbccMapper.selectTTrainingbccById(tTrainingbcc.getId());
        String tempUrl = "";

        // 模板路径
        if (tTraining.getTrainingType().equals("20")) {
            tempUrl = "static/word/training/signMOCbcc.docx"; // 模板文件
        } else {
            tempUrl = "static/word/training/signbcc.docx"; // 模板文件
        }
        //渲染文本
        Map<String, Object> params = getWordData(tTraining);
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "tTrainingbcc";
        // 生成word的文件名称
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"));
        String fileName = time + tTraining.getId() + "_" + DateUtils.getDate() + ".docx";
        String wordPath = createWord(tempUrl, fileDir, fileName, params, "tTrainingbcc");
        return AjaxResult.success(officeConvertController.wordTransPdf(wordPath));
    }

    public Map<String, Object> getWordData(TTrainingbcc trainingbcc) {
        Map<String, Object> params = new HashMap<>();
        TableRenderData tableRenderData = new TableRenderData();

        TableStyle tableStyle = new TableStyle();
        tableStyle.setWidth("100%");
        tableStyle.setColWidths(new int[]{8, 10, 10, 12, 10, 8, 10, 10, 12, 10});
        tableRenderData.setTableStyle(tableStyle);

        // 创建表头行
        RowRenderData row1 = Rows.of("序号", "姓名", "部门", "签名", "日期", "序号", "姓名", "部门", "签名", "日期").center().textBold().rowExactHeight(1.1f).create();
        tableRenderData.addRow(row1);

        int plant = 0, ctm = 0, cta = 0, count = 1;
        PictureRenderData plantMgr = null;
        TTrainingbccDevice tTrainingbccDevice = new TTrainingbccDevice();
        tTrainingbccDevice.setRegularId(trainingbcc.getId());
        List<TTrainingbccDevice> list = tTrainingbccDeviceMapper.sortSelectTTrainingbccDeviceList(tTrainingbccDevice);
        for (int i = 0; i < list.size(); i++) {
            TTrainingbccDevice t1 = list.get(i);
            for (int j = i+1; j < list.size(); j++) {
                TTrainingbccDevice t2 = list.get(j);
                if (t1.getName().equals(t2.getName())) {
                    t1.setName(t1.getName() +"1");
                    t2.setName(t2.getName() + "2");
                }
            }
        }
        for (int i = 0; i < list.size(); i++) {
            //如果当前行为偶数，直接开始下一行
            if (i % 2 != 0) {
                continue;
            }
            TTrainingbccDevice device = list.get(i);
            TTrainingbccDevice device2 = null;
            if (i < list.size() - 1) {
                device2 = list.get(i + 1);
            }

            SysUser user1 = sysUserMapper.selectUserByStaffId(device.getStaffId());
            SysUser user2 = null;
            if (device2 != null) {
                user2 = sysUserMapper.selectUserByStaffId(device2.getStaffId());
            }
            RowRenderData row = null;
            String lineNum="";
            String lineNum2="";
            // 创建数据行
                 lineNum = String.valueOf(i + 1);
                 lineNum2 = String.valueOf(i + 2);

            if (device2!=null)
                row = Rows.of(lineNum, device.getName(), "CBP/C", "", DateUtils.dateTime(device.getStartDate()),
                        lineNum2, device2.getName(), "CBP/C", "", DateUtils.dateTime(device2.getStartDate())).verticalCenter().textFontSize(8).rowExactHeight(1.1f).create();
            else
                row = Rows.of(lineNum, device.getName(), "CBP/C", "", DateUtils.dateTime(device.getStartDate()),
                        "", "", "", "", "").verticalCenter().horizontalCenter().textFontSize(8).rowExactHeight(1.1f).create();
            if (device.getExamState() == 1) {
                if (user1 != null)
                    row.getCells().set(3, new CellRenderData().addParagraph(new ParagraphRenderData().addPicture(Pictures.ofLocal(FileUtils.fileName(user1.getSignUrl())).size(60, 20).create())));
            }
            if (device2!=null&&device2.getExamState() == 1) {
                if (user2 != null)
                    row.getCells().set(8, new CellRenderData().addParagraph(new ParagraphRenderData().addPicture(Pictures.ofLocal(FileUtils.fileName(user2.getSignUrl())).size(60, 20).create())));
            }
            tableRenderData.addRow(row);
        }

        // 准备表格数据和其他参数
        params.put("course", trainingbcc.getCourse());
        params.put("table1", tableRenderData);

        return params;

    }


    private String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap, String directory) 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);
        logger.info("模板{}!", templatePath);
        // 读取模板渲染参数
        InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath);

        XWPFTemplate template = XWPFTemplate.compile(is).render(paramMap);
        try {
            // 将模板参数写入路径
            template.writeToFile(filePath);
            template.close();
            is.close();
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }
        String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getFilePath("/" + directory), fileName);
        return pathFileName;
    }

}
