package com.testor.module.report.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.sys.dict.data.controller.SysDictDataController;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataComplexResponse;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataListResponse;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataRequest;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.util.DateUtil;
import com.testor.ddd.safetyControl.application.service.spaceManage.SpaceManageService;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.space.TSafeSpaceVO;
import com.testor.module.duty.model.domain.TSysDuty;
import com.testor.module.duty.model.domain.*;
import com.testor.module.duty.model.dto.Duty;
import com.testor.module.duty.service.*;
import com.testor.module.isRead.model.domain.TSysIsRead;
import com.testor.module.isRead.service.TSysIsReadService;
import com.testor.module.news.model.domain.SysNews;
import com.testor.module.news.service.SysNewsService;
import com.testor.module.report.dto.*;
import com.testor.module.safe.model.dto.TSafeHazardStandardTypeAllVO;
import com.testor.module.safe.service.TSafeHazardStandardTypeService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component("dutyRecordService")
public class DutyRecordService {
    @Resource
    private DutyService dutyService;
    @Autowired
    private TSysSelectiveService tSysSelectiveService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private TSysDutyLogService tSysDutyLogService;
    @Autowired
    private TSysTaskWorkService tSysTaskWorkService;
    @Autowired
    private TSysIsReadService tSysIsReadService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TSysDutyMonthService tSysDutyMonthService;
    //值班记录下载
    public List<Duty> getRecordDown(String dsName, String datasetName, Map<String, Object> parameters) throws Exception {
        QueryWrapper<TSysDuty> queryWrapper = new QueryWrapper<>();
        String companyids = (String) parameters.get("companyids");
        Object startDate = parameters.get("startDate");
        Object endDate = parameters.get("endDate");
        queryWrapper.orderByDesc("duty_date", "classes");
        queryWrapper.in("company_id", companyids);
        queryWrapper.eq("status", 0);
        queryWrapper.between("duty_date", startDate, endDate);
        List<TSysDuty> list = dutyService.list(queryWrapper);
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Duty> duties = new ArrayList<>();
        list.stream().forEach(item -> {
            Duty duty = BeanHelper.beanToBean(item, Duty.class);
            try {
                cal.setTime(sdf.parse(item.getDutyDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //星期
            duty.setWeek(getWeek(item.getDutyDate()));
            //年
            duty.setYear(Integer.toString(cal.get(Calendar.YEAR)));
            //月
            duty.setMon(Integer.toString(cal.get(Calendar.MONTH) + 1));
            //日
            duty.setDay(Integer.toString(cal.get(Calendar.DATE)));
            TSysDutyMonth one = tSysDutyMonthService.getOne(new QueryWrapper<TSysDutyMonth>().eq("id", item.getRefId()));
            duty.setDutyPattern(one.getDutyPattern());
            duties.add(duty);
        });
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("没数据导出");
        }
        return duties;
    }

    public static String getWeek(String sdate) {
        // 再转换为时间
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Date parseDate = null;
        try {
            parseDate = dateFormat.parse(sdate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(parseDate);
        int week_index = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return weeks[week_index];
    }

    //值班抽查导出
    public List<TSysSelectiveDto> getExportSpot(String dsName, String datasetName, Map<String, Object> parameters) {

        QueryWrapper<TSysSelective> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(TSysSelective.CHECK_TIME);
        queryWrapper.eq(TSysSelective.STATUS, "0");
        //企业 id
        String companyId = parameters.get("companyId").toString();
//        //租户id
//        Object tenantId = parameters.get("tenantId");
        //开始时间
        String startDate = parameters.get("startDate").toString();
        //结束时间
        String endDate = parameters.get("endDate").toString();
        //是否存在问题
        String isIssue = parameters.get("isIssue").toString();
        if (!"".equals(companyId)) {
            queryWrapper.eq(TSysSelective.COMPANY_ID, companyId);
        }
        if (!"".equals(startDate) && !"".equals(endDate)) {
            queryWrapper.between(TSysSelective.CHECK_TIME, startDate + " 00:00:00", endDate + " 23:59:59");
        }
        if (!"".equals(isIssue)) {
            queryWrapper.eq(TSysSelective.IS_ISSUE, isIssue);
        }
        List<TSysSelective> tSysSelectives = tSysSelectiveService.list(queryWrapper);
        List<TSysSelectiveDto> selectiveDtos = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
        tSysSelectives.stream().forEach(item -> {
            TSysSelectiveDto tSysSelectiveDto = BeanHelper.beanToBean(item, TSysSelectiveDto.class);
            LocalDateTime checkTime = DateUtil.dateToLocalDateTime(tSysSelectiveDto.getCheckTime());
            // 抽查人员照片
            String checkPersonPhoto = tSysSelectiveDto.getCheckPersonPhoto();
            // 存在问题照片
            String issuePhoto = tSysSelectiveDto.getIssuePhoto();
            boolean check = checkPersonPhoto.startsWith("http://");
            if (check) {
                String[] split = checkPersonPhoto.split(",");
                if(split.length>=1){
                    checkPersonPhoto = split[0];
                }
                tSysSelectiveDto.setCheckPersonPhoto(checkPersonPhoto);
            }else {
                tSysSelectiveDto.setCheckPersonPhoto("http://"+checkPersonPhoto);
            }
            boolean issue = issuePhoto.startsWith("http://");
            if (issue) {
                String[] iss = issuePhoto.split(",");
                if (iss.length >= 1) {
                    issuePhoto = iss[0];
                }
                tSysSelectiveDto.setIssuePhoto(issuePhoto);
            } else {
                tSysSelectiveDto.setIssuePhoto("http://"+issuePhoto);
            }

            Date dateformat = Date.from(checkTime.atZone(ZoneId.systemDefault()).toInstant());
            String format = sdf.format(dateformat);
            Date date = null;
            try {
                date = sdf.parse(format);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            cal.setTime(date);
            tSysSelectiveDto.setYear(Integer.toString(cal.get(Calendar.YEAR)));
            tSysSelectiveDto.setMonth(Integer.toString(cal.get(Calendar.MONTH)));
            tSysSelectiveDto.setDay(Integer.toString(cal.get(Calendar.DATE)));
            String format1 = sdfTime.format(dateformat);
            tSysSelectiveDto.setTime(format1);
            tSysSelectiveDto.setWeek(getWeek(format));
            selectiveDtos.add(tSysSelectiveDto);
        });
        return selectiveDtos;
    }

    @Autowired
    private SysNewsService sysNewsService;

    //新闻信息汇总
    public List<GetNews> getNews(String dsName, String datasetName, Map<String, Object> parameters) {
        QueryWrapper<SysNews> query = new QueryWrapper<>();
        query.eq("status", "0")
                .eq("process_status", "5");

        Object title = parameters.get("title");
        Object startDate = parameters.get("startTime");
        Object endDate = parameters.get("endTime");
        Object levels = parameters.get("levels");
        String isRead = (String) parameters.get("isRead");
        String loginUserId = (String) parameters.get("loginUserId");

        if (ObjectHelper.isNotEmpty(title)) {
            query.like("title", title);
        }
        if (ObjectHelper.isNotEmpty(startDate) && ObjectHelper.isNotEmpty(endDate)) {
            query.between("release_time", startDate + " 00:00:00", endDate + " 23:59:59");
        }
        if (ObjectHelper.isNotEmpty(levels)) {
            String[] split = ((String) levels).split(",");
            query.in("\"level\"", split);
        }
        query.select("title", "release_unit", "release_time", "id").orderByDesc("release_time");
        List<SysNews> list = sysNewsService.list(query);
        list = returnList(list, isRead, loginUserId);
        List<GetNews> getNews1 = new ArrayList<>();
        list.stream().forEach(item -> {
            GetNews getNews = BeanHelper.beanToBean(item, GetNews.class);
            getNews.setReleaseTime(item.getReleaseTime());
            getNews1.add(getNews);
        });

        return getNews1;
    }

    private List<SysNews> returnList(List<SysNews> list, String isRead, String loginUserId) {
        QueryWrapper<TSysIsRead> wrapper = new QueryWrapper<>();
        List<String> idList = new ArrayList<>();
        list.stream().forEach(item -> {
            String id = item.getId();
            idList.add(id);
        });
        wrapper.in(TSysIsRead.ARTICLE_ID, idList).eq(TSysIsRead.USER_ID, loginUserId);
        List<TSysIsRead> list1 = tSysIsReadService.list(wrapper);
        //==
        list.stream().forEach(p -> {
            p.setIsRead("0");
            list1.stream().forEach(r -> {
                if ((p.getId().equals(r.getArticleId())) && (r.getUserId().equals(loginUserId))) {
                    p.setIsRead(r.getIsRead());
                }
            });
        });
        if ("0".equals(isRead)) {
            list = list.stream().filter(item -> item.getIsRead().equals("0")).collect(Collectors.toList());
        } else if ("1".equals(isRead)) {
            list = list.stream().filter(item -> item.getIsRead().equals("1")).collect(Collectors.toList());
        }

        list = list.stream().sorted(Comparator.comparing(p -> p.getIsRead())).collect(Collectors.toList());
        return list;
    }

    public Date parseDate(LocalDateTime localDateTime) {
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
        Instant instant = zonedDateTime.toInstant();
        Date date = Date.from(instant);
        return date;
    }

    //新闻数量统计
    public List<NewsCount> getNewsCount(String dsName, String datasetName, Map<String, Object> parameters) {
        QueryWrapper<SysNews> query = new QueryWrapper<>();
        query.eq("status", "0")
                .eq("process_status", "5");

        Object title = parameters.get("title");
        Object startDate = parameters.get("startTime");
        Object endDate = parameters.get("endTime");
        Object levels = parameters.get("levels");
        String isRead = (String) parameters.get("isRead");
        String loginUserId = (String) parameters.get("loginUserId");

        if (ObjectHelper.isNotEmpty(title)) {
            query.like("title", title);
        }
        if (ObjectHelper.isNotEmpty(startDate) && ObjectHelper.isNotEmpty(endDate)) {
            query.between("release_time", startDate + " 00:00:00", endDate + " 23:59:59");
        }
        if (ObjectHelper.isNotEmpty(levels)) {
            String[] split = ((String) levels).split(",");
            query.in("\"level\"", split);
        }
        query.select("release_unit", "\"level\"", "release_org_id", "id");
        List<SysNews> list = sysNewsService.list(query);
        list = returnList(list, isRead, loginUserId);
        List<NewsCount> newsCounts = new ArrayList<>();
        Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(SysNews::getReleaseOrgId, Collectors.counting()));
        list.stream().forEach(item -> {
            NewsCount newsCount = BeanHelper.beanToBean(item, NewsCount.class);
            newsCount.setCount(collect.get(item.getReleaseOrgId()));
            newsCounts.add(newsCount);
        });
        HashSet<NewsCount> newsCounts1 = new HashSet<>(newsCounts);
        List<NewsCount> newsCounts2 = new ArrayList<>(newsCounts1);
        return newsCounts2;
    }

    //值班日志批量下载
    public List<ReturnDutyLog> getDownloadDutyLog(String dsName, String datasetName, Map<String, Object> parameters) {
        String id = (String) parameters.get("id");
        TSysDutyLog tSysDutyLog = tSysDutyLogService.getById(id);
        String jobId = tSysDutyLog.getJobId();
        // 日志所对应的多个作业活动id
        List<String> ids = Arrays.asList(jobId.split(","));
        QueryWrapper<TSysTaskWork> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        // 日志所对应的多个作业活动
        List<TSysTaskWork> tSysTaskWorks = tSysTaskWorkService.list(queryWrapper);

        List<ReturnDutyLog> taskworks = new ArrayList<>();
        tSysTaskWorks.stream().forEach(item -> {
            ReturnDutyLog returnDutyLog = BeanHelper.beanToBean(item, ReturnDutyLog.class);
            returnDutyLog.setDutyDate(tSysDutyLog.getDutyDate());
            returnDutyLog.setDutyLeader(tSysDutyLog.getDutyLeader());
            returnDutyLog.setAttentionMatter(tSysDutyLog.getAttentionMatter());
            returnDutyLog.setEmergency(tSysDutyLog.getEmergency());
            returnDutyLog.setDefendName(tSysDutyLog.getDefendName());
            returnDutyLog.setHandoverIssue(tSysDutyLog.getHandoverIssue());
            returnDutyLog.setHandoverSign(tSysDutyLog.getHandoverSign());
            returnDutyLog.setIssueApply(tSysDutyLog.getIssueApply());
            returnDutyLog.setOtherStaffs(tSysDutyLog.getOtherStaffs());
            returnDutyLog.setOtherWork(tSysDutyLog.getOtherWork());
            returnDutyLog.setWeather(tSysDutyLog.getWeather());
            returnDutyLog.setTakeStep(tSysDutyLog.getTakeStep());
            returnDutyLog.setTimeSection(tSysDutyLog.getTimeSection());
            returnDutyLog.setSuccessionSign(tSysDutyLog.getSuccessionSign());
            taskworks.add(returnDutyLog);
        });
        System.out.println(taskworks);

        return taskworks;

    }

    //值班列表 参考文件-企业信息
    public List<SysOrg> dowReferenceModel(String dsName, String datasetName, Map<String, Object> parameters) {
        String orgId = (String) parameters.get("orgId");
//        List<SysOrg> childrenById = sysOrgService.getChildrenById(orgId);
        ArrayList<SysOrg> childrenById = new ArrayList<>();
        SysOrg sysOrg = sysOrgService.getById(orgId);
        childrenById.add(sysOrg);
        return childrenById;
    }

    //值班列表 参考文件-值班人员
    public List<DowDutyPersonModel> dowDutyPersonModel(String dsName, String datasetName, Map<String, Object> parameters) {
        String orgId = (String) parameters.get("orgId");
        // 获取部门
        List<SysOrg> deptList = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, orgId).eq(SysOrg.IS_DEPT, "1")
                .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE));
        List<DowDutyPersonModel> dowDutyPersonModels = new ArrayList<>();
        for (SysOrg sysOrg : deptList) {
            List<SysUser> users = sysUserService.list(new QueryWrapper<SysUser>().eq(SysUser.DEPT_ID, sysOrg.getOrgId()).ne(
                    SysUser.STATUS, BizConstants.STATUS_DELETE
            ));
            for (SysUser user : users) {
                DowDutyPersonModel dowDutyPersonModel = new DowDutyPersonModel();
                dowDutyPersonModel.setId(user.getLoginName());
                dowDutyPersonModel.setOrgName(sysOrg.getOrgName());
                dowDutyPersonModel.setUserName(user.getUserName());
                dowDutyPersonModels.add(dowDutyPersonModel);
            }
        }
        return dowDutyPersonModels;
    }

    //人员资质 参考文件-企业信息
    public List<SysOrg> dowAptitudeCompanyMessage(String dsName, String datasetName, Map<String, Object> parameters) {
        List<SysOrg> orgArrayList = new ArrayList<>();
        Object orgId = parameters.get("orgId");
        SysOrg one = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, orgId));
        orgArrayList.add(one);
        return orgArrayList;
    }

    //人员资质 参考文件-人员信息

    public List<AptitudePersonAndDept> dowAptitudePersonMessage(String dsName, String datasetName, Map<String, Object> parameters) {
        Object orgId = parameters.get("orgId");
        // 获取当前企业下的所有部门
        List<SysOrg> list = sysOrgService.list(new QueryWrapper<SysOrg>()
                .eq(SysOrg.PARENT_ID, orgId)
                .eq(SysOrg.IS_DEPT, "1")
                .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
        );
        List<AptitudePersonAndDept> andDepts = new ArrayList<>();
        for (SysOrg sysOrg : list) {
            // 部门下的人员
            List<SysUser> list1 = sysUserService.list(new QueryWrapper<SysUser>()
                    .eq(SysUser.DEPT_ID, sysOrg.getOrgId())
                    .ne(SysUser.STATUS, BizConstants.STATUS_DELETE)
            );
            AptitudePersonAndDept aptitudePersonAndDept = null;
            for (SysUser sysUser : list1) {
                aptitudePersonAndDept = BeanHelper.beanToBean(sysUser, AptitudePersonAndDept.class);
                aptitudePersonAndDept.setOrgName(sysOrg.getOrgName());
            }
            andDepts.add(aptitudePersonAndDept);
        }
        return andDepts;
    }

    @Autowired
    private SysDictDataController sysDictDataController;
     //人员资质 参考文件-资质类型
    public List<SysDictDataListResponse> DowAptitudeType(String dsName, String datasetName, Map<String, Object> parameters) {
        SysDictDataRequest sysDictDataRequest = new SysDictDataRequest();
        sysDictDataRequest.setDictType("aptitude_type");
        BaseResponse<SysDictDataComplexResponse> sysDictDataComplexResponseBaseResponse = sysDictDataController.listDataByType(sysDictDataRequest);
        List<SysDictDataListResponse> data = sysDictDataComplexResponseBaseResponse.getData().getData();
        return data;
    }
