package com.ruoyi.project.sems.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.document.PDFTemplateUtil;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.sems.domain.TReportPatrol;
import com.ruoyi.project.sems.service.ITReportPatrolService;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.sems.domain.TReportMonth;
import com.ruoyi.project.sems.service.ITReportMonthService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 月度检查Controller
 *
 * @author ruoyi
 * @date 2021-08-31
 */
@RestController
@RequestMapping("/sems/month")
public class TReportMonthController extends BaseController
{
    @Autowired
    private ITReportMonthService tReportMonthService;

    @Autowired
    private ITReportPatrolService tReportPatrolService;

    @Autowired
    private HistoryService historyService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询月度检查列表
     */
    @PreAuthorize("@ss.hasPermi('sems:month:list')")
    @GetMapping("/list")
    public TableDataInfo list(TReportMonth tReportMonth)
    {
        startPage();
        List<TReportMonth> list = tReportMonthService.selectTReportMonthList(tReportMonth);
        return getDataTable(list);
    }

    /**
     * 导出月度检查列表
     */
    @PreAuthorize("@ss.hasPermi('sems:month:export')")
    @Log(title = "月度检查", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TReportMonth tReportMonth)
    {
        List<TReportMonth> list = tReportMonthService.selectTReportMonthList(tReportMonth);
        ExcelUtil<TReportMonth> util = new ExcelUtil<TReportMonth>(TReportMonth.class);
        return util.exportExcel(list, "month");
    }

    /**
     * 获取月度检查详细信息
     */
    @PreAuthorize("@ss.hasPermi('sems:month:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tReportMonthService.selectTReportMonthById(id));
    }

    /**
     * 新增月度检查
     */
    @PreAuthorize("@ss.hasPermi('sems:month:add')")
    @Log(title = "月度检查", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TReportMonth tReportMonth)
    {
        return toAjax(tReportMonthService.insertTReportMonth(tReportMonth));
    }

    /**
     * 修改月度检查
     */
    @PreAuthorize("@ss.hasPermi('sems:month:edit')")
    @Log(title = "月度检查", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TReportMonth tReportMonth)
    {
        return toAjax(tReportMonthService.updateTReportMonth(tReportMonth));
    }

    /**
     * 删除月度检查
     */
    @PreAuthorize("@ss.hasPermi('sems:month:remove')")
    @Log(title = "月度检查", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tReportMonthService.deleteTReportMonthByIds(ids));
    }

    @RequestMapping("/exportPDF")
    public String exportPDF(@RequestParam String approveId, String id, HttpServletRequest request, HttpServletResponse response) {
        OutputStream out= null;
        try {
            out = response.getOutputStream();
            //获取信息，就是上面的结构
            HashMap<String, Object> map = new HashMap<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            TReportMonth reportMonth = tReportMonthService.selectTReportMonthById(Long.parseLong(id));
            map.put("month", reportMonth);
            String[] buildDate = sdf.format(reportMonth.getCheckMonth()).split("-");
            map.put("checkDateYear", buildDate[0]);
            map.put("checkDateMonth", buildDate[1]);
            List<TReportPatrol> reportPatrols = tReportPatrolService.selectTReportPatrolByMonthId(Long.parseLong(id));
            map.put("reportPatrols", reportPatrols);
            HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();
            List<HistoricTaskInstance> htiLists = htiq.processInstanceId(approveId).finished().orderByHistoricTaskInstanceEndTime().asc().list();
            logger.info("历史任务：" + JSON.toJSONString(htiLists));
            if( htiLists != null && htiLists.size() > 0 ){
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //获取用户名称
                map.put("jxwxSign",sysUserService.selectUserById(Long.parseLong(htiLists.get(0).getAssignee())).getNickName());
                map.put("jxwxEndTime",sdf2.format(htiLists.get(0).getEndTime()));
                map.put("dywxSign",sysUserService.selectUserById(Long.parseLong(htiLists.get(1).getAssignee())).getNickName());
                map.put("dywxEndTime",sdf2.format(htiLists.get(1).getEndTime()));
                map.put("gybmSign",sysUserService.selectUserById(Long.parseLong(htiLists.get(2).getAssignee())).getNickName());
                map.put("gybmEndTime",sdf2.format(htiLists.get(2).getEndTime()));
            }
            PDFTemplateUtil.exportPdf("monthFMaker.ftl", "承压类特种设备月度检查记录.pdf","file:/"+ RuoYiConfig.getProfile(), map, response);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(out!=null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }
}
