package com.ruoyi.powerdistribution.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.DateUtils;
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.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/dailyReport")
public class DailyReportController extends BaseController {

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

    @Autowired
    private IPdmReportIllegalDayService pdmReportIllegalDayService;

    @Autowired
    private IPdmReportPlanDayService pdmReportPlanDayService;
    @Autowired
    private IPdmReportAppointmentDayService pdmReportAppointmentDayService;
    @Autowired
    private IPdmReportPlanNextDayService pdmReportPlanNextDayService;
    @Autowired
    private IPdmWorkPlanService pdmWorkPlanService;

    @PostMapping("/export")
    @ApiOperation(value = "日报导出")
    public void dayExport(HttpServletResponse response, String beingDate,String endDate) throws IOException, ParseException {
        PdmReportIllegalDay pdmReportIllegalDay = new PdmReportIllegalDay();
        pdmReportIllegalDay.setStartDate(beingDate);
        pdmReportIllegalDay.setEndDate(endDate);
        Map<String,Object> dataMap = new HashMap();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date cvrtFirstDate = sdf.parse(beingDate);
        Date cvrtEndDate = sdf.parse(endDate);
        //日期公共使用
        dataMap.put("rptDate", DateUtils.parseDateToStr("yyyy年MM月dd日",cvrtEndDate));//日报生成日期
        dataMap.put("month",new SimpleDateFormat("MM").format(cvrtFirstDate));//月
        dataMap.put("beginDay",new SimpleDateFormat("dd").format(cvrtFirstDate));//开始日
        dataMap.put("endDay",new SimpleDateFormat("dd").format(cvrtEndDate));//结束日
        //1.违章查处情况
        long provinceInvestPunishRecNum=0;
        long provinceInvestSeriousRecNum=0;
        long cityInvestPunishRecNum=0;
        long cityInvestSeriousRecNum=0;
        long countySelfInvestPunishRecNum=0;
        long countySelfInvestSeriousRecNum=0;
        long guaraSelfIssuesRecNum=0;
        List<PdmReportIllegalDay> illegalList = pdmReportIllegalDayService.selectPdmReportIllegalDayList(pdmReportIllegalDay); File descFile=null;
        if(illegalList!=null && illegalList.size()>1){
            pdmReportIllegalDay=illegalList.get(illegalList.size()-1);
            provinceInvestPunishRecNum=pdmReportIllegalDay.getProvinceNum1()+pdmReportIllegalDay.getProvinceNum2();
            provinceInvestSeriousRecNum=pdmReportIllegalDay.getProvinceNum1();
            cityInvestPunishRecNum=pdmReportIllegalDay.getCityNum1()+pdmReportIllegalDay.getCityNum2();
            cityInvestSeriousRecNum=pdmReportIllegalDay.getCityNum1();
            countySelfInvestPunishRecNum=pdmReportIllegalDay.getCountyNum1()+pdmReportIllegalDay.getCountyNum2();
            countySelfInvestSeriousRecNum=pdmReportIllegalDay.getCountyNum1();
            guaraSelfIssuesRecNum=pdmReportIllegalDay.getCheckNum();
        }

        dataMap.put("illegalList",illegalList);//列表明细
        dataMap.put("provinceInvestPunishRecNum",provinceInvestPunishRecNum);//被省公司查处违章
        dataMap.put("provinceInvestSeriousRecNum",provinceInvestSeriousRecNum);//严重违章
        dataMap.put("cityInvestPunishRecNum",cityInvestPunishRecNum);//被市公司查处违章
        dataMap.put("cityInvestSeriousRecNum",cityInvestSeriousRecNum);//严重违章
        dataMap.put("countySelfInvestPunishRecNum",countySelfInvestPunishRecNum);//县区公司自查处违章
        dataMap.put("countySelfInvestSeriousRecNum",countySelfInvestSeriousRecNum);//严重违章
        dataMap.put("guaraSelfIssuesRecNum",guaraSelfIssuesRecNum);//保障体系自查问题
        dataMap.put("guaraCityIssuesRecNum",0);//其中市公司查处问题

        //(二）作业计划执行情况
        long jobRecNum=0;
        long exceRecNum=0;
        long cancelRecNum=0;
        String implementationRate="0%";
        long tmpPlanRecNum=0;
        String tmpPlanRate="0%";
        long temporaryCancelSum=0;
        PdmReportPlanDay pdmReportPlanDay = new PdmReportPlanDay();
        pdmReportPlanDay.setReportDate(beingDate);
        List<PdmReportPlanDay> planlist = pdmReportPlanDayService.selectPdmReportPlanDayList(pdmReportPlanDay);
        if(planlist!=null && planlist.size()>1){
            pdmReportPlanDay=planlist.get(planlist.size()-1);
            jobRecNum=pdmReportPlanDay.getWeekSum();
            exceRecNum=pdmReportPlanDay.getWeekSum()-pdmReportPlanDay.getWeekCancelSum();
            cancelRecNum=pdmReportPlanDay.getWeekCancelSum();
            implementationRate=pdmReportPlanDay.getWeekRatio();
            tmpPlanRecNum=pdmReportPlanDay.getTemporarySum();
            temporaryCancelSum=pdmReportPlanDay.getTemporaryCancelSum();
            tmpPlanRate=pdmReportPlanDay.getTemporaryPlanRatio();
        }
        dataMap.put("jobRecNum",jobRecNum);//周计划发布作业信息条数
        dataMap.put("exceRecNum",exceRecNum);//已执行
        dataMap.put("cancelRecNum",cancelRecNum);//已取消
        dataMap.put("implementationRate",implementationRate);//执行率
        dataMap.put("tmpPlanRecNum",tmpPlanRecNum);//临时计划
        dataMap.put("cancelTmpPlanRecNum",temporaryCancelSum);//取消计划数
        dataMap.put("tmpPlanRate",tmpPlanRate);//临时计划率
        dataMap.put("repairRecNum",0);//已执行临时计划包含抢修
        dataMap.put("operateRecNum",0);//操作条数
        dataMap.put("planlist",planlist);//操作条数

        //（三）人员到岗到位履职情况
        long supervTimes=0;
        long leaderSupervTimes=0;
        long manageSupervTimes=0;
        long nonfulfilmentNum=0;
        long derelictionDutyNum=0;
        PdmReportAppointmentDay pdmReportAppointmentDay = new PdmReportAppointmentDay();
        pdmReportAppointmentDay.setReportDate(beingDate);
        List<PdmReportAppointmentDay> appointmentlist = pdmReportAppointmentDayService.selectPdmReportAppointmentDayList(pdmReportAppointmentDay);
        if(appointmentlist!=null && appointmentlist.size()>1){
            pdmReportAppointmentDay=appointmentlist.get(appointmentlist.size()-1);
            supervTimes=pdmReportAppointmentDay.getBossSum()+pdmReportAppointmentDay.getManageSum();
            leaderSupervTimes=pdmReportAppointmentDay.getBossSum();
            manageSupervTimes=pdmReportAppointmentDay.getManageSum();
            nonfulfilmentNum=pdmReportAppointmentDay.getAbsentSum();
            derelictionDutyNum= pdmReportAppointmentDay.getAbsentBadSum();
        }
        dataMap.put("supervTimes",supervTimes);//督察共计次数
        dataMap.put("leaderSupervTimes",leaderSupervTimes);//领导督察共计次数
        dataMap.put("manageSupervTimes",manageSupervTimes);//管理人员督察次数
        dataMap.put("nonfulfilmentNum",nonfulfilmentNum);//未履职（应查未查）现场
        dataMap.put("derelictionDutyNum",derelictionDutyNum);//履职不到位
        dataMap.put("appointmentlist",appointmentlist);//操作条数

        //二、明日配网安全工作安排
        long distNetworkProfesRecNum=0;
        long switchOperatNum=0;
        long distNetworkProjectNum=0;
        long expanRelocationNum=0;
        long maintenanceNum=0;
        long other=0;
        long tempPlanNum=0;
        long liveWorkingNum=0;
        String threeRiskNum="0";
        String fourRiskNum="0";
        String fiveRiskNum="0";
        PdmReportPlanNextDay nextDay = new PdmReportPlanNextDay();
        nextDay.setReportDate(DateUtils.getNextDateStr(beingDate,DateUtils.YYYYMMDD,1));
        List<PdmReportPlanNextDay> nextDayList = pdmReportPlanNextDayService.selectPdmReportPlanNextDayList(nextDay);
        if(nextDayList!=null&& nextDayList.size()>1){
            nextDay=nextDayList.get(nextDayList.size()-1);
            distNetworkProfesRecNum=nextDay.getWorkTotal();
            switchOperatNum=nextDay.getWorkType1Sum();
            distNetworkProjectNum=nextDay.getWorkType2Sum();
            expanRelocationNum=nextDay.getWorkType3Sum();
            maintenanceNum=nextDay.getWorkType4Sum();
            other=nextDay.getWorkType5Sum();
            tempPlanNum=nextDay.getTemporaryPlanSum();
            liveWorkingNum=nextDay.getElePlanSum();
            threeRiskNum=nextDay.getPlanLeve3();
            fourRiskNum=nextDay.getPlanLeve4();
            fiveRiskNum=nextDay.getPlanLeve5();
        }
        dataMap.put("distNetworkProfesRecNum",distNetworkProfesRecNum);//作业信息总共条数
        dataMap.put("switchOperatNum",switchOperatNum);//倒闸操作操作项
        dataMap.put("distNetworkProjectNum",distNetworkProjectNum);//配网工程项
        dataMap.put("expanRelocationNum",expanRelocationNum);//业扩杆迁
        dataMap.put("maintenanceNum",maintenanceNum);//运维检修
        dataMap.put("other",other);//其他
        dataMap.put("tempPlanNum",tempPlanNum);//临时计划共计
        dataMap.put("operateNum",0);//操作项
        dataMap.put("kv10Num",0);//10千伏作业
        dataMap.put("zeroPointFourKvNum",0);//0.4千伏作业
        dataMap.put("liveWorkingNum",liveWorkingNum);//带电作业
        dataMap.put("liveDisconnectLeadNum",0);//带电断接引
        dataMap.put("assemDeviceNum",0);//带电消缺、装拆设备
        dataMap.put("threeRiskNum",threeRiskNum);//三级风险作业
        dataMap.put("fourRiskNum",fourRiskNum);//四级风险作业
        dataMap.put("fiveRiskNum",fiveRiskNum);//五级风险作业
        dataMap.put("liftingOperationNum",0);//起重作业
        dataMap.put("verticalPoleNum",0);//立杆
        dataMap.put("chgeDeviceNum",0);//更换配变、综配箱等设备
        dataMap.put("keyAssignments",0);//重点作业面
        dataMap.put("nextDayList",nextDayList);//
        //（二）“七分准备”及承载力审查情况
        List<String> morrowExistSupRiskCompList=new ArrayList<>(); //存放次日存在超管理承载力风险的单位数据
        dataMap.put("morrowExistSupRiskComp",morrowExistSupRiskCompList==null||morrowExistSupRiskCompList.size()==0?"无":String.join(",",morrowExistSupRiskCompList));//次日存在超管理承载力风险的单位
        List<SupRiskTeam> supRiskTeamList=new ArrayList<>(); //存放次日存在超作业承载力风险的班组
        StringBuilder builder=new StringBuilder();
        for(int i=0;i<supRiskTeamList.size();i++){
            SupRiskTeam supRiskTeam=supRiskTeamList.get(i);
            builder.append((i+1)).append(".").append(supRiskTeam.getTeamName()).append(":").append(String.join(",",supRiskTeam.getHandlingMatters())).append("\r\n");
        }
        dataMap.put("supRiskTeam",supRiskTeamList==null||supRiskTeamList.size()==0?"无":builder.toString());//次日存在超作业承载力风险的班组
        //（三）人员到岗到位履职安排
        SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        dataMap.put("tomorrow",formatter.format(format.parse(DateUtils.getNextDateStr(endDate,"yyyyMMdd",1))));//获取明天的日期
        dataMap.put("cityThreeRiskPlanNum",threeRiskNum);//全市三级作业风险计划

        PdmWorkPlanDTO workPlan = new PdmWorkPlanDTO();
        workPlan.setStartDate(beingDate);
        workPlan.setEndDate(endDate);
        workPlan.setLevel3Flag("1");//三级及以上作业
        List<PdmWorkPlan> workList = pdmWorkPlanService.selectPdmWorkPlanList(workPlan);
        StringBuilder riskPlanBuilder=new StringBuilder();
        for(int i=0;i<workList.size();i++){
            PdmWorkPlan taskRiskPlan=workList.get(i);
            riskPlanBuilder.append((i+1)).append(".").append(taskRiskPlan.getSubmitOrgNm()).append("：").append(taskRiskPlan.getOpContent()).append("。")
                    .append("把关领导：").append(taskRiskPlan.getWorkPrincipNm()).append("/").append(taskRiskPlan.getWorkPrincipContactMode()).append("\r\n").append("&nbsp;&nbsp;&nbsp;");
        }
        dataMap.put("cityThreeRiskPlan",workList==null||workList.size()==0?"":riskPlanBuilder.toString().replaceAll("\r\n", "<w:br/>").replaceAll("&nbsp;","<w:tab/>"));//全市三级作业风险计划
        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();
        }
  }
}
