package com.ym.mec.biz.service.impl;

import com.ym.mec.biz.dal.dao.CourseScheduleDao;
import com.ym.mec.biz.dal.dao.InspectionItemDao;
import com.ym.mec.biz.dal.dao.InspectionItemPlanConclusionDao;
import com.ym.mec.biz.dal.dao.InspectionItemPlanDao;
import com.ym.mec.biz.dal.dto.InspectionItemPlanConclusionDto;
import com.ym.mec.biz.dal.entity.CourseSchedule;
import com.ym.mec.biz.dal.entity.InspectionItem;
import com.ym.mec.biz.dal.entity.InspectionItemPlan;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ym.mec.biz.dal.entity.InspectionItemPlanConclusion;
import com.ym.mec.biz.service.InspectionItemPlanConclusionService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class InspectionItemPlanConclusionServiceImpl extends BaseServiceImpl<Long, InspectionItemPlanConclusion> implements InspectionItemPlanConclusionService {

    @Autowired
    private InspectionItemPlanConclusionDao inspectionItemPlanConclusionDao;
    @Autowired
    private InspectionItemPlanDao inspectionItemPlanDao;
    @Autowired
    private InspectionItemDao inspectionItemDao;
    @Autowired
    private CourseScheduleDao courseScheduleDao;

    @Override
    public BaseDAO<Long, InspectionItemPlanConclusion> getDAO() {
        return inspectionItemPlanConclusionDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InspectionItemPlanConclusionDto add(InspectionItemPlanConclusionDto inspectionItemPlanConclusionDto) {
        Date nowDate = new Date();
        List<InspectionItemPlanConclusion> inspectionItemPlanConclusions = inspectionItemPlanConclusionDto.getInspectionItemPlanConclusions();
        if(CollectionUtils.isEmpty(inspectionItemPlanConclusions)){
            throw new BizException("请填写答案");
        }
        if(inspectionItemPlanConclusions.stream().anyMatch(e -> StringUtils.isEmpty(e.getCheckConclusion()) && !StringUtils.equals(e.getQuestionType(),"radio"))){
            throw new BizException("请填写所有答案");
        }
        //删除老的
        Long planId = inspectionItemPlanConclusions.get(0).getPlanId();
        Integer checkItem = inspectionItemPlanConclusions.get(0).getCheckItem();
        //时间早于/晚于计划时间当天，不能提交
        InspectionItemPlan inspectionItemPlan = inspectionItemPlanDao.get(planId);
        if (nowDate.before(DateUtil.trunc(inspectionItemPlan.getPlanStart()))) {
            throw new BizException("提交时间不能早于日程安排当天");
        }

        if (nowDate.after(DateUtil.getLastTimeWithDay(inspectionItemPlan.getPlanStart()))) {
            throw new BizException("提交时间不能晚于日程安排当天");
        }

        inspectionItemPlanConclusionDao.delByPlanIdAndCheckItem(planId, checkItem);
        for (InspectionItemPlanConclusion inspectionItemPlanConclusion : inspectionItemPlanConclusions) {
            inspectionItemPlanConclusion.setCreateTime(nowDate);
            inspectionItemPlanConclusion.setUpdateTime(nowDate);
        }
        inspectionItemPlanConclusionDto.setInspectionItemPlanConclusions(inspectionItemPlanConclusions);
        //插入新的
        inspectionItemPlanConclusionDao.batchAdd(inspectionItemPlanConclusions);
        //有状态信息,更新gps信息和提交状态
        if (inspectionItemPlanConclusionDto.getStatus() == null) {
            return inspectionItemPlanConclusionDto;
        }
        //获取巡查结果的异常数量
        int eConclusionNum = inspectionItemPlanConclusionDao.getCountByPlanIdAndCheckConclusion(planId, 0);
        inspectionItemPlan.setConclusionStatus(0);

        //未提交过，更新提交信息
        if (inspectionItemPlan.getStatus().equals(0)) {
            inspectionItemPlan.setSubmitedGps(inspectionItemPlanConclusionDto.getSubmitedGps());
            inspectionItemPlan.setSubmitedTime(nowDate);
            inspectionItemPlan.setStatus(inspectionItemPlanConclusionDto.getStatus());
            inspectionItemPlan.setUpdateTime(nowDate);
            if (eConclusionNum > 0) {
                inspectionItemPlan.setConclusionStatus(1);
            }
            inspectionItemPlanDao.update(inspectionItemPlan);
            //更新提交次数
            InspectionItem inspectionItem = inspectionItemDao.get(inspectionItemPlan.getItemId());
            inspectionItem.setSubmittedTimes(inspectionItem.getSubmittedTimes() + 1);
            inspectionItem.setUpdateTime(nowDate);
            inspectionItemDao.update(inspectionItem);
            return inspectionItemPlanConclusionDto;
        }

        //提交过，异常变正常，更新提交信息
        if (inspectionItemPlanConclusionDto.getStatus().equals(1)) {
            inspectionItemPlan.setSubmitedGps(inspectionItemPlanConclusionDto.getSubmitedGps());
            inspectionItemPlan.setSubmitedTime(nowDate);
            inspectionItemPlan.setStatus(inspectionItemPlanConclusionDto.getStatus());
        }
        if (eConclusionNum > 0) {
            inspectionItemPlan.setConclusionStatus(1);
        }
        inspectionItemPlan.setUpdateTime(nowDate);
        inspectionItemPlanDao.update(inspectionItemPlan);
        return inspectionItemPlanConclusionDto;
    }

    @Override
    public Map<Integer, List<InspectionItemPlanConclusion>> getInfo(Long planId, Integer checkItem) {
        List<InspectionItemPlanConclusion> conclusions = inspectionItemPlanConclusionDao.getInspectionItemPlanConclusion(planId, checkItem);
        return conclusions.stream().collect(Collectors.groupingBy(InspectionItemPlanConclusion::getCheckItem));
    }

    @Override
    public List<CourseSchedule> getPlanCourses(Long planId) {
        InspectionItemPlan plan = inspectionItemPlanDao.get(planId);
        List<CourseSchedule> courseSchedules = new ArrayList<>();
        if (plan == null) {
            return courseSchedules;
        }
        courseSchedules = inspectionItemPlanConclusionDao.getPlanConclusionCourses(planId);
        if (courseSchedules.size() > 0) {
            return courseSchedules;
        }
        courseSchedules = courseScheduleDao.getMusicGroupCourseInfo(plan.getMusicGroupId(), DateUtil.trunc(plan.getPlanStart()), DateUtil.getLastTimeWithDay(plan.getPlanStart()));
        return courseSchedules;
    }

    @Override
    public List<Map<String, String>> getPlanConclusion(Long planId) {
        List<InspectionItemPlanConclusion> conclusions = inspectionItemPlanConclusionDao.getInspectionItemPlanConclusion(planId, null);
        Map<Long, List<InspectionItemPlanConclusion>> courseConclusions = conclusions.stream().collect(Collectors.groupingBy(InspectionItemPlanConclusion::getCourseScheduleId));
        List<Map<String, String>> conclusionMaps = new ArrayList<>();
        courseConclusions.forEach((courseId, inspectionItemPlanConclusions) -> {
            Map<String, String> conclusionMap = new LinkedHashMap<>();
            for (InspectionItemPlanConclusion conclusion : inspectionItemPlanConclusions) {
                if (!conclusionMap.containsKey("name")) {
                    conclusionMap.put("name", conclusion.getClassInfo());
                }
                conclusionMap.put(conclusion.getCheckItem().toString(), conclusion.getCheckConclusion());
            }
            conclusionMaps.add(conclusionMap);
        });
        return conclusionMaps;
    }
}



