package com.casic.missiles.modular.alarm.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.application.context.AbstractPermissionContext;
import com.casic.missiles.core.datascope.DataScope;
import com.casic.missiles.core.util.EhcacheConstant;
import com.casic.missiles.modular.alarm.job.DelayJob;
import com.casic.missiles.modular.alarm.model.JobListParam;
import com.casic.missiles.modular.alarm.service.IAlarmJobService;
import com.casic.missiles.modular.system.dao.AlarmJobMapper;
import com.casic.missiles.modular.system.dto.UserClientView;
import com.casic.missiles.modular.system.model.AlarmJob;
import com.casic.missiles.modular.system.service.IBusWellInfoSupportService;
import com.casic.missiles.modular.system.util.WebSocket;
import com.casic.missiles.quartz.service.IQuartzManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 报警工单表 服务实现类
 * </p>
 *
 * @author casic123
 * @since 2019-05-17
 */
@Service
@Slf4j
public class AlarmJobServiceImpl extends ServiceImpl<AlarmJobMapper, AlarmJob> implements IAlarmJobService {

    @Value("${smartcity.leaderRoleName}")
    private String sLeader;
    @Value("${smartcity.memberRoleName}")
    private String sMember;
    @Value("${smartcity.appRoleName}")
    private String sApp;
    @Value("${smartcity.useOverTime}")
    private String useOverTime;

    @Resource
    private AbstractPermissionContext iCommonUserService;
    @Resource
    private IQuartzManager quartzManager;
    @Resource
    private WebSocket webSocket;

    @Override
    public List<Map<String, Object>> jobList(Page<Map<String, Object>> page, String keywords, String beginTime, String endTime, String jobStatus, String alarmType, String alarmContent, DataScope dataScope, Long userId,String deptid) {
        alarmContent = converAlarmContent(alarmContent);
        Long deptId= StringUtils.isNotEmpty(deptid)?Long.valueOf(deptid):-1;
        List<Map<String, Object>> alarmJobList = this.baseMapper.jobList(page, keywords, beginTime, endTime, jobStatus, alarmType, alarmContent, dataScope, userId,deptId);
        return alarmJobList;
    }

    @Override
    public List<Map<String, Object>> jobListApp(Page<Map<String, Object>> page, String keywords, String beginTime, String endTime, String jobStatus, String alarmType, String alarmContent, Long deptId, Long userId, Long leaderId) {
        alarmContent = converAlarmContent(alarmContent);
        List<Map<String, Object>> alarmJobList = this.baseMapper.jobListApp(page, keywords, beginTime, endTime, jobStatus, alarmType, alarmContent, deptId, userId, leaderId);
        return alarmJobList;
    }

    @Override
    public List<Map<String, Object>> jobListDelayRe(Page<Map<String, Object>> page, String keywords, String beginTime, String endTime, String alarmType, String alarmContent, DataScope dataScope, Long userId,String deptId) {
        alarmContent = converAlarmContent(alarmContent);
        Long deptid =StringUtils.isNotEmpty(deptId)?Long.valueOf(deptId):-1;
        List<Map<String, Object>> alarmJobList = this.baseMapper.jobListDelayRe(page, keywords, beginTime, endTime, alarmType, alarmContent, dataScope, userId,deptid);
        return alarmJobList;
    }

    @Override
    public List<Map<String, Object>> jobListDelayReApp(Page<Map<String, Object>> page, String keywords, String beginTime, String endTime, String alarmType, String alarmContent, Long deptId, Long userId, Long leaderId) {
        alarmContent = converAlarmContent(alarmContent);

        List<Map<String, Object>> alarmJobList = this.baseMapper.jobListDelayReApp(page, keywords, beginTime, endTime, alarmType, alarmContent, deptId, userId, leaderId);
        return alarmJobList;
    }

    @Override
    public List<Map<String, Object>> jobListDelayPro(Page<Map<String, Object>> page, String keywords, String beginTime, String endTime, String alarmType, String alarmContent, DataScope dataScope, Long userId,String deptId) {
        alarmContent = converAlarmContent(alarmContent);
        Long deptid= StringUtils.isNotEmpty(deptId)?Long.valueOf(deptId):-1;
        List<Map<String, Object>> alarmJobList = this.baseMapper.jobListDelayPro(page, keywords, beginTime, endTime, alarmType, alarmContent, dataScope, userId,deptid);
        return alarmJobList;
    }

    @Override
    public List<Map<String, Object>> jobListDelayProApp(Page<Map<String, Object>> page, String keywords, String beginTime, String endTime, String alarmType, String alarmContent, Long deptId, Long userId, Long leaderId) {
        alarmContent = converAlarmContent(alarmContent);
        List<Map<String, Object>> alarmJobList = this.baseMapper.jobListDelayProApp(page, keywords, beginTime, endTime, alarmType, alarmContent, deptId, userId, leaderId);
        return alarmJobList;
    }

    @Override
    public List<Map<String, Object>> jobListSearch(Page<Map<String, Object>> page, JobListParam jobListParam, DataScope dataScope, Long userId) {
        jobListParam.setAlarmContent(converAlarmContent(jobListParam.getAlarmContent()));
        List<Map<String, Object>> alarmJobList = this.baseMapper.jobListSearch(page, jobListParam, dataScope, userId);
        return alarmJobList;
    }

