package com.xunmei.core.resumption.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xunmei.common.core.constant.SecurityConstants;
import com.xunmei.common.core.constant.SystemParameterConstant;
import com.xunmei.common.core.utils.DateHelper;
import com.xunmei.common.core.utils.IDHelper;
import com.xunmei.common.core.utils.ResumptionStatus;
import com.xunmei.core.resumption.domain.*;
import com.xunmei.core.resumption.dto.AppResumptionDataDto;
import com.xunmei.core.resumption.dto.ResumptionTaskDataDto;
import com.xunmei.core.resumption.dto.ResumptionTaskDto;
import com.xunmei.core.resumption.dto.TaskDetailsDto;
import com.xunmei.core.resumption.vo.*;
import com.xunmei.system.api.RemoteConfigService;
import com.xunmei.system.api.domain.SysConfig;
import com.xunmei.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class ResumptionBusiness {
    @Autowired
    private ResumptionService resumptionService;
    @Autowired
    private AppResumptionDataNfcService appResumptionDataNfcService;
    @Autowired
    private AppResumptionTaskDataRemarkimgService appResumptionTaskDataRemarkimgService;
    @Autowired
    private RemoteConfigService systemParameService;
    @Autowired
    private IAppRulePointService appRulePointService;
    @Autowired
    private AppResumptionDataService appResumptionDataService;
    public Map<String, Object> tasktotal(ResumptionTaskDto request) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        final DateHelper dateTime = new DateHelper(sdf.parse(request.getDateTime()));
        int year =dateTime.getYear();
        int month = dateTime.getMonth();
        int week = dateTime.getWeek();
        int quarter =dateTime.getQuarter() ;
        int halfyear =dateTime.getHalfyear() ;
        String time = request.getDateTime();
        Map<String,Object> tasktotal = new HashMap<>();
        if(request.getTypeCode().equals("day")){//返回每日，没小时的数据
            //统计数据
            Map<String,Object> hourtotal = new HashMap<>();
            Map<String,Object> daytotal = new HashMap<>();
            //统计每日的所有任务数据
            //List<Resumption> dayList = resumptionService.findListByDay(time,Long.valueOf(request.getRoleId()),Long.valueOf(request.getOrgid()));
            List<Map<String,Object>> dayList = resumptionService.findDayTaskList(year,quarter,time,Long.valueOf(request.getRoleId()),Long.valueOf(request.getOrgid()));
            //List<Map<String,Object>> dayList = objectMapper.findDayTaskList(year,quarter,time,Long.valueOf(request.getRoleId()),Long.valueOf(request.getOrgid()));
            //统计每小时的任务数据
            int hourfinishnum = (int) dayList.stream().filter(r->(int)r.get("type")==6&&((int)r.get("status")==1||(int)r.get("status")==2||(int)r.get("status")==5)).count();
            int  hourundonenum = (int) dayList.stream().filter(r->(int)r.get("type")==6&&(int)r.get("status")==3).count();
            int  hourwaitenum = (int) dayList.stream().filter(r->(int)r.get("type")==6&&(int)r.get("status")==0).count();
            int  hourtotalall = (int) dayList.stream().filter(r->(int)r.get("type")==6).count();
            hourtotal.put("finishnum",hourfinishnum);
            hourtotal.put("undonenum",hourundonenum);
            hourtotal.put("waitenum",hourwaitenum);
            hourtotal.put("tasknum",hourtotalall);
            tasktotal.put("hourtotal",hourtotal);
            //统计每日的任务数据
            int  dayfinishnum = (int) dayList.stream().filter(r->(int)r.get("type")==0&&((int)r.get("status")==1||(int)r.get("status")==2||(int)r.get("status")==5)).count();
            int dayundonenum = (int) dayList.stream().filter(r->(int)r.get("type")==0&&(int)r.get("status")==3).count();
            int daywaitnum = (int) dayList.stream().filter(r->(int)r.get("type")==0&&(int)r.get("status")==0).count();
            int daytotalall = (int) dayList.stream().filter(r->(int)r.get("type")==0).count();
            daytotal.put("finishnum",dayfinishnum);
            daytotal.put("undonenum",dayundonenum);
            daytotal.put("waitenum",daywaitnum);
            daytotal.put("tasknum",daytotalall);
            tasktotal.put("daytotal",daytotal);

            List<Map<String,Object>> hourlistMap = dayList.stream().filter(r->(int)r.get("type")==6).collect(Collectors.toList());
            List<ResumptionTaskListVo> hourlist = taskListVo(hourlistMap,6);
            tasktotal.put("hourlist",hourlist);
            List<Map<String,Object>> daylistMap = dayList.stream().filter(r->(int)r.get("type")==0).collect(Collectors.toList());
            List<ResumptionTaskListVo> daylist = taskListVo(daylistMap,0);
            tasktotal.put("daylist",daylist);
            //获取任务列表
        }if(request.getTypeCode().equals("month")){//返回没月，每周的数据
            //统计数据
            Map<String,Object> weektotal = new HashMap<>();
            Map<String,Object> monthtotal = new HashMap<>();
            //统计每周的任务数据
            List<Map<String,Object>> weekList =resumptionService.findMonthTaskList(year,month,1,Long.valueOf(request.getRoleId()),Long.valueOf(request.getOrgid()),quarter);
            //统计每月的任务数据
            List<Map<String,Object>> monthList = resumptionService.findMonthTaskList(year,month,2,Long.valueOf(request.getRoleId()),Long.valueOf(request.getOrgid()),quarter);
            int weekfinishnum =(int) weekList.stream().filter(r->((int)r.get("status")==1||(int)r.get("status")==2||(int)r.get("status")==5)).count();
            int weekundonenum =(int) weekList.stream().filter(r->(int)r.get("status")==3).count();
            int weekwaitnum =(int) weekList.stream().filter(r->(int)r.get("status")==0).count();
            int weektotall =weekList.size();
            weektotal.put("finishnum",weekfinishnum);
            weektotal.put("undonenum",weekundonenum);
            weektotal.put("waitenum",weekwaitnum);
            weektotal.put("tasknum",weektotall);
            tasktotal.put("weektotal",weektotal);
            int monthfinishnum =(int) monthList.stream().filter(r->((int)r.get("status")==1||(int)r.get("status")==2||(int)r.get("status")==5)).count();
            int monthundonenum =(int) monthList.stream().filter(r->(int)r.get("status")==3).count();
            int monthwaitnum =(int) monthList.stream().filter(r->(int)r.get("status")==0).count();
            int monthtotall =monthList.size();
            monthtotal.put("finishnum",monthfinishnum);
            monthtotal.put("undonenum",monthundonenum);
            monthtotal.put("waitenum",monthwaitnum);
            monthtotal.put("tasknum",monthtotall);
            tasktotal.put("monthtotal",monthtotal);
            List<ResumptionTaskListVo> weeklist = taskListVo(weekList,1);
            List<ResumptionTaskListVo> monthlist = taskListVo(monthList,2);
            tasktotal.put("weeklist",weeklist);
            tasktotal.put("monthlist",monthlist);
            //获取任务列表

        }if(request.getTypeCode().equals("year")){//返回每季度，每半年，和每年的数据
            //统计数据
            Map<String,Object> quartertotal = new HashMap<>();
            Map<String,Object> halfyeartotal = new HashMap<>();
            Map<String,Object> yeartotal = new HashMap<>();
            //统计每季度的任务数据
            List<Map<String,Object>> quarterList = resumptionService.findYearTaskList(year,3,Long.valueOf(request.getRoleId()),Long.valueOf(request.getOrgid()),quarter);
            List<Map<String,Object>> halfyearList = resumptionService.findYearTaskList(year,4,Long.valueOf(request.getRoleId()),Long.valueOf(request.getOrgid()),quarter);
            List<Map<String,Object>> yearList = resumptionService.findYearTaskList(year,5,Long.valueOf(request.getRoleId()),Long.valueOf(request.getOrgid()),1);
            int quarterfinishnum =(int) quarterList.stream().filter(r->((int)r.get("status")==1||(int)r.get("status")==2||(int)r.get("status")==5)).count();
            int quarterundonenum =(int) quarterList.stream().filter(r->(int)r.get("status")==3).count();
            int quarterwaitnum =(int) quarterList.stream().filter(r->(int)r.get("status")==0).count();
            int quartertotall =quarterList.size();
            quartertotal.put("finishnum",quarterfinishnum);
            quartertotal.put("undonenum",quarterundonenum);
            quartertotal.put("waitenum",quarterwaitnum);
            quartertotal.put("tasknum",quartertotall);
            tasktotal.put("quartertotal",quartertotal);
            //统计每半年的任务数据
            int halfyearfinishnum =(int) halfyearList.stream().filter(r->((int)r.get("status")==1||(int)r.get("status")==2||(int)r.get("status")==5)).count();
            int halfyearundonenum =(int) halfyearList.stream().filter(r->(int)r.get("status")==3).count();
            int halfyearwaitnum =(int) halfyearList.stream().filter(r->(int)r.get("status")==0).count();
            int halfyeartotalall =halfyearList.size();
            halfyeartotal.put("finishnum",halfyearfinishnum);
            halfyeartotal.put("undonenum",halfyearundonenum);
            halfyeartotal.put("waitenum",halfyearwaitnum);
            halfyeartotal.put("tasknum",halfyeartotalall);
            tasktotal.put("halfyeartotal",halfyeartotal);
            //统计每年的任务数据
            int yearfinishnum =(int) yearList.stream().filter(r->((int)r.get("status")==1||(int)r.get("status")==2||(int)r.get("status")==5)).count();
            int yearundonenum =(int) yearList.stream().filter(r->(int)r.get("status")==3).count();
            int yearwaitnum =(int) yearList.stream().filter(r->(int)r.get("status")==0).count();
            int yeartotalall =yearList.size();
            yeartotal.put("finishnum",yearfinishnum);
            yeartotal.put("undonenum",yearundonenum);
            yeartotal.put("waitenum",yearwaitnum);
            yeartotal.put("tasknum",yeartotalall);
            tasktotal.put("yeartotal",yeartotal);

            List<ResumptionTaskListVo> quarterlist = taskListVo(quarterList,3);
            List<ResumptionTaskListVo> halfyearlist = taskListVo(halfyearList,4);
            List<ResumptionTaskListVo> yearlist = taskListVo(yearList,5);

            tasktotal.put("quarterlist",quarterlist);
            tasktotal.put("halfyearlist",halfyearlist);
            tasktotal.put("yearlist",yearlist);


        }
        return tasktotal;
    }
    public List<ResumptionTaskListVo> taskListVo(List<Map<String,Object>> list,int type) throws ParseException {
        List<ResumptionTaskListVo> listVos = new ArrayList<>();
        List<Map<String,Object>> taskarealist = new ArrayList<>();
        SimpleDateFormat sdft = new SimpleDateFormat("HH:mm:ss");
        sdft.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        SimpleDateFormat sdfta = new SimpleDateFormat("yyyy-MM-dd");
        sdfta.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        SimpleDateFormat sdftb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdftb.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        if(type==6){//处理每小时的数据
            for(Map map:list){
                ResumptionTaskListVo vo = new ResumptionTaskListVo();
                vo.setId(map.get("id").toString());
                vo.setPlanstarttime(map.get("planstarttime")==null?"":sdft.format((Date) map.get("planstarttime")));
                vo.setPlanendtime(map.get("planendtime")==null?"":sdft.format((Date) map.get("planendtime")));
                vo.setTitle(map.get("title").toString());
                vo.setStatus((int)map.get("status"));
                vo.setSubmitBy(map.get("submitBy")==null?"":map.get("submitBy").toString());
                vo.setSubmitTime(map.get("submitTime")==null?"":sdftb.format((Date) map.get("submitTime")));
                listVos.add(vo);
            }
        } if(type==0){//处理每日的数据
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            for(Map map:list){
                ResumptionTaskListVo vo = new ResumptionTaskListVo();
                vo.setId(map.get("id").toString());
                vo.setPlanstarttime(map.get("planstarttime")==null?"":sdft.format((Date) map.get("planstarttime")));
                vo.setPlanendtime(map.get("planendtime")==null?"":sdft.format((Date) map.get("planendtime")));
                vo.setTitle(map.get("title").toString());
                vo.setStatus((int)map.get("status"));
                vo.setSubmitBy(map.get("submitBy")==null?"":map.get("submitBy").toString());
                vo.setSubmitTime(map.get("submitTime")==null?"":sdftb.format((Date) map.get("submitTime")));
                listVos.add(vo);
            }

        } if(type==1){//处理每周的数据
            for(Map map:list){
                ResumptionTaskListVo vo = new ResumptionTaskListVo();
                vo.setId(map.get("id").toString());
                vo.setPlanstarttime(map.get("planstarttime")==null?"":sdfta.format((Date) map.get("planstarttime")));
                vo.setPlanendtime(map.get("planendtime")==null?"":sdfta.format((Date) map.get("planendtime")));
                vo.setTitle(map.get("ymd_year")+"年第"+map.get("ymd_week")+"周-"+map.get("title"));
                vo.setStatus((int)map.get("status"));
                vo.setSubmitBy(map.get("submitBy")==null?"":map.get("submitBy").toString());
                vo.setSubmitTime(map.get("submitTime")==null?"":sdftb.format((Date) map.get("submitTime")));
                listVos.add(vo);
            }

        } if(type==2){//处理每月的数据
            for(Map map:list){
                ResumptionTaskListVo vo = new ResumptionTaskListVo();
                vo.setId(map.get("id").toString());
                vo.setPlanstarttime(map.get("planstarttime")==null?"":sdfta.format((Date) map.get("planstarttime")));
                vo.setPlanendtime(map.get("planendtime")==null?"":sdfta.format((Date) map.get("planendtime")));
                vo.setTitle(map.get("ymd_year")+"年第"+map.get("ymd_month")+"月-"+map.get("title"));
                vo.setStatus((int)map.get("status"));
                vo.setSubmitBy(map.get("submitBy")==null?"":map.get("submitBy").toString());
                vo.setSubmitTime(map.get("submitTime")==null?"":sdftb.format((Date) map.get("submitTime")));
                listVos.add(vo);
            }

        } if(type==3){//处理每季度的数据
            for(Map map:list){
                ResumptionTaskListVo vo = new ResumptionTaskListVo();
                vo.setId(map.get("id").toString());
                vo.setPlanstarttime(map.get("planstarttime")==null?"":sdfta.format((Date) map.get("planstarttime")));
                vo.setPlanendtime(map.get("planendtime")==null?"":sdfta.format( (Date) map.get("planendtime")));
                vo.setTitle(map.get("ymd_year")+"年第"+map.get("ymd_quarter")+"季度-"+map.get("title"));
                vo.setStatus((int)map.get("status"));
                vo.setSubmitBy(map.get("submitBy")==null?"":map.get("submitBy").toString());
                vo.setSubmitTime(map.get("submitTime")==null?"":sdftb.format((Date) map.get("submitTime")));
                listVos.add(vo);
            }

        } if(type==4){//处理每半年的数据
            for(Map map:list){
                ResumptionTaskListVo vo = new ResumptionTaskListVo();
                vo.setId(map.get("id").toString());
                vo.setPlanstarttime(map.get("planstarttime")==null?"":sdfta.format((Date) map.get("planstarttime")));
                vo.setPlanendtime(map.get("planendtime")==null?"":sdfta.format((Date) map.get("planendtime")));
                int ymd_halfyear = (int) map.get("ymd_halfyear");
                String strhalfyear = "";
                switch (ymd_halfyear){
                    case 1:strhalfyear="上半年";break;
                    case 2:strhalfyear="下半年";break;
                }
                vo.setTitle(map.get("ymd_year")+"年"+strhalfyear+"-"+map.get("title"));
                vo.setStatus((int)map.get("status"));
                vo.setSubmitBy(map.get("submitBy")==null?"":map.get("submitBy").toString());
                vo.setSubmitTime(map.get("submitTime")==null?"":sdftb.format((Date) map.get("submitTime")));
                listVos.add(vo);
            }

        } if(type==5){//处理每年的数据
            for(Map map:list){
                ResumptionTaskListVo vo = new ResumptionTaskListVo();
                vo.setId(map.get("id").toString());
                vo.setPlanstarttime(map.get("planstarttime")==null?"":sdfta.format((Date) map.get("planstarttime")));
                vo.setPlanendtime( map.get("planendtime")==null?"":sdfta.format((Date) map.get("planendtime")));
                vo.setTitle(map.get("ymd_year")+"年-"+map.get("title"));
                vo.setStatus((int)map.get("status"));
                vo.setSubmitBy(map.get("submitBy")==null?"":map.get("submitBy").toString());
                vo.setSubmitTime(map.get("submitTime")==null?"":sdftb.format((Date) map.get("submitTime")));
                listVos.add(vo);
            }

        }
        return listVos;
    }
    public List<Map<String,Object>>taskarealistnew(TaskDetailsDto request){
        //根据计划id 关联要点，获取区域列表
        //Resumption resumption = resumptionService.find(taskid);
        Resumption resumption = resumptionService.findOneByTaskIdAndDate(request);
        String taskid = request.getTaskId();
        List<ResumptionNfcInfoVo> nfcs = appResumptionDataNfcService.findPointNfcData(taskid, resumption.getOrgId());
        //List<AppResumptionDataImg> imgs = appResumptionDataImgService.getResumptionImgs(resumption.getId());
        List<AppResumptionTaskDataRemarkimg> imgs = appResumptionTaskDataRemarkimgService.list((new QueryWrapper<AppResumptionTaskDataRemarkimg>()).lambda().eq(AppResumptionTaskDataRemarkimg::getTaskId,resumption.getId()));
        List<ResumptionInfoVo> list = appResumptionDataService.findDataByTaskId(taskid);
        Map<Long,List<AppResumptionTaskDataRemarkimg>> pointImgs = new HashMap<>();
        for (AppResumptionTaskDataRemarkimg img : imgs) {
            List<AppResumptionTaskDataRemarkimg> imgList = pointImgs.get(img.getTaskDataId());
            if(imgList == null){
                imgList = new ArrayList<>();
                imgList.add(img);
                pointImgs.put(img.getTaskDataId(),imgList);
            }else{
                imgList.add(img);
                pointImgs.put(img.getTaskDataId(),imgList);
            }
        }
        Map<Long,Set<ResumptionNfcInfoVo>> areaMap = new HashMap<>();
        Map<Long,List<ResumptionNfcInfoVo>> itemNfc = new HashMap<>();
        for (ResumptionNfcInfoVo nfc : nfcs) {
            Set<ResumptionNfcInfoVo> infos = areaMap.get(nfc.getAreaId());
            if(infos == null){
                infos = new HashSet<>();
                infos.add(nfc);
                areaMap.put(nfc.getAreaId(),infos);
            }else{
                infos.add(nfc);
                areaMap.put(nfc.getAreaId(),infos);
            }
            List<ResumptionNfcInfoVo> pointNfcs = itemNfc.get(nfc.getPointId());
            if(pointNfcs == null){
                pointNfcs = new ArrayList<>();
                pointNfcs.add(nfc);
                itemNfc.put(nfc.getPointId(),pointNfcs);
            }else{
                pointNfcs.add(nfc);
                itemNfc.put(nfc.getPointId(),pointNfcs);
            }
        }
        Map<Long,Map<String,Object>> rel = new HashMap<>();
        Map<Long,Map<String,Object>> items = new HashMap<>();
        for (ResumptionInfoVo obj : list) {
            Long areaId = obj.getAreaId();
            Map<String, Object> areaData = rel.get(areaId);
            if(areaData == null){
                //如果不存在区域
                areaData = new HashMap<>();
                areaData.put("areaid",areaId.toString());
                areaData.put("areaname",obj.getAreaName());
                areaData.put("nfclist",areaMap.get(areaId)==null?new ArrayList<>():areaMap.get(areaId));
                List<Map<String,Object>> checklist = new ArrayList<>();
                Map<String,Object> item = new HashMap<>();
                item.put("itemid",obj.getItemId());
                item.put("itemname",obj.getItemName());
                List<Map<String,Object>> checkitemlist = new ArrayList<>();
                Map<String,Object> checkItem =  sealData(obj,itemNfc,pointImgs);
                checkitemlist.add(checkItem);
                item.put("checkitemlist",checkitemlist);
                items.put(obj.getItemId(),item);
                checklist.add(item);
                areaData.put("checklist",checklist);
                rel.put(areaId,areaData);
            }else{
                //如果存在区域
                Map<String, Object> item = items.get(obj.getItemId());
                List<Map<String,Object>> checklist = (List<Map<String, Object>>) areaData.get("checklist");
                if(item == null){
                    item = new HashMap<>();
                    item.put("itemid",obj.getItemId());
                    item.put("itemname",obj.getItemName());
                    List<Map<String,Object>> checkitemlist = new ArrayList<>();
                    Map<String,Object> checkItem = sealData(obj,itemNfc,pointImgs);
                    checkitemlist.add(checkItem);
                    item.put("checkitemlist",checkitemlist);
                    items.put(obj.getItemId(),item);
                    checklist.add(item);
                }else{
                    List<Map<String,Object>> checkitemlist = (List<Map<String, Object>>) item.get("checkitemlist");
                    Map<String,Object> checkItem  = sealData(obj,itemNfc,pointImgs);
                    checkitemlist.add(checkItem);
                    item.put("checkitemlist",checkitemlist);
                    items.put(obj.getItemId(),item);
                }
                rel.put(areaId,areaData);
            }
        }
        List<Map<String,Object>> results = new ArrayList<>();
        for (Map.Entry<Long,Map<String,Object>> entry : rel.entrySet()){
            Map<String, Object> value = entry.getValue();
            results.add(value);
        }
        return results;
    }
    private Map<String, Object> sealData(ResumptionInfoVo obj, Map<Long, List<ResumptionNfcInfoVo>> itemNfc, Map<Long, List<AppResumptionTaskDataRemarkimg>> pointImgs) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        Map<String,Object> checkItem = new HashMap<>();
        checkItem.put("pointid",obj.getPointId());
        checkItem.put("pointname",obj.getPointName());
        checkItem.put("resvalue",obj.getDataValue());
        checkItem.put("resstatus",obj.getDataStatus());
        checkItem.put("resTime",obj.getDataTime() == null ? "" :sdf.format(obj.getDataTime()));
        checkItem.put("timeType",obj.getTimeType());
        checkItem.put("pointdataid",obj.getId());
        checkItem.put("pointnfclist",itemNfc.get(obj.getPointId())==null?new ArrayList<>():itemNfc.get(obj.getPointId()));
        checkItem.put("imglist",pointImgs.get(obj.getId())==null?new ArrayList<>():pointImgs.get(obj.getId()));
        checkItem.put("pointnum",obj.getPointNum());
        checkItem.put("resremark",obj.getDataRemark());
        return checkItem;
    }

    public ResumptionTaskListVo getTaskObjByTaskid(TaskDetailsDto request) throws ParseException {
        List<Map<String, Object> > map = resumptionService.findOneByTaskId(request);

        return  taskListVo(map,(int) map.get(0).get("type")).get(0);

    }
    @Transactional(rollbackFor = Exception.class)
    public void deleteTaskData(Resumption resumption) {
        //删除Nfc数据
        QueryWrapper<AppResumptionDataNfc> qwNfc = new QueryWrapper();
        qwNfc.lambda().eq(AppResumptionDataNfc::getResumptionId,resumption.getId());
        appResumptionDataNfcService.remove(qwNfc);
        //删除检查项数据
        QueryWrapper<AppResumptionData> qwData = new QueryWrapper();
        qwData.lambda().eq(AppResumptionData::getResumptionId,resumption.getId());
        appResumptionDataService.remove(qwData);
        //删除备注
//        QueryWrapper<AppResumptionTaskDataRemark> qwRemark = new QueryWrapper();
//        qwRemark.lambda().eq(AppResumptionTaskDataRemark::getTaskId,resumption.getId());
//        appResumptionTaskDataRemarkService.remove(qwRemark);
        //删除图片
        QueryWrapper<AppResumptionTaskDataRemarkimg> qwRemarkImg = new QueryWrapper();
        qwRemarkImg.lambda().eq(AppResumptionTaskDataRemarkimg::getTaskId,resumption.getId());
        appResumptionTaskDataRemarkimgService.remove(qwRemarkImg);
        //删除问题整改()
//        QueryWrapper<AppQuestionTask> qwQuestion = new QueryWrapper();
//        qwQuestion.lambda().eq(AppQuestionTask::getTaskId,resumption.getId());
//        qwQuestion.lambda().eq(AppQuestionTask::getStatus,0);
//        List<AppQuestionTask> taskList =appQuestionTaskService.list(qwQuestion);
//        appQuestionTaskService.remove(qwQuestion);
        //删除问题整改的待办
//        List<String> taskIds = new ArrayList<>();
//        for(AppQuestionTask task :taskList){
//            taskIds.add(task.getId().toString());
//        }
//        todoService.remove(taskIds);


    }
    public List<Map<String,Object>> toTaskDetails(TaskDetailsDto request){
        SysConfig nfcLock = systemParameService.findFirstByCode(SystemParameterConstant.NFC_RESUMPTION_LOCK, SecurityConstants.INNER).getData();
        //Resumption resumption = resumptionService.find(taskid);
        Resumption resumption = resumptionService.findOneByTaskIdAndDate(request);
        List<Map<String,Object>> arealsit = new ArrayList<>();
        List<ResumptionPointVo> pointList = appRulePointService.findPointByRulePlan(resumption.getPlanId());
        Set<Long> nfcBindIdList = new HashSet<>();
        pointList.forEach(r->{
            nfcBindIdList.add(r.getAreaid());
            r.setPointdataid(IDHelper.id());
        });
        //获取nfc
        List<ResumptionNfcVo> nfclists =appResumptionDataNfcService.findNfcByAreaIdAndOrgId(nfcBindIdList,resumption.getOrgId(),resumption.getPlanId());
        //对nfc进行去重
        List<ResumptionNfcVo> nfclist = nfclists.stream().collect(Collectors.collectingAndThen
                (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ResumptionNfcVo-> ResumptionNfcVo.getNfccdoe()))), ArrayList::new));

        try{
            for(ResumptionPointVo pointVo:pointList) {
                List<ResumptionNfcVo> nfclista = nfclist.stream().filter(r -> r.getPointId().equals(pointVo.getPointid())).collect(Collectors.toList());
                if (nfclista != null && nfclista.size() > 0) {
                    nfclista.forEach(r -> r.setNfcdataid(IDHelper.id()));
                }
                pointVo.setPointnfclist(nfclista == null ? new ArrayList<>() : nfclista);
                //如果是布撤防数据要显示默认时间


                DateTime datetime = new DateTime();
                datetime.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                Date startTime = datetime.setField(DateField.HOUR_OF_DAY, 0).setField(DateField.MINUTE, 0).setField(DateField.SECOND, 0);
                Date endTime = DateUtil.endOfDay(datetime).offset(DateField.MILLISECOND, -999);
                SimpleDateFormat sdftb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdftb.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                String strStartTime = sdftb.format(startTime);
                String strEndTime = sdftb.format(endTime);
//                //撤防时间
//                ProtectionLog log = null;
//                if ((pointVo.getPointid().equals("3916620810321920") || pointVo.getPointname().equals("入侵报警撤防时间")) && pointVo.getTimeType() == 1) {
//                    log = protectionLogService.findCFLogByOrg(resumption.getOrgId(), startTime, endTime);
//                }
//                if ((pointVo.getPointid().equals("3916637791404032") || pointVo.getPointname().equals("入侵报警设防时间")) && pointVo.getTimeType() == 1) {
//                    log = protectionLogService.findBFLogByOrg(resumption.getOrgId(), startTime, endTime);
//                }
//                if (log != null) {
//                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
//                    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//                    pointVo.setResTime(sdf.format(log.getUpdateTime()));
//                }
//
//                if (pointVo.getBusinessType() != null) {
//                    AppPlan plan= appPlanService.getById(resumption.getPlanId());
//                    dealWithPointBusinessData(pointVo,resumption,plan);
//                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
        //将数据按区域分组
        Map<Long,List<ResumptionPointVo>> pointListMap = pointList.stream().collect(Collectors.groupingBy(r->r.getAreaid()));
        for(Long key:pointListMap.keySet()){
            List<ResumptionPointVo> pointsList = pointListMap.get(key);
            if(pointsList==null||pointsList.size()==0){
                continue;
            }


            Map<String,Object> area = new HashMap<>();
            area.put("areaid",key.toString());
            area.put("areaname",pointsList.get(0).getAreaname());
            List<ResumptionNfcVo> areanfclist = nfclist.stream().filter(r->r.getAreaId().equals(key)).collect(Collectors.toList());
            if("0".equals(nfcLock.getValue())){
                if(areanfclist == null || areanfclist.size() == 0){
                    continue;
                }

            }

            area.put("nfclist",areanfclist==null?new ArrayList<>():areanfclist);
            //将区域内的要点按检查项分组
            Map<Long,List<ResumptionPointVo>> pointsListMapItem = pointsList.stream().collect(Collectors.groupingBy(r->r.getItemid()));
            List<Map<String,Object>> checklist = new ArrayList<>();
            for(Long keya:pointsListMapItem.keySet()){
                List<ResumptionPointVo> checkitemlist = pointsListMapItem.get(keya);
                if(checkitemlist==null||checkitemlist.size()==0){
                    continue;
                }
                Map<String,Object> item = new HashMap<>();
                item.put("itemid",keya);
                item.put("itemname",checkitemlist.get(0).getItemname());
                item.put("checkitemlist",checkitemlist);
                checklist.add(item);
            }
            area.put("checklist",checklist);
            arealsit.add(area);

        }
        return arealsit;
    }
    @Transactional(rollbackFor = Exception.class)
    public int submitTaskData(ResumptionTaskDataDto request, LoginUser user, Resumption resumption) throws ParseException {
        int result = 0;
        Date time = new Date();
        List<AppResumptionDataNfc> nfcList = request.getNfcdata();
        //传值的时候，要新增nfcId（页面取checkId）pointId
        nfcList.stream().forEach(n->n.setResumptionId(request.getTaskid()).setId(IDHelper.id()));
        //传值的时候，要新增nfcId（页面取checkId）pointId
        appResumptionDataNfcService.saveBatch(nfcList);
        //获取未扫描的nfc数据
        List<AppResumptionDataDto> resumptionDataList = request.getPointdata();
        final List<AppResumptionData> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//        List<AppResumptionTaskDataRemark> remarkDtoList = new ArrayList<>();
        for (AppResumptionDataDto appResumptionDataDto : resumptionDataList) {
            AppResumptionData data = new AppResumptionData();
            //页面传值 新增areaId 取值areaid，planId 取值planId， itemId页面取值pointid
            data.setId(appResumptionDataDto.getId());
            data.setAreaId(appResumptionDataDto.getAreaId());
            data.setPlanId(appResumptionDataDto.getPlanId());
            data.setItemId(appResumptionDataDto.getItemId());
            data.setResumptionId(request.getTaskid());
            //页面传值 新增areaId 取值areaid，planId 取值planId， itemId页面取值pointid
            data.setSubmitBy(user.getUserid()).setSubmitName(user.getUsername()).setSubmitTime(time);
            data.setResValue(appResumptionDataDto.getResValue());
            data.setResRemark(appResumptionDataDto.getResRemark());
            if(StringUtils.isNotEmpty(appResumptionDataDto.getResTime())){
                data.setResTime(sdf.parse(appResumptionDataDto.getResTime()));
            }
            if(time.before(resumption.getPlanEndTime())){
                //最终提交时间小于计划结束时间
                data.setResStatus(1);
            }else {
                //最终提交时间大于计划结束时间
                data.setResStatus(3);
            }
            list.add(data);
            if(StringUtils.isNotEmpty(appResumptionDataDto.getResRemark())||(appResumptionDataDto.getImgData()!=null&&appResumptionDataDto.getImgData().size()>0)) {
//                AppResumptionTaskDataRemark remark = new AppResumptionTaskDataRemark();
//                remark.setRemark(appResumptionDataDto.getResRemark() == null ? "" : appResumptionDataDto.getResRemark());
//                remark.setId(IDHelper.id());
//                remark.setTaskId(request.getTaskid());
//                remark.setTaskDataId(data.getId());
//                appResumptionTaskDataRemarkService.saveOne(remark);
//                try {
//                    if (StringUtils.isNotEmpty(remark.getRemark())) {
//                        appQuestionTaskService.createQuestionTask(request.getTaskid(), data.getItemId(), remark.getId(), user.getId(), user.getName(), 1,request);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                List<AppResumptionTaskDataRemarkimg> imgLista = appResumptionDataDto.getImgData();
//                //根据remark 删除图片
//                appResumptionTaskDataRemarkimgService.remove((new QueryWrapper<AppResumptionTaskDataRemarkimg>()).lambda().eq(AppResumptionTaskDataRemarkimg::getRemarkId, remark.getId()));
//                if (imgLista.size() > 0) {
//                    imgLista.forEach(r -> r.setId(IDHelper.id()).setRemarkId(remark.getId()).setTaskDataId(data.getId()).setTaskId(request.getTaskid()));
//                    appResumptionTaskDataRemarkimgService.saveBatch(imgLista);
//                }
            }
        }
        appResumptionDataService.saveBatch(list);
        //获取未提交的履职数据当未提交的履职数据为0时，修改履职任务为已完成
        int num = (int) appResumptionDataService.count((new QueryWrapper<AppResumptionData>()).lambda().eq(AppResumptionData::getResumptionId,request.getTaskid()).isNull(AppResumptionData::getSubmitTime));
        if(resumption.getStartTime()==null){//第一次提交数据的时候修改任务开始时间为当前时间
            resumption.setStartTime(time);
        }
        resumption.setEndTime(time);
        resumption.setSubmitTime(time);
        if(num==0){//所有履职数据都已提交
            if(time.before(resumption.getPlanEndTime())){
                //最终提交时间小于计划结束时间
                resumption.setStatus(ResumptionStatus.NORMAL);
            }else {
                //最终提交时间大于计划结束时间
                resumption.setStatus(ResumptionStatus.DELAY);
            }

        }
        //获取履职数据异常的数据个数
        int exceptionCount = (int) appResumptionDataService.count((new QueryWrapper<AppResumptionData>()).lambda().eq(AppResumptionData::getResumptionId,request.getTaskid()).eq(AppResumptionData::getResValue,1));
        resumption.setExceptionCount(exceptionCount);
        resumption.setUpdateTime(time);
//        resumption.setModifiedId(user.getId());
//        resumption.setModifiedName(user.getName());
        //resumptionService.save(resumption);
        resumptionService.updateResumption(resumption);
        //清除代办
//        this.todoService.remove(resumption.getId());
        return result;
    }
}
