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.bean.BeanUtils;
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.*;
import java.util.stream.Collectors;

/**
 * 周报导出
 */
@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.本周计划执行情况
        PdmReportPlanWeek pdmReportPlan = new PdmReportPlanWeek();
        pdmReportPlan.setReportDate(beingDate);
        pdmReportPlan.setReportEndDate(endDate);
        List<PdmReportPlanWeek> planlist = pdmReportPlanWeekService.selectPdmReportPlanWeekList(pdmReportPlan);
        dataMap.put("planlist",planlist);//本周计划执行情况
        long jobRecNum=0;
        long weekPlanJobReNum=0;
        long cancelRecNum=0;
        String implRate="";
        long tmpPlanRecNum=0;
        String tmpPlanRate="";
        long cancelTmpPlanRecNum=0;
        String tmpPlanImplRate="";
        String lowImplUnit="";
        String lowImplRate="";

       if(planlist!=null && planlist.size()>1){
            pdmReportPlan=planlist.get(planlist.size()-1);
            jobRecNum=pdmReportPlan.getTotal();
            weekPlanJobReNum=pdmReportPlan.getWeekSum();
            cancelRecNum=pdmReportPlan.getWeekCancelSum();
            implRate=pdmReportPlan.getWeekRatio();
            tmpPlanRecNum=pdmReportPlan.getTemporarySum();
            tmpPlanRate=pdmReportPlan.getTemporaryPlanRatio();
            cancelTmpPlanRecNum=pdmReportPlan.getTemporaryCancelSum();
            tmpPlanImplRate=pdmReportPlan.getTemporaryRatio();
           List<PdmReportPlanWeek> planlist2=new ArrayList<>();
           planlist.forEach(plan->{
               if(!plan.getCompany().equals("总计")){
                   PdmReportPlanWeek planWeek=new PdmReportPlanWeek();
                   BeanUtils.copyBeanProp(planWeek,plan);
                   planlist2.add(planWeek);
               }
           });
           Collections.sort(planlist2, new Comparator<PdmReportPlanWeek>(){
               public int compare(PdmReportPlanWeek o1, PdmReportPlanWeek o2) {
                   //按照周计划执行率行升序排列
                   if((o1.getWeekSum()-o1.getWeekCancelSum())/o1.getWeekSum() > (o2.getWeekSum()-o2.getWeekCancelSum())/o2.getWeekSum()){
                       return -1;
                   }
                   if((o1.getWeekSum()-o1.getWeekCancelSum())/o1.getWeekSum() < (o2.getWeekSum()-o2.getWeekCancelSum())/o2.getWeekSum()){
                       return 1;
                   }
                   return 0;
               }
           });
           PdmReportPlanWeek lowPdmReportPlan=planlist2.get(planlist2.size()-1);
           lowImplUnit=lowPdmReportPlan.getCompany();
           lowImplRate=lowPdmReportPlan.getWeekRatio();
       }
        dataMap.put("jobRecNum",jobRecNum);//发布作业信息条数
        dataMap.put("weekPlanJobReNum",weekPlanJobReNum);//来源于周计划的作业条数
        dataMap.put("cancelRecNum",cancelRecNum);//已取消
        dataMap.put("implRate",implRate);//执行率
        dataMap.put("lowImplUnit",lowImplUnit);//较低的单位 ()
        dataMap.put("lowImplRate",lowImplRate);//较低的单位执行率
        dataMap.put("tmpPlanRecNum",tmpPlanRecNum);//临时计划
        dataMap.put("repairRecNum",0);//其中抢修
        dataMap.put("operateRecNum",0);//操作条数
        dataMap.put("maintenanceNum",0);//运维检修
        dataMap.put("expanRelocationNum",0);//业扩
        dataMap.put("networkReformNum",0);//网改
        dataMap.put("tmpPlanRate",tmpPlanRate);//临时计划率
        dataMap.put("cancelTmpPlanRecNum",cancelTmpPlanRecNum);//临时取消计划数
        dataMap.put("tmpPlanImplRate",tmpPlanImplRate);//临时计划执行率


        //2.下周计划安排情况
        String nextMonday=DateUtils.getNextMonday(beingDate,"yyyyMMdd");
        String nextSunday=DateUtils.getNextSunday(endDate,"yyyyMMdd");
        Date cvrtNextMonday = sdf.parse(nextMonday);
        Date cvrtNextSunday = sdf.parse(nextSunday);

        long nextWeekJobRecNum=0;
        long nextWeekSwitchingNum=0;
        long distribuNetworkEngineNum=0;
        long nextWeekExpanRelocationNum=0;
        long nextWeekMaintenanceNum=0;
        String threeLevelRiskNum="0";
        String fourLevelRiskNum="0";
        String fiveLevelRiskNum="0";
        long liveWorkingNum=0;
        PdmReportPlanNextWeek next = new PdmReportPlanNextWeek();
        next.setReportDate(nextMonday);
        next.setReportEndDate(nextSunday);
        List<PdmReportPlanNextWeek> nextList = pdmReportPlanNextWeekService.selectPdmReportPlanNextWeekList(next);
        if(nextList!=null && nextList.size()>1){
            next=nextList.get(nextList.size()-1);
            nextWeekJobRecNum=next.getWorkTotal();
            nextWeekSwitchingNum=next.getWorkType1Sum();
            distribuNetworkEngineNum=next.getWorkType2Sum();
            nextWeekExpanRelocationNum=next.getWorkType3Sum();
            nextWeekMaintenanceNum=next.getWorkType4Sum();
            threeLevelRiskNum=next.getPlanLeve3();
            fourLevelRiskNum=next.getPlanLeve4();
            fiveLevelRiskNum=next.getPlanLeve5();
            liveWorkingNum=next.getElePlanSum();
        }

        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",nextWeekJobRecNum);//配网专业计划总数
        dataMap.put("nextWeekSwitchingNum",nextWeekSwitchingNum);//倒闸操作
        dataMap.put("distribuNetworkEngineNum",distribuNetworkEngineNum);//配网工程
        dataMap.put("nextWeekExpanRelocationNum",nextWeekExpanRelocationNum);//业扩杆迁
        dataMap.put("nextWeekMaintenanceNum",nextWeekMaintenanceNum);//运维检修
        dataMap.put("threeLevelRiskNum",threeLevelRiskNum);//三级风险作业
        dataMap.put("fourLevelRiskNum",fourLevelRiskNum);//四级风险作业
        dataMap.put("fiveLevelRiskNum",fiveLevelRiskNum);//五级风险作业
        dataMap.put("liveWorkingNum",liveWorkingNum);//带电作业
        dataMap.put("liveDisconnectLeadNum",0);//带电断接引
        dataMap.put("assemDeviceNum",0);//带电消缺、装拆设备
        //三级及以上作业风险计划
        PdmWorkPlanDTO workPlan = new PdmWorkPlanDTO();
        workPlan.setStartDate(nextMonday);
        workPlan.setEndDate(nextSunday);
        workPlan.setLevel3Flag("1");//三级及以上作业
        List<PdmWorkPlan> workList = pdmWorkPlanService.selectPdmWorkPlanList(workPlan);
        dataMap.put("threeLevelRiskWorkList",workList);//三级及以上作业列表明细

        //三级风险作业内容：
       // List<ThreeLevelRiskJob> threeLevelRiskJobs=new ArrayList<ThreeLevelRiskJob>() ;
        StringBuilder builder=new StringBuilder();
        for(int i=0;i<workList.size();i++){
            PdmWorkPlan  threeLevelRiskJob=workList.get(i);
            month=new SimpleDateFormat("MM").format(threeLevelRiskJob.getPlanStartWkTm());
            String day=new SimpleDateFormat("dd").format(threeLevelRiskJob.getPlanStartWkTm());
            builder.append(threeLevelRiskJob.getSubmitOrgNm()).append(": ").append(month+"月"+day+"日").append(",").append(threeLevelRiskJob.getOpContent()).append("。").append("\r\n").append("&nbsp;&nbsp;&nbsp;");
        }
        dataMap.put("threeLevelRiskJobs",StringUtils.isEmpty(builder.toString())?"无":builder.toString().replaceAll("\r\n", "<w:br/>").replaceAll("&nbsp;","<w:tab/>"));//三级风险作业内容：
        dataMap.put("fousMaintenanceNum",0);//重点关注检修面个数
        String fousMaintenanceInfo="";//重点关注检修面内容
        dataMap.put("fousMaintenanceInfo", StringUtils.isEmpty(fousMaintenanceInfo)?"无":fousMaintenanceInfo);//重点关注检修面内容
        //下周计划安排情况
        dataMap.put("nextWeekWorkList",nextList);//下周计划安排情况列表

        //二、专业反违章履职情况
        //1.本周违章查处情况
        long provinceInvestSeriousRecNum=0;
        long provinceInvestGeneralRecNum=0;
        long cityInvestSeriousRecNum=0;
        long cityInvestGeneralRecNum=0;
        long countyInvestSeriousRecNum=0;
        long countyInvestGeneralRecNum=0;
        PdmReportIllegalWeek pdmReportIllegal = new PdmReportIllegalWeek();
        pdmReportIllegal.setReportDate(beingDate);
        pdmReportIllegal.setReportEndDate(endDate);
        List<PdmReportIllegalWeek> illegalList = pdmReportIllegalWeekService.selectPdmReportIllegalWeekList(pdmReportIllegal);
        if(illegalList!=null && illegalList.size()>1){
            pdmReportIllegal=illegalList.get(illegalList.size()-1);
            provinceInvestSeriousRecNum=pdmReportIllegal.getProvinceNum1();
            provinceInvestGeneralRecNum=pdmReportIllegal.getProvinceNum2();
            cityInvestSeriousRecNum=pdmReportIllegal.getCityNum1();
            cityInvestGeneralRecNum=pdmReportIllegal.getCityNum2();
            countyInvestSeriousRecNum=pdmReportIllegal.getCountyNum1();
            countyInvestGeneralRecNum=pdmReportIllegal.getCountyNum2();
        }
        dataMap.put("investPunishRecAllNum",(provinceInvestSeriousRecNum+provinceInvestGeneralRecNum+cityInvestSeriousRecNum+cityInvestGeneralRecNum+countyInvestSeriousRecNum+countyInvestGeneralRecNum));//配网专业共计查处违章
        dataMap.put("provinceInvestPunishRecNum",(provinceInvestSeriousRecNum+provinceInvestGeneralRecNum));//被省公司查处违章
        dataMap.put("cityInvestPunishRecNum",(cityInvestSeriousRecNum+cityInvestGeneralRecNum));//被市公司查处违章
        dataMap.put("cityInvestSeriousRecNum",cityInvestSeriousRecNum);//严重违章
        dataMap.put("cityInvestGeneralRecNum",cityInvestGeneralRecNum);//一般违章
        dataMap.put("countyInvestPunishRecNum",(countyInvestSeriousRecNum+countyInvestGeneralRecNum));//县区公司自查处违章
        dataMap.put("countyInvestSeriousRecNum",countyInvestSeriousRecNum);//严重违章
        dataMap.put("countyInvestGeneralRecNum",countyInvestGeneralRecNum);//一般违章
        //本周违章查处情况列表
        dataMap.put("illegalList",illegalList);//违章列表明细
        String typicalIllegal="";//其中典型违章通报如下
        dataMap.put("typicalIllegal",StringUtils.isEmpty(typicalIllegal)?"无":typicalIllegal);//其中典型违章通报如下


        //2.本周人员到岗到位履职情况
        long leaderSupervTimes=0;
        long manageSupervTimes=0;
        long problemNum=0;
        long cityFindProblemNum=0;
        long derelictionDutyNum=0;
        PdmReportAppointmentWeek pdmReportAppointment = new PdmReportAppointmentWeek();
        pdmReportAppointment.setReportDate(beingDate);
        pdmReportAppointment.setReportEndDate(endDate);
        List<PdmReportAppointmentWeek> appointmentlist = pdmReportAppointmentWeekService.selectPdmReportAppointmentWeekList(pdmReportAppointment);

        if(appointmentlist!=null && appointmentlist.size()>1) {
            pdmReportAppointment=appointmentlist.get(appointmentlist.size()-1);
            leaderSupervTimes=pdmReportAppointment.getBossSum();
            manageSupervTimes=pdmReportAppointment.getManageSum();
            problemNum=pdmReportAppointment.getProblemSum();
            cityFindProblemNum=pdmReportAppointment.getCityCheckSum();
            derelictionDutyNum=pdmReportAppointment.getAbsentSum();

        }
        dataMap.put("appointmentlist",appointmentlist);//本周到岗到位履职情况
        dataMap.put("supervTimes",(leaderSupervTimes+manageSupervTimes));//督察共计次数
        dataMap.put("leaderSupervTimes",leaderSupervTimes);//领导督察共计次数
        dataMap.put("manageSupervTimes",manageSupervTimes);//管理人员督察次数
        dataMap.put("problemNum",problemNum);//督察发现问题
        dataMap.put("cityFindProblemNum",cityFindProblemNum);//市公司发现问题处数
        dataMap.put("derelictionDutyNum",derelictionDutyNum);//履职不到位(应查未查）



        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();
        }
  }
}
