package com.ruoyi.project.patrol.fire.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
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.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.patrol.fire.domain.TFireAidkit;
import com.ruoyi.project.patrol.fire.service.ITFireAidkitService;
import com.ruoyi.project.patrol.patrol.domain.TPatrolPlan;
import com.ruoyi.project.patrol.patrol.service.ITPatrolPlanService;
import com.ruoyi.project.pssr.domain.TPssrAirtight;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 急救箱检查记录Controller
 *
 * @author ssy
 * @date 2024-10-30
 */
@RestController
@RequestMapping("/fire/aidkit")
public class TFireAidkitController extends BaseController {
    @Autowired
    private ITFireAidkitService tFireAidkitService;

    @Autowired
    private ITPatrolPlanService tPatrolPlanService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询急救箱检查记录列表
     */
    @PreAuthorize("@ss.hasPermi('fire:aidkit:list')")
    @GetMapping("/list")
    public TableDataInfo list(TFireAidkit tFireAidkit) {
        startPage();
        List<TFireAidkit> list = tFireAidkitService.selectTFireAidkitList(tFireAidkit);
        return getDataTable(list);
    }

    /**
     * 导出急救箱检查记录列表
     */
    
    @Log(title = "急救箱检查记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TFireAidkit tFireAidkit) {
        List<TFireAidkit> list = tFireAidkitService.selectTFireAidkitList(tFireAidkit);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TFireAidkit> list) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = "static/word/patrol/aidkit.xlsx"; // 模板文件
            InputStream is = null;
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
            XSSFWorkbook wb = null;
            wb = new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0);

            //填充数据

            Row originalRow = sheet.getRow(3);
            Cell originalcell = originalRow.getCell(0);
            // 获取单元格样式
            CellStyle originalStyle = originalcell.getCellStyle();

            String confirmed = "";
            Date confirmedDate = null;
            for (TFireAidkit t : list) {
                Row row = sheet.getRow(3);
                row.getCell(2).setCellValue(t.getAidkitAppearance());
                row.getCell(3).setCellValue(t.getRequireCheck());
                row.getCell(4).setCellValue(t.getSealIntegrity());
                TPatrolPlan tPatrolPlan = tPatrolPlanService.selectTPatrolPlanById(t.getPlanId());
                if (Objects.nonNull(tPatrolPlan) && Objects.nonNull(tPatrolPlan.getConfirmed())) {
                    SysUser sysUser = sysUserService.selectUserById(Long.valueOf(tPatrolPlan.getConfirmed()));
                    if (sysUser != null) {
                        confirmed = sysUser.getSignUrl();
                        confirmedDate = tPatrolPlan.getConfirmDate();
                    }
                }
            }
            if (StringUtils.isNotEmpty(confirmed))
                ExcelUtils.insertPicture(wb, sheet, confirmed, 4, 3, 1, 1);
            if (confirmedDate!=null){
                sheet.getRow(5).getCell(2).setCellValue(DateUtils.dateTime(confirmedDate));
            }
            filename =  filename = "PSSR_13_消气防设施_急救箱检查记录.xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }

    /**
     * 获取急救箱检查记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('fire:aidkit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tFireAidkitService.selectTFireAidkitById(id));
    }

    /**
     * 新增急救箱检查记录
     */
    @PreAuthorize("@ss.hasPermi('fire:aidkit:add')")
    @Log(title = "急救箱检查记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TFireAidkit tFireAidkit) {
        return toAjax(tFireAidkitService.insertTFireAidkit(tFireAidkit));
    }

    /**
     * 修改急救箱检查记录
     */
    @PreAuthorize("@ss.hasPermi('fire:aidkit:edit')")
    @Log(title = "急救箱检查记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TFireAidkit tFireAidkit) {
        TFireAidkit item = tFireAidkitService.selectTFireAidkitById(tFireAidkit.getId());
        TPatrolPlan tPatrolPlan = tPatrolPlanService.selectTPatrolPlanById(tFireAidkit.getPlanId());
        if (tPatrolPlan.getStatus() == 1) {
            return AjaxResult.error("当前选择的计划已确认！");
        }
        if (!"1".equals(item.getCheckStatus())) {
            tPatrolPlan.setUncheckedNum(tPatrolPlan.getUncheckedNum() - 1);
            tPatrolPlan.setCheckedNum(tPatrolPlan.getCheckedNum() + 1);
            tPatrolPlanService.updateTPatrolPlan(tPatrolPlan);
        }
        tFireAidkit.setUpdatedate(new Date());
        tFireAidkit.setUpdaterCode(getUserId().toString());
        tFireAidkit.setCheckStatus("1");
        tFireAidkit.setCheckDate(new Date());
        tFireAidkit.setIssuesStatus("0");
        return toAjax(tFireAidkitService.updateTFireAidkit(tFireAidkit));
    }

    /**
     * 删除急救箱检查记录
     */
    @PreAuthorize("@ss.hasPermi('fire:aidkit:remove')")
    @Log(title = "急救箱检查记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tFireAidkitService.deleteTFireAidkitByIds(ids));
    }
}