//    public  ReturnDutyTaskWork getDownloadDutyLog(String dsName, String datasetName, Map<String, Object> parameters) {
//        String id = (String) parameters.get("id");
//        TSysDutyLog tSysDutyLog = tSysDutyLogService.getById(id);
//        String jobId = tSysDutyLog.getJobId();
//        // 日志所对应的多个作业活动id
//        List<String> ids = Arrays.asList(jobId.split(","));
//        QueryWrapper<TSysTaskWork> queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("id", ids);
//        // 日志所对应的多个作业活动
//        List<TSysTaskWork> tSysTaskWorks = tSysTaskWorkService.list(queryWrapper);
//
//        ReturnDutyTaskWork returnDutyTaskWork = BeanHelper.beanToBean(tSysDutyLog, ReturnDutyTaskWork.class);
//        returnDutyTaskWork.setTaskWorks(tSysTaskWorks);
//        System.out.println(returnDutyTaskWork.toString());
//        return returnDutyTaskWork ;
//    }
    @Resource
    private SpaceManageService spaceManageService;
    //视频监控  参照文件-作业区域统计
    public List<TSafeSpaceVO> videoJobAccount(String dsName, String datasetName, Map<String, Object> parameters) {
        Object orgId = parameters.get("orgId");
        TSafeSpaceDTOParam tSafeSpaceDTOParam = new TSafeSpaceDTOParam();
        tSafeSpaceDTOParam.setLevel(2);
        List<String> orgIds = new ArrayList<>();
        orgIds.add(orgId.toString());
        tSafeSpaceDTOParam.setCondOrgIdList(orgIds);
        List<TSafeSpaceVO> data = spaceManageService.listByPage(tSafeSpaceDTOParam).getData();
        return data;
    }

    @Autowired
    private TSafeHazardStandardTypeService tSafeHazardStandardTypeService;
    // 巡检排查标准  参考文件-标准分类
    public List<SafehazardStandard> JsafeHazardStandardType(String dsName, String datasetName, Map<String, Object> parameters) {
        List<TSafeHazardStandardTypeAllVO> data = tSafeHazardStandardTypeService.listAll().getData();
        ArrayList<SafehazardStandard> standardArrayList = new ArrayList<>();
        for (TSafeHazardStandardTypeAllVO item : data) {
            List<TSafeHazardStandardTypeAllVO> typeAllVOList = item.getTypeAllVOList();
            if (typeAllVOList.size() > 0 && ObjectHelper.isNotEmpty(typeAllVOList)) {
                for (TSafeHazardStandardTypeAllVO typeAllVO : typeAllVOList) {
                    SafehazardStandard safehazardStandard = new SafehazardStandard();
                    if (StringHelper.isNotEmpty(typeAllVO.getParentName())) {
                        safehazardStandard.setStairClassify(item.getName()+"排查标准");
                        safehazardStandard.setSecondClassify(typeAllVO.getParentName()+"排查标准");
                        safehazardStandard.setTertiaryClassify(typeAllVO.getName()+"排查标准");
                    }else{
                        safehazardStandard.setStairClassify(item.getName()+"排查标准");
                        safehazardStandard.setSecondClassify(typeAllVO.getName()+"排查标准");
                    }
                    standardArrayList.add(safehazardStandard);
                }
            }else{
                SafehazardStandard safehazardStandard = new SafehazardStandard();
                safehazardStandard.setStairClassify(item.getName()+"排查标准");
                standardArrayList.add(safehazardStandard);
            }
        }
        List<SafehazardStandard> collect = standardArrayList.stream()
                .sorted(Comparator.comparing(SafehazardStandard::getStairClassify)
                        .thenComparing(SafehazardStandard::getSecondClassify).reversed()).collect(Collectors.toList());
        return collect ;
    }
}