    @Override
    public List<Map<String, Object>> jobListSearchApp(Page<Map<String, Object>> page, JobListParam jobListParam, Long deptId, Long userId, Long leaderId) {
        jobListParam.setAlarmContent(converAlarmContent(jobListParam.getAlarmContent()));
        List<Map<String, Object>> alarmJobList = this.baseMapper.jobListSearchApp(page, jobListParam.getKeywords(),
                jobListParam.getAlarmLevel(), jobListParam.getAlarmContent(), jobListParam.getJobStatus(), jobListParam.getBeginTime(),
                jobListParam.getEndTime(), jobListParam.getGetJobBeginTime(), jobListParam.getGetJobEndTime(), jobListParam.getShouldGetBeginTime(),
                jobListParam.getShouldGetEndTime(), jobListParam.getHandleJobBeginTime(), jobListParam.getHandleJobEndTime(), jobListParam.getShouldHandleBeginTime(),
                jobListParam.getShouldHandleEndTime(), deptId, userId, leaderId);
        return alarmJobList;
    }

    private String converAlarmContent(String alarmContent) {
        if (StrUtil.isEmpty(alarmContent)) {
            return alarmContent;
        } else {
            return EhcacheConstant.retBean().getAlarmContentName(Integer.valueOf(alarmContent));
        }
    }

    @Override
    public List<Map<String, Object>> jobInfo(Long id, DataScope dataScope, Long personId) {
        List<Map<String, Object>> jobList = this.baseMapper.jobInfo(id,personId);
        jobList.forEach(job -> job.put("editable", job.get("jobBelongTo") != null && job.get("jobBelongTo").toString().equals(personId) ? 1 : 0));
        return jobList;
    }

    @Override
    public Map<String, Object> countByJobStatus(long deptId, int spanDays) {
        return this.baseMapper.countByJobStatus(deptId, spanDays);
    }

    @Override
    public Map<String, Object> countMyJob(long userId, long deptId, int spanDays) {
        return this.baseMapper.countMyJob(userId, deptId, spanDays);
    }

    private boolean isWeekend(Calendar cal) {
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean confirmJob(Long id, long personId, String firstState, String firstStatePhotos, String needHandle) {
        if ("1".equals(needHandle)) {
            return this.baseMapper.confirmJob(id, personId, firstState, firstStatePhotos, needHandle);
        } else {
            return this.baseMapper.confirmOverJobAndAlarm(id, personId, firstState, firstStatePhotos) && this.baseMapper.confirmOverAlarmRecords(id);
        }
    }

    @Override
    public boolean transferJob(Long id, long transferPerson, String flowRec) {
        return this.baseMapper.transferJob(id, transferPerson, flowRec);
    }

    @Override
    public boolean saveJob(Long id, String handleMessage, String handlePhotos) {
        return this.baseMapper.saveJob(id, handleMessage, handlePhotos);
    }

    @Override
    public boolean overJob(Long id, long personId, String handleMessage, String handlePhotos) {
        return this.baseMapper.overJob(id, personId, handleMessage, handlePhotos) && this.baseMapper.overJobAlarmRecrds(id);
    }

    @Override
    public boolean overAlarm(Long jobId) {
        return this.baseMapper.overAlarm(jobId);
//        return this.baseMapper.overJob(id, personId,handleMessage, handlePhotos);
    }

    public static void main(String [] args) {
        Calendar now = Calendar.getInstance();
        Date getTime = now.getTime();
        now.add(Calendar.WEEK_OF_YEAR, 1);
        now.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        now.set(Calendar.HOUR_OF_DAY, 10);//默认8点上班
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
    }

    @Override
    public boolean handleJob(Long id, long personId) {
        return this.baseMapper.handleJob(id, personId);
    }

    @Override
    public boolean checkJobStatus(String jobStatus) {
        if (StrUtil.isEmpty(jobStatus)) {
            return false;
        } else {
            return "1".equals(jobStatus) || "2".equals(jobStatus) || "3".equals(jobStatus);
        }
    }

    @Override
    public List<UserClientView> selectUserByWellCode(String wellCode) {
        return this.baseMapper.selectUserByWellCode(wellCode);
    }


    @Override
    public boolean checkPcRole(Set<String> roleTips) {
        List<String> roleList = new ArrayList<>(roleTips);
        Iterator<String> it = roleList.iterator();
        while (it.hasNext()) {
            String role = it.next();
            if (role.equals(sApp) || role.equals(sLeader) || role.equals(sMember)) {
                it.remove();
            }
        }
        return roleList.size() > 0;
    }

    @Override
    public Integer countByDataScope(DataScope dataScope, String alarmType, String jobStatus, String beginTime, String endTime) {
//        try {
//            Date startTime = timeFormat.parse(beginTime);
//            Date lastTime = timeFormat.parse(endTime);
        List<Map<String, Object>> res = this.baseMapper.countByDataScope(dataScope, alarmType, jobStatus, beginTime, endTime);
        return res.size();
//
//        } catch (ParseException ex) {
//            log.error("主题：日期格式转换出错，开始日期{}，结束日期{}，异常信息{}",beginTime,endTime,ex);
//        }
//        return null;
    }

    @Override
    public Integer countByResponse(String alarmType, String jobStatus, Long deptId, String beginTime, String endTime) {
        return this.baseMapper.countByResponse(alarmType, jobStatus, deptId, beginTime, endTime);
    }

    @Override
    public Integer countByUser(String alarmType, String jobStatus, Long userId, String beginTime, String endTime) {
        return this.baseMapper.countByUser(alarmType, jobStatus, userId, beginTime, endTime);
    }


    @Override
    public String selectClientIdByUser(Long userId) {
        return this.baseMapper.selectClientIdByUser(userId);
    }
}
