package com.ruoyi.project.production.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
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.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.production.domain.TFivesFile;
import com.ruoyi.project.production.domain.TFivesRegion;
import com.ruoyi.project.production.service.ITFivesFileService;
import com.ruoyi.project.production.service.ITFivesRegionService;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * 区域列台账Controller
 *
 * @author ruoyi
 * @date 2023-03-30
 */
@RestController
@RequestMapping("/production/region")
public class TFivesRegionController extends BaseController {
    @Autowired
    private ITFivesRegionService tFivesRegionService;
    @Autowired
    private ITFivesFileService tFivesFileService;
    @Autowired
    private ITStaffmgrService tStaffmgrService;

    /**
     * 查询区域列台账列表
     */
    @PreAuthorize("@ss.hasPermi('production:region:list')")
    @GetMapping("/list")
    public TableDataInfo list(TFivesRegion tFivesRegion) {
        startPage();
        List<TFivesRegion> list = tFivesRegionService.selectTFivesRegionList(tFivesRegion);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('production:region:list')")
    @GetMapping("/listAll")
    public AjaxResult listAll(TFivesRegion tFivesRegion) {
        return AjaxResult.success(tFivesRegionService.selectTFivesRegionList(tFivesRegion));
    }

    /**
     * 导出区域列台账列表
     */
    @PreAuthorize("@ss.hasPermi('production:region:export')")
    @Log(title = "区域列台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TFivesRegion tFivesRegion) {
        List<TFivesRegion> list = tFivesRegionService.selectTFivesRegionList(tFivesRegion);
        ExcelUtil<TFivesRegion> util = new ExcelUtil<TFivesRegion>(TFivesRegion.class);
        return util.exportExcel(list, "region");
    }

    /**
     * 获取区域列台账详细信息
     */
    @PreAuthorize("@ss.hasPermi('production:region:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tFivesRegionService.selectTFivesRegionById(id));
    }

    /**
     * 新增区域列台账
     */
    @PreAuthorize("@ss.hasPermi('production:region:add')")
    @Log(title = "区域列台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TFivesRegion tFivesRegion) {
        tFivesRegion.setCreatedate(new Date());
        tFivesRegion.setCreaterCode(getUserId().toString());
        return toAjax(tFivesRegionService.insertTFivesRegion(tFivesRegion));
    }

    /**
     * 修改区域列台账
     */
    @PreAuthorize("@ss.hasPermi('production:region:edit')")
    @Log(title = "区域列台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TFivesRegion tFivesRegion) {
        return toAjax(tFivesRegionService.updateTFivesRegion(tFivesRegion));
    }

    /**
     * 删除区域列台账
     */
    @PreAuthorize("@ss.hasPermi('production:region:remove')")
    @Log(title = "区域列台账", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tFivesRegionService.deleteTFivesRegionByIds(ids));
    }

