package com.zehong.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.zehong.common.utils.StringUtils;
import com.zehong.system.domain.TInspectStatisticsInfo;
import com.zehong.system.domain.TTaskInspect;
import com.zehong.system.mapper.TInspectStatisticsInfoMapper;
import com.zehong.system.mapper.TTaskInspectMapper;
import com.zehong.system.service.ITStatisticsInspectItemService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务检查项统计
 */
@Service
public class TStatisticsInspectItemServiceImpl implements ITStatisticsInspectItemService {

    @Resource
    private TTaskInspectMapper tTaskInspectMapper;

    @Resource
    private TInspectStatisticsInfoMapper inspectStatisticsInfoMapper;

    /**
     * 任务检查项统计
     * @param inspectStatisticsInfo 查询条件
     * @return
     */
    @Override
    public List<TInspectStatisticsInfo> statisticsInspectItems(TInspectStatisticsInfo inspectStatisticsInfo) {
        return inspectStatisticsInfoMapper.statisticsInspectInfoByCondition(inspectStatisticsInfo);
    }

    /**
     * 安检项统计
     * @param inspectList 安检单信息
     * @param statisticsMainInfo 统计结果
     * @return List<TInspectStatisticsInfo> 统计信息
     */
    private List<TInspectStatisticsInfo> inspectItemStatistics( List<TTaskInspect> inspectList,TInspectStatisticsInfo statisticsMainInfo){
        Map<String,TInspectStatisticsInfo> inspectItemStatistics = new LinkedHashMap<>();
        for(TTaskInspect inspect : inspectList){
            String contentStr = inspect.getContent();
            JSONObject contentJson = JSON.parseObject(contentStr, Feature.OrderedField);
            if(StringUtils.isNotEmpty(contentStr)){
                JSONObject inspectObj = contentJson.getJSONObject("obj");
                int sort = 0;
                for(String key : inspectObj.keySet()){
                    if("xiangyonghuxuanchuanjuminranqiyonghuyongqixuzhi".equals(key) || "ninduibencifuwuzhiliangpingjia".equals(key) || "yonghuyukaihurenguanxiguanxi".equals(key)) continue;
                    JSONArray inspectItemArray = inspectObj.getJSONObject(key).getJSONArray("range");
                    JSONArray checkItemArray = inspectObj.getJSONObject(key).getJSONArray("valueArr2");
                    for(int i = 0; i < inspectItemArray.size(); i++){
                        sort++;
                        JSONObject item = inspectItemArray.getJSONObject(i);
                        String itemName = item.getString("text");
                        Boolean disable = (Boolean) checkItemArray.get((int)item.get("value"));
                        if (null == disable) continue;
                        //统计对象初始化
                        TInspectStatisticsInfo statisticsInfo = BeanUtil.copyProperties(statisticsMainInfo,TInspectStatisticsInfo.class);
                        statisticsInfo.setTaskType(inspect.getTaskType());
                        statisticsInfo.setCreateTime(removeTime(inspect.getCreateTime()));
                        statisticsInfo.setName(itemName);
                        statisticsInfo.setNameHashCode(itemName.hashCode());
                        statisticsInfo.setSort(sort);
                        if(inspectItemStatistics.containsKey(itemName)){
                            if(disable){
                                TInspectStatisticsInfo inspectItemStatisticsInfo = inspectItemStatistics.get(itemName);
                                Integer num = inspectItemStatisticsInfo.getDangerNum();
                                inspectItemStatisticsInfo.setDangerNum(++num);
                            }
                        }else {
                            if(disable){
                                statisticsInfo.setDangerNum(1);
                                inspectItemStatistics.put(itemName,statisticsInfo);
                            }else{
                                statisticsInfo.setDangerNum(0);
                                inspectItemStatistics.put(itemName,statisticsInfo);
                            }
                        }
                    }
                }
            }
        }
        return new ArrayList<>(inspectItemStatistics.values());
    }


