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

import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.CheckItemDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.dal.page.InspectionItemPlanQueryInfo;
import com.ym.mec.biz.service.SysConfigService;
import com.ym.mec.biz.service.SysMessageService;
import com.ym.mec.biz.service.SysTenantConfigService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
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.service.InspectionItemPlanService;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class InspectionItemPlanServiceImpl extends BaseServiceImpl<Long, InspectionItemPlan> implements InspectionItemPlanService {

    @Autowired
    private InspectionItemPlanDao inspectionItemPlanDao;
    @Autowired
    private InspectionItemDao inspectionItemDao;
    @Autowired
    private InspectionDao inspectionDao;
    @Autowired
    private MusicGroupDao musicGroupDao;
    @Autowired
    private InspectionItemPlanConclusionDao inspectionItemPlanConclusionDao;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private SchoolDao schoolDao;
    @Autowired
    private SysTenantConfigService sysTenantConfigService;

    @Override
    public BaseDAO<Long, InspectionItemPlan> getDAO() {
        return inspectionItemPlanDao;
    }


    @Override
    public PageInfo<InspectionItemPlan> getPageList(InspectionItemPlanQueryInfo queryInfo) {
        PageInfo<InspectionItemPlan> pageInfo = this.queryPage(queryInfo);
        if (pageInfo.getRows().size() > 0) {
            Integer tenantId = TenantContextHolder.getTenantId();
            //签到GPS范围
            String gpsRange = sysTenantConfigService.getTenantConfigValue(SysConfigService.ATTENDANCE_RANGE,tenantId);
            Integer attendanceRange = 0;
            if(StringUtils.isNotEmpty(gpsRange)){
                attendanceRange = Integer.parseInt(gpsRange);
            }
            List<Long> planIds = pageInfo.getRows().stream().map(InspectionItemPlan::getId).collect(Collectors.toList());
            List<CheckItemDto> lastCheckItems = inspectionItemPlanConclusionDao.getLastCheckItem(planIds);
            for (InspectionItemPlan row : pageInfo.getRows()) {
                row.setAttendanceRange(attendanceRange);
                for (CheckItemDto lastCheckItem : lastCheckItems) {
                    if (!lastCheckItem.getPlanId().equals(row.getId())) continue;
                    row.setLastCheckItem(lastCheckItem.getCheckItem());
                }
            }
        }
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InspectionItemPlan add(InspectionItemPlan inspectionItemPlan) {
        InspectionItem inspectionItem = inspectionItemDao.get(inspectionItemPlan.getItemId());
        if (inspectionItem == null) {
            throw new BizException("任务项不存在");
        }
        if (!inspectionItem.getUserId().equals(inspectionItemPlan.getUserId())) {
            throw new BizException("请勿非法操作他人日程");
        }
        Date nowDate = new Date();
        Inspection inspection = inspectionDao.get(inspectionItem.getInspectionId());
        if (inspection.getMonth().after(inspectionItemPlan.getPlanStart())) {
            throw new BizException("日程时间不能早于工作周期开始时间");
        }
        if (nowDate.after(inspectionItemPlan.getPlanStart())) {
            throw new BizException("日程时间不能早于当前时间");
        }
        Date itemEndTime = DateUtil.getLastTimeWithDay(DateUtil.getLastDayOfMonth(inspection.getMonth()));
        if (itemEndTime.before(inspectionItemPlan.getPlanEnd())) {
            throw new BizException("日程时间不能晚于工作周期结束时间");
        }
        //事项计划同一乐团同一天不能重复
        Date dayStartTime = DateUtil.trunc(inspectionItemPlan.getPlanStart());
        Date dayEndTime = DateUtil.trunc(inspectionItemPlan.getPlanStart());
        int dayMusicGroupItemPlanCount = inspectionItemPlanDao.getMusicGroupItemPlanCount(inspectionItemPlan.getItemId(),
                inspectionItemPlan.getMusicGroupId(), dayStartTime, dayEndTime, null);
        if (dayMusicGroupItemPlanCount > 0) {
            throw new BizException("该乐团当天已有巡查安排,请核查");
        }
        //获取乐团教学点的GPS信息
        MusicGroup musicGroup = musicGroupDao.get(inspectionItemPlan.getMusicGroupId());
        School school = schoolDao.get(musicGroup.getSchoolId());

        inspectionItemPlan.setOrganId(inspectionItem.getOrganId());
        inspectionItemPlan.setCooperationOrganId(musicGroup.getCooperationOrganId());
        inspectionItemPlan.setInspectionId(inspectionItem.getInspectionId());
        inspectionItemPlan.setSchoolGps(school.getLongitudeLatitude());
        inspectionItemPlan.setSubmitedGps("");
        inspectionItemPlan.setMemo("");
        inspectionItemPlan.setStatus(0);
        inspectionItemPlan.setConclusionStatus(0);
        inspectionItemPlan.setCreateTime(nowDate);
        inspectionItemPlan.setUpdateTime(nowDate);
        inspectionItemPlanDao.insert(inspectionItemPlan);
        inspectionItem.setPlannedTimes(inspectionItem.getPlannedTimes() + 1);
        inspectionItemDao.update(inspectionItem);
        return inspectionItemPlan;
    }

    @Override
    public InspectionItemPlan updatePlan(InspectionItemPlan inspectionItemPlan) {
        InspectionItemPlan oldPlan = inspectionItemPlanDao.get(inspectionItemPlan.getId());
        if (oldPlan.getStatus() > 0) {
            throw new BizException("日程已完成，不能修改");
        }
        InspectionItem inspectionItem = inspectionItemDao.get(inspectionItemPlan.getItemId());
        if (inspectionItem == null) {
            throw new BizException("任务项不存在");
        }
        if (!inspectionItem.getUserId().equals(inspectionItemPlan.getUserId())) {
            throw new BizException("请勿非法操作他人日程");
        }
        Date nowDate = new Date();
        Inspection inspection = inspectionDao.get(inspectionItem.getInspectionId());
        if (inspection.getMonth().after(inspectionItemPlan.getPlanStart())) {
            throw new BizException("日程时间不能早于工作周期开始时间");
        }
        if (nowDate.after(inspectionItemPlan.getPlanStart())) {
            throw new BizException("日程时间不能早于当前时间");
        }
        Date itemEndTime = DateUtil.getLastTimeWithDay(DateUtil.getLastDayOfMonth(inspection.getMonth()));
        if (itemEndTime.before(inspectionItemPlan.getPlanEnd())) {
            throw new BizException("日程时间不能晚于工作周期结束时间");
        }
        //事项计划同一乐团同一天不能重复
        Date dayStartTime = DateUtil.trunc(inspectionItemPlan.getPlanStart());
        Date dayEndTime = DateUtil.trunc(inspectionItemPlan.getPlanStart());
        int dayMusicGroupItemPlanCount = inspectionItemPlanDao.getMusicGroupItemPlanCount(inspectionItemPlan.getItemId(),
                inspectionItemPlan.getMusicGroupId(), dayStartTime, dayEndTime, inspectionItemPlan.getId());
        if (dayMusicGroupItemPlanCount > 0) {
            throw new BizException("该乐团当天已有巡查安排,请核查");
        }
        //获取乐团教学点的GPS信息
        if (oldPlan.getStatus().equals(0)) { //未提交的修改
            //获取乐团教学点的GPS信息
            MusicGroup musicGroup = musicGroupDao.get(inspectionItemPlan.getMusicGroupId());
            School school = schoolDao.get(musicGroup.getSchoolId());
            inspectionItemPlan.setInspectionId(inspectionItem.getInspectionId());
            inspectionItemPlan.setCooperationOrganId(musicGroup.getCooperationOrganId());
            inspectionItemPlan.setSchoolGps(school.getLongitudeLatitude());
            inspectionItemPlan.setSubmitedGps("");
            inspectionItemPlan.setMemo("");
            inspectionItemPlan.setStatus(0);
        }
        inspectionItemPlan.setUpdateTime(nowDate);
        inspectionItemPlanDao.update(inspectionItemPlan);
        return inspectionItemPlan;
    }

    @Override
    public List<InspectionItemPlan> pushNotice() {
        Date nowDate = new Date();
        Date startTime = DateUtil.trunc(nowDate);
        Date endTime = DateUtil.getLastTimeWithDay(nowDate);
        List<InspectionItemPlan> startPlans = inspectionItemPlanDao.getStartPlan(startTime, endTime);
        Set<Integer> userIds = startPlans.stream().map(InspectionItemPlan::getUserId).collect(Collectors.toSet());
        //发送推送信息
        Map<Integer, String> userMap = new HashMap<>();
        for (Integer userId : userIds) {
            userMap.put(userId, userId.toString());
        }

        String baseApiUrl = sysConfigDao.findConfigValue(SysConfigService.EDU_TEACHER_BASE_URL);
        String pushUrl = baseApiUrl + "/#/musicInspection";
        sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.SYSTEM_PUSH_SMS_INSPECTION_NOTICE,
                userMap, null, 0, "8?" + pushUrl, "SYSTEM");
        return startPlans;
    }
}


