package com.ruoyi.powerdistribution.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.powerdistribution.domain.*;
import com.ruoyi.powerdistribution.domain.dto.PdmWorkPlanDTO;
import com.ruoyi.powerdistribution.domain.vo.SupRiskTeam;
import com.ruoyi.powerdistribution.domain.vo.TaskRiskPlan;
import com.ruoyi.powerdistribution.domain.vo.ThreeLevelRiskJob;
import com.ruoyi.powerdistribution.service.*;
import com.ruoyi.powerdistribution.util.GenerateWordUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 周报导出
 */
@RestController
@RequestMapping("/power/weklyReport")
public class WeeklyReportController extends BaseController {

    @Value("${printReplenishmentPath}")
    private String printReplenishmentPath;

    @Autowired
    private IPdmReportIllegalWeekService pdmReportIllegalWeekService;

    @Autowired
    private IPdmReportPlanNextWeekService pdmReportPlanNextWeekService;
    @Autowired
    private IPdmWorkPlanService pdmWorkPlanService;
    @Autowired
    private IPdmReportPlanNextDayService pdmReportPlanNextDayService;

    @Autowired
    private IPdmReportPlanWeekService pdmReportPlanWeekService;
    @Autowired
    private IPdmReportAppointmentWeekService pdmReportAppointmentWeekService;