    /**
     * 根据日期手动统计
     * @param dateBegin 开始时间
     * @param dateEnd 结束时间
     */
    @Override
    public void statisticsResidentInspectItemByHand(String dateBegin,String dateEnd){
        Map<String,Object> params = new HashMap<>();
        params.put("type",1);
        params.put("dateBegin",dateBegin);
        params.put("dateEnd",dateEnd);
        List<TTaskInspect> inspectList = tTaskInspectMapper.selectResidentInspectItemStatistics(params);
        // 定义日期格式化器
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Map<String, List<TTaskInspect>>> inspectListGroupByTaskTypeAndCreateTime = inspectList.stream()
                .collect(
                        Collectors.groupingBy(inspect -> Optional.ofNullable(inspect.getTaskType()).orElse("defaultKey"),
                                Collectors.groupingBy(inspect -> format.format(inspect.getCreateTime()))
                        )
                );
        for(Map<String, List<TTaskInspect>> taskInspectGroupByTaskTypeList : inspectListGroupByTaskTypeAndCreateTime.values()){
            for(List<TTaskInspect> taskInspectList : taskInspectGroupByTaskTypeList.values()){
                insertInspectItemStatistics(taskInspectList);
            }
        }
    }

    /**
     * 定时统计昨天居民安检项
     */
    @Override
    public void statisticsYesterdayResidentInspectItem(){
        Date yesterday = DateUtil.yesterday();
        Date beginOfDay = DateUtil.beginOfDay(yesterday);
        Date endOfDay = DateUtil.endOfDay(yesterday);
        Map<String,Object> params = new HashMap<>();
        params.put("type",1);
        params.put("dateBegin",DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss"));
        params.put("dateEnd",DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss"));
        List<TTaskInspect> inspectList = tTaskInspectMapper.selectResidentInspectItemStatistics(params);
        Map<String,List<TTaskInspect>> inspectListGroupByTaskType = inspectList.stream().collect(Collectors.groupingBy(inspect -> Optional.ofNullable(inspect.getTaskType()).orElse("defaultKey")));
        for(List<TTaskInspect> taskInspectList : inspectListGroupByTaskType.values()){
            insertInspectItemStatistics(taskInspectList);
        }
    }

    /**
     * 持久化安检项
     * @param taskInspectList 安检信息
     */
    private void insertInspectItemStatistics(List<TTaskInspect> taskInspectList){

        TInspectStatisticsInfo statisticsInfo = new TInspectStatisticsInfo();
        //安检居民
        List<TTaskInspect> inspectResident = taskInspectList.stream()
                .collect(Collectors.groupingBy(
                        TTaskInspect::getReceiveId,
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparingInt(
                                        inspect -> null != inspect.getDanger() ? inspect.getDanger() : Integer.MIN_VALUE
                                )),
                                Optional::get
                        )
                ))
                .values()
                .stream()
                .collect(Collectors.toList());
        //存在隐患居民
        List<TTaskInspect> inspectDangerResident = inspectResident.stream().filter(item -> null != item.getDanger() && 1 == item.getDanger()).collect(Collectors.toList());
        statisticsInfo.setInspectNum(taskInspectList.size());
        statisticsInfo.setUserNum(inspectResident.size());
        statisticsInfo.setUserDangerNum(inspectDangerResident.size());
        //安检项统计
        List<TInspectStatisticsInfo> statisticsInfoList = inspectItemStatistics(taskInspectList,statisticsInfo);
        if(!CollectionUtils.isEmpty(statisticsInfoList)){
            inspectStatisticsInfoMapper.batchInsertTInspectStatisticsInfo(statisticsInfoList);
        }
    }

    /**
     * 时间类型转换
     * @param date 时间
     * @return
     */
    private Date removeTime(Date date) {
        if (date == null) {
            return null;
        }
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = dateFormat.format(date);
            return dateFormat.parse(dateStr);
        } catch (ParseException e) {
            return date;
        }
    }

}