    @Log(title = "区域列台账", businessType = BusinessType.EXPORT)
    @GetMapping("/generateExcel/{id}")
    public AjaxResult generateExcel(@PathVariable Long id) {
        try {
            String templateFilePath = "static/template/production/regionMod.xlsx";
            String filePath = RuoYiConfig.getProfile() + "/production/regionMod";
            File fileDir = new File(filePath);
            if (!fileDir.exists()) {
                logger.info("不存在目录：{}，开始创建。", fileDir);
                fileDir.mkdirs();
            }
            TFivesRegion tFivesRegion = tFivesRegionService.selectTFivesRegionById(id);
            InputStream fis = getClass().getClassLoader().getResourceAsStream(templateFilePath);
            XSSFWorkbook wb = new XSSFWorkbook(fis);
            XSSFSheet sheet = wb.getSheetAt(0);
            Map<String, Object> param = new HashMap<>();
            param.put("{personLiable}", tFivesRegion.getPersonLiable());
            param.put("{position}", tFivesRegion.getPosition());
            param.put("{deptName}", tFivesRegion.getDeptName());
            int flag;
            if (tFivesRegion.getPosition().contains("打印")) {
                flag = 1;
            } else if (tFivesRegion.getPosition().contains("餐厅") || tFivesRegion.getPosition().contains("休息室") || tFivesRegion.getPosition().contains("洗手间") || tFivesRegion.getPosition().contains("更衣室") || tFivesRegion.getPosition().contains("浴室") || tFivesRegion.getPosition().contains("厕")) {
                flag = 2;
            } else if (tFivesRegion.getPosition().contains("吸烟室")) {
                flag = 3;
            } else if (tFivesRegion.getPosition().contains("危废库房")) {
                flag = 4;
            } else if (tFivesRegion.getPosition().contains("库房")) {
                flag = 5;
            } else {
                flag = 6;
            }
            // 获取行数添加相关信息
            int rowNum = sheet.getLastRowNum();
            for (int i = 0; i < rowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                // 获取行里面的总列数
                int columnNum = 0;
                if (row != null) {
                    columnNum = row.getLastCellNum();
                }
                for (int j = 0; j < columnNum; j++) {
                    XSSFCell cell = sheet.getRow(i).getCell(j);
                    String cellValue = cell.getStringCellValue();
                    for (Map.Entry<String, Object> entry : param.entrySet()) {
                        String key = entry.getKey();
                        if (key.equals(cellValue)) {
                            String value = entry.getValue().toString();
                            XSSFCell newCell = sheet.getRow(i).getCell(j);
                            newCell.setCellValue(value);
                        }
                    }
                    if (i == 5 && j == 0) {
                        if (flag != 3 && flag != 5)
                            cell.setCellValue("1：无杂物及灰尘");
                        else {
                            cell.setCellValue("1：地面无杂物");
                        }
                    }
                    if (i == 6 && j == 0) {
                        if (flag != 6) {
                            cell.setCellValue("2：物品定置摆放");
                        } else {
                            cell.setCellValue("2：仅限必要列具物品");
                        }
                    }
                    if (i == 7 && j == 0) {
                        if (flag == 1) {
                            cell.setCellValue("3：标准化文档管理");
                        } else if (flag != 6) {
                            cell.setCellValue("3：公共设施及安全设施完好");
                        } else {
                            cell.setCellValue("3：办公室物品定置摆放");
                        }
                    }
                    if (i == 8 && j == 0) {
                        if (flag == 1) {
                            cell.setCellValue("4：公共设施及安全设施完好");
                        } else if (flag == 3) {
                            cell.setCellValue("4：门保持常开");
                        } else if (flag != 6) {
                            cell.setCellValue("4：门保持常闭");
                        } else {
                            cell.setCellValue("4：流程设置合理有效");
                        }
                    }
                    if (i == 9 && j == 0) {
                        if (flag == 1 || flag == 2) {
                            cell.setCellValue("5：保持空调系统运行正常");
                        } else if (flag == 4) {
                            cell.setCellValue("5：危废及保护标识清晰");
                        } else if (flag != 6) {
                            cell.setCellValue("5：消防实施完好");
                        } else {
                            cell.setCellValue("5：办公设施良好");
                        }
                    }
                    if (i == 10 && j == 0) {
                        if (flag == 1) {
                            cell.setCellValue("6：严格遵守公司信息保密规定");
                        } else if (flag != 6) {
                            cell.setCellValue("");
                        } else {
                            cell.setCellValue("6：标准化文档管理，遵守公司信息保密规定");
                        }
                    }
                    if (i == 11 && j == 0) {
                        if (flag == 1) {
                            cell.setCellValue("7：定期巡检");
                        } else if (flag != 6) {
                            cell.setCellValue("");
                        } else {
                            cell.setCellValue("7：无纸化与节俭办公");
                        }
                    }
                    if (i == 12 && j == 0) {
                        if (flag == 1) {
                            cell.setCellValue("");
                        } else if (flag != 6) {
                            cell.setCellValue("");
                        } else {
                            cell.setCellValue("8：热情工作文明礼仪");
                        }
                    }
                }
            }
            // 插入图片
            // 区域标准照片
            XSSFDrawing patriarch = sheet.createDrawingPatriarch();
            if (StringUtils.isNotEmpty(tFivesRegion.getFileId())) {
                List<String> urls = new ArrayList<>();
                for (String fileId : tFivesRegion.getFileId().split(",")) {
                    TFivesFile file = tFivesFileService.selectTFivesFileById(Long.valueOf(fileId));
                    urls.add(file.getUrl());
                }

                for (int i = 0; i < urls.size(); i++) {
                    try {
                        String url = urls.get(i);
                        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                        BufferedImage bufferImg = ImageIO.read(new File(RuoYiConfig.getProfile() + url.replaceFirst("/profile", "")));
                        ImageIO.write(bufferImg, "jpg", byteArrayOut);
                        int h = 0;
                        int l = 0;
                        int endh = 0;
                        int endl = 0;
                        if (urls.size() == 1) {
                            endl = 5;
                            endh = 10;
                        }
                        if (i == 0) {
                            if (urls.size() == 2) {
                                endl = 5;
                            }
                        } else if (i == 1) {
                            if (urls.size() == 2) {
                                h = 12;
                                endh = 10;
                            } else {
                                l = 5;
                            }
                            endl = 5;
                        } else if (i == 2) {
                            h = 12;
                            endh = 10;
                        } else if (i == 3) {
                            l = 5;
                            endl = 5;
                            h = 12;
                            endh = 10;
                        }
                        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 6 + l, 2 + h, 11 + endl, 14 + endh);
                        // 插入图片
                        patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                        byteArrayOut.close();
                    } catch (Exception e) {
                    }
                }
            }
            List<String> urls = new ArrayList<>();
            if (tFivesRegion.getInSys().equals("否")) {
                if (StringUtils.isNotEmpty(tFivesRegion.getPersonFile())) {
                    for (String fileId : tFivesRegion.getPersonFile().split(",")) {
                        TFivesFile file = tFivesFileService.selectTFivesFileById(Long.valueOf(fileId));
                        urls.add(file.getUrl());
                    }
                }
            } else {
                if (StringUtils.isNotEmpty(tFivesRegion.getStaffId())) {
                    for (String staffId : tFivesRegion.getStaffId().split(",")) {
                        TStaffmgr tStaffmgr = tStaffmgrService.selectTStaffmgrByStaffId(staffId);
                        urls.add(tStaffmgr.getPhoto());
                    }
                }
            }
            for (int i = 0; i < urls.size(); i++) {
                try {
                    String url = urls.get(i);
                    ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                    BufferedImage bufferImg = ImageIO.read(new File(RuoYiConfig.getProfile() + url.replaceFirst("/profile", "")));
                    ImageIO.write(bufferImg, "jpg", byteArrayOut);
                    int h = 0;
                    int l = 0;
                    int endh = 0;
                    int endl = 0;
                    if (urls.size() == 1) {
                        endl = 1;
                        endh = 2;
                    }
                    if (i == 1) {
                        l = 1;
                        endl = 1;
                    } else if (i == 2) {
                        h = 2;
                        endh = 2;
                    } else if (i == 3) {
                        l = 1;
                        endl = 1;
                        h = 2;
                        endh = 2;
                    }
                    XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 0 + l, 14 + h, 1 + endl, 16 + endh);
                    // 插入图片
                    patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                    byteArrayOut.close();
                } catch (Exception e) {
                    continue;
                }
            }
            String fileName = DateUtils.dateTimeNow() + "_" + tFivesRegion.getPersonLiable() + ".xlsx";
            wb.write(Files.newOutputStream(Paths.get(filePath + "/" + fileName)));
            fis.close();
            wb.close();
            String pathFileName = FileUploadUtils.getPathFileName(filePath, fileName);
            return AjaxResult.success(pathFileName);
        } catch (IOException e) {
            return AjaxResult.error("读取文件失败！");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