    @PostMapping("/export")
    @ApiOperation(value = "周报导出")
    public void export(HttpServletResponse response, String beingDate,String endDate) throws IOException, ParseException {
        PdmReportIllegalDay pdmReportIllegalDay = new PdmReportIllegalDay();
        pdmReportIllegalDay.setReportDate(beingDate);
        Map<String,Object> dataMap = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date cvrtFirstDate = sdf.parse(beingDate);
        Date cvrtEndDate = sdf.parse(endDate);
        //日期公共使用
        String month=new SimpleDateFormat("MM").format(cvrtFirstDate);
        dataMap.put("beginDay",month+"月"+new SimpleDateFormat("dd").format(cvrtFirstDate)+"日");//开始日
        dataMap.put("endDay",month+"月"+new SimpleDateFormat("dd").format(cvrtEndDate)+"日");//结束日
        //一.风险计划管控
        //1.本周计划执行情况
        dataMap.put("jobRecNum",0);//发布作业信息条数
        dataMap.put("weekPlanJobReNum",0);//来源于周计划的作业条数
        dataMap.put("cancelRecNum",0);//已取消
        dataMap.put("implRate",0);//执行率
        dataMap.put("lowImplUnit","");//较低的单位 ()
        dataMap.put("lowImplRate","");//较低的单位执行率
        dataMap.put("tmpPlanRecNum",0);//临时计划
        dataMap.put("repairRecNum",0);//其中抢修
        dataMap.put("operateRecNum",0);//操作条数
        dataMap.put("maintenanceNum",0);//运维检修
        dataMap.put("expanRelocationNum",0);//业扩
        dataMap.put("networkReformNum",0);//网改
        dataMap.put("tmpPlanRate",0);//临时计划率
        dataMap.put("cancelTmpPlanRecNum",0);//临时取消计划数
        dataMap.put("tmpPlanImplRate",0);//临时计划执行率
        PdmReportPlanWeek pdmReportPlan = new PdmReportPlanWeek();
        pdmReportPlan.setReportDate(beingDate);
        pdmReportPlan.setReportEndDate(endDate);
        List<PdmReportPlanWeek> planlist = pdmReportPlanWeekService.selectPdmReportPlanWeekList(pdmReportPlan);
        dataMap.put("planlist",planlist);//本周计划执行情况

        //2.下周计划安排情况
        String nextMonday=DateUtils.getNextMonday(beingDate,"yyyyMMdd");
        String nextSunday=DateUtils.getNextSunday(beingDate,"yyyyMMdd");
        Date cvrtNextMonday = sdf.parse(nextMonday);
        Date cvrtNextSunday = sdf.parse(nextSunday);
        month=new SimpleDateFormat("MM").format(cvrtNextMonday);
        dataMap.put("nextWeekBeginDay",month+"月"+new SimpleDateFormat("dd").format(cvrtNextMonday)+"日");//下周开始日
        dataMap.put("nextWeekEndDay",month+"月"+new SimpleDateFormat("dd").format(cvrtNextSunday)+"日");//下周结束日
        dataMap.put("nextWeekJobRecNum",0);//配网专业计划总数
        dataMap.put("nextWeekSwitchingNum",0);//倒闸操作
        dataMap.put("distribuNetworkEngineNum",0);//配网工程
        dataMap.put("nextWeekExpanRelocationNum",0);//业扩杆迁
        dataMap.put("nextWeekMaintenanceNum",0);//运维检修
        dataMap.put("threeLevelRiskNum",0);//三级风险作业
        dataMap.put("fourLevelRiskNum",0);//四级风险作业
        dataMap.put("fiveLevelRiskNum",0);//五级风险作业
        dataMap.put("liveWorkingNum",0);//带电作业
        dataMap.put("liveDisconnectLeadNum",0);//带电断接引
        dataMap.put("assemDeviceNum",0);//带电消缺、装拆设备
        //三级风险作业内容:
        List<ThreeLevelRiskJob> threeLevelRiskJobs=new ArrayList<ThreeLevelRiskJob>() ;
        StringBuilder builder=new StringBuilder();
        for(int i=0;i<threeLevelRiskJobs.size();i++){
            ThreeLevelRiskJob threeLevelRiskJob=threeLevelRiskJobs.get(i);
            builder.append(threeLevelRiskJob.getCompName()).append(": ").append(threeLevelRiskJob.getJobDate()).append(",").append(threeLevelRiskJob.getJobContent()).append("。").append("\r\n");
        }
        dataMap.put(" threeLevelRiskJobs",StringUtils.isEmpty(builder.toString())?"无":builder.toString());//三级风险作业内容:
        //三级及以上作业风险计划
        PdmWorkPlanDTO workPlan = new PdmWorkPlanDTO();
        workPlan.setStartDate(nextMonday);
        workPlan.setEndDate(nextSunday);
        workPlan.setLevel3Flag("1");//三级及以上作业
        List<PdmWorkPlan> workList = pdmWorkPlanService.selectPdmWorkPlanList(workPlan);
        dataMap.put("threeLevelRiskWorkList",workList);//三级及以上作业列表明细
        dataMap.put("fousMaintenanceNum",0);//重点关注检修面个数
        String fousMaintenanceInfo="";//重点关注检修面内容
        dataMap.put("fousMaintenanceInfo", StringUtils.isEmpty(fousMaintenanceInfo)?"无":fousMaintenanceInfo);//重点关注检修面内容
        //下周计划安排情况
        PdmReportPlanNextWeek next = new PdmReportPlanNextWeek();
        next.setReportDate(nextMonday);
        next.setReportEndDate(nextSunday);
        List<PdmReportPlanNextWeek> nextList = pdmReportPlanNextWeekService.selectPdmReportPlanNextWeekList(next);
        dataMap.put("nextWeekWorkList",nextList);//下周计划安排情况列表

        //二、专业反违章履职情况
        //1.本周违章查处情况
        dataMap.put("investPunishRecAllNum",0);//配网专业共计查处违章
        dataMap.put("provinceInvestPunishRecNum",0);//被省公司查处违章
        dataMap.put("cityInvestPunishRecNum",0);//被市公司查处违章
        dataMap.put("cityInvestSeriousRecNum",0);//严重违章
        dataMap.put("cityInvestGeneralRecNum",0);//一般违章
        dataMap.put("countyInvestPunishRecNum",0);//县区公司自查处违章
        dataMap.put("countyInvestSeriousRecNum",0);//严重违章
        dataMap.put("countyInvestGeneralRecNum",0);//一般违章

        //本周违章查处情况列表
        PdmReportIllegalWeek pdmReportIllegal = new PdmReportIllegalWeek();
        pdmReportIllegal.setReportDate(beingDate);
        pdmReportIllegal.setReportEndDate(endDate);
        List<PdmReportIllegalWeek> illegalList = pdmReportIllegalWeekService.selectPdmReportIllegalWeekList(pdmReportIllegal);
        dataMap.put("illegalList",illegalList);//违章列表明细
        String typicalIllegal="";//其中典型违章通报如下
        dataMap.put("typicalIllegal",StringUtils.isEmpty(typicalIllegal)?"无":typicalIllegal);//其中典型违章通报如下


        //2.本周人员到岗到位履职情况
        dataMap.put("supervTimes",0);//督察共计次数
        dataMap.put("leaderSupervTimes",0);//领导督察共计次数
        dataMap.put("manageSupervTimes",0);//管理人员督察次数
        dataMap.put("problemNum",0);//督察发现问题
        dataMap.put("cityFindProblemNum",0);//市公司发现问题处数
        dataMap.put("derelictionDutyNum",0);//履职不到位(应查未查)
        //本周到岗到位履职情况
        PdmReportAppointmentWeek pdmReportAppointment = new PdmReportAppointmentWeek();
        pdmReportAppointment.setReportDate(beingDate);
        pdmReportAppointment.setReportEndDate(endDate);
        List<PdmReportAppointmentWeek> appointmentlist = pdmReportAppointmentWeekService.selectPdmReportAppointmentWeekList(pdmReportAppointment);
        dataMap.put("appointmentlist",appointmentlist);//本周到岗到位履职情况

        File descFile=null;
        try {
            String fileN = UUID.randomUUID().toString();
            File fileFold = new File(printReplenishmentPath+"/temp_print/");
            if(!fileFold.exists()){
                fileFold.mkdirs();
            }
            String fileDocPath = fileFold+"/"+fileN+".doc";
            GenerateWordUtil.generateWord(dataMap, "生产周例会配电汇报内容.ftl", new OutputStreamWriter(new FileOutputStream(new File(fileDocPath)), "utf-8"));
            descFile = new File(fileDocPath);
            String type = new MimetypesFileTypeMap().getContentType(descFile);
            response.setHeader("Content-type",type);
            String filename = new String(descFile.getName().getBytes("utf-8"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType("application/octet-stream");
            response.reset();
            OutputStream outputStream1 = response.getOutputStream();
            BufferedInputStream bis = null;
            bis = new BufferedInputStream(new FileInputStream(descFile));
            byte[] buff = new byte[bis.available()];
            bis.read(buff);
            outputStream1.write(buff);
            outputStream1.close();
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//            if(descFile!=null)
//                descFile.deleteOnExit();
        }
        //下载之后删除
        try {
            if(descFile.exists()){
                descFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
  }
}