package com.zcxk.order.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxk.model.LoginUser;
import com.zcxk.order.dao.WorkOrderManageMapper;
import com.zcxk.order.dto.StatisticsDto;
import com.zcxk.order.dto.WorkOrderManageByAlarmDto;
import com.zcxk.order.dto.WorkOrderManageDto;
import com.zcxk.order.entity.WorkOrderManage;
import com.zcxk.order.service.WorkOrderManageService;
import com.zcxk.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 *
 * @author yjy
 * @Description
 * @date 2021-1-11
 */

@Service
public class WorkOrderManageServiceImpl implements WorkOrderManageService {

    @Autowired
    WorkOrderManageMapper workOrderManageMapper;
    /**
     * 新增数据
     *
     * @param workOrderManage 实例对象
     * @return 实例对象
     */
    @Override
    public int insertSelective(WorkOrderManage workOrderManage) {
        return workOrderManageMapper.insertSelective(workOrderManage);
    }

    /**
     * APP运维管理待处理
     */
    @Override
    public List<WorkOrderManageDto> selectAppTodo() {
        LoginUser currentUser = UserUtil.getCurrentUser();
        return workOrderManageMapper.selectAppTodo(currentUser.getId(),currentUser.getTenantId());
    }
    /**
     * APP运维管理全部查询
     */
    @Override
    public List<WorkOrderManageDto> selectAppAll() {
        LoginUser currentUser = UserUtil.getCurrentUser();
        return workOrderManageMapper.selectAppAll(currentUser.getId(),currentUser.getTenantId());
    }
    /**
     * 按id查询工单
     */
    @Override
    public WorkOrderManage selectByPrimaryKey(Integer id) {
        return workOrderManageMapper.selectByPrimaryKey(id);
    }
    /**
     * 更新工单
     */
    @Override
    public int updateByPrimaryKey(WorkOrderManage record) {
        return workOrderManageMapper.updateByPrimaryKey(record);
    }
    /**
     * 按id查询工单和详情
     */
    @Override
    public List<WorkOrderManageDto> selectOrderDetail(Integer id) {
        return workOrderManageMapper.selectOrderDetail(id);
    }
    /**
     * 批量插入工单信息（报警生成的）
     */
    @Override
    public Integer batchInsertByAlarms(List<WorkOrderManageByAlarmDto> workOrderManages) {
        if(workOrderManages.size()>0){
            return workOrderManageMapper.batchInsertByAlarms(workOrderManages);
        }
        return 0;
    }
    /**
     * 报警恢复时，删除未派单的工单
     */
    @Override
    public Integer batchDeleteByAlarms(List<Long> deviceIds) {
        if(deviceIds.size()>0){
            return workOrderManageMapper.batchDeleteByAlarms(deviceIds);
        }
        return 0;
    }

    public List<WorkOrderManageByAlarmDto> findWorkOrderByDeviceIds(List<Long> deviceIds){
        return workOrderManageMapper.findWorkOrderByDeviceIds(deviceIds);
    }

    public void updateByAlarms(List<WorkOrderManageByAlarmDto> workOrderManages){
        for(WorkOrderManageByAlarmDto workOrderManage :workOrderManages){
            workOrderManageMapper.updateByAlarms(workOrderManage);
        }
    }

    @Override
    public Page<WorkOrderManageDto> selectPage(IPage<WorkOrderManageDto> page, WorkOrderManageDto workOrderManageDto) {
        return workOrderManageMapper.findPage(page,workOrderManageDto);
    }

    @Override
    public Page<WorkOrderManageDto> selectByNo(IPage<WorkOrderManageDto> page,WorkOrderManageDto workOrderManageDto) {
        return workOrderManageMapper.findByNo(page,workOrderManageDto);
    }

    @Override
    public Page<WorkOrderManageDto> findEventListPage(IPage<WorkOrderManageDto> page, WorkOrderManageDto workOrderManageDto) {
        return workOrderManageMapper.findEventListPage(page,workOrderManageDto);
    }

    @Override
    public List<WorkOrderManage> selectByPId(Map<String, Object> map) {
        return workOrderManageMapper.selectByPId(map);
    }

    @Override
    public int updateByPrimaryKeySelective(WorkOrderManage record) {
        return workOrderManageMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public Integer batchDelete(List<Integer> ids) {
        return workOrderManageMapper.batchDelete(ids);
    }

    @Override
    public Map<String, Object> selectOrderUserStatus(String userId) {
        return workOrderManageMapper.selectOrderUserStatus(userId);
    }

    @Override
    public Map<String, Object> selectPlanUserStatus(String userId) {
        return workOrderManageMapper.selectPlanUserStatus(userId);
    }

    @Override
    public Map<String, Object> selectMaintainUserStatus(String userId) {
        return workOrderManageMapper.selectMaintainUserStatus(userId);
    }

    @Override
    public Map<String, Object> workOrderStatistics(WorkOrderManageDto workOrderManageDto) {
        return workOrderManageMapper.workOrderStatistics(workOrderManageDto);
    }

    @Override
    public List<Map<String, Object>> eventMonthStatistics(WorkOrderManageDto workOrderManageDto) throws ParseException {
        int days = differentDaysByMillisecond(workOrderManageDto.getStartDate(),workOrderManageDto.getEndDate());
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> list = workOrderManageMapper.eventMonthStatistics(workOrderManageDto);
        for(int i=0; i<days; i++) {
            String strDate =  subDay(workOrderManageDto.getStartDate(),i);
            Map<String, Object> data = new HashMap<>();
            data.put("数量", 0);
            data.put("日期", strDate);
            data.put("序号",i+1);
            result.add(data);
        }
        for(int i=0;i<list.size();i++){
            Map<String,Object> map =list.get(i);
            int day = Integer.parseInt(map.get("日期").toString().substring(8,10));
            result.get(day-1).put("数量",map.get("数量"));
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> eventYearStatistics(WorkOrderManageDto workOrderManageDto) throws ParseException {
        int months = differentMonths(workOrderManageDto.getStartDate(),workOrderManageDto.getEndDate());
        List<Map<String,Object>> list = workOrderManageMapper.eventYearStatistics(workOrderManageDto);
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        for(int i=0; i<months; i++) {
            String strDate = workOrderManageDto.getStartDate().substring(0, 4) + String.format("-%02d", i + 1);
            Map<String, Object> data = new HashMap<>();
            data.put("数量", 0);
            data.put("日期", strDate);
            data.put("序号",i+1);
            result.add(data);
        }
        for(int i=0;i<list.size();i++){
            Map<String,Object> map =list.get(i);
            int month = Integer.parseInt(map.get("日期").toString().substring(5,7));
            result.get(month-1).put("数量",map.get("数量"));
        }
        return result;
    }

    @Override
    public int selectPendingPower(Map<String, Object> map) {
        return workOrderManageMapper.selectPendingPower(map);
    }


    @Override
    public List<WorkOrderManageDto> selectOrderStatus(WorkOrderManageDto workOrderManageDto) {
        return workOrderManageMapper.selectOrderStatus(workOrderManageDto);
    }

    @Override
    public List<WorkOrderManageDto> selectMaintainOrder(WorkOrderManageDto workOrderManageDto) {
        return workOrderManageMapper.selectMaintainOrder(workOrderManageDto);
    }

    @Override
    public List<StatisticsDto> reportStatistics(WorkOrderManageDto workOrderManageDto) {
        return workOrderManageMapper.reportStatistics(workOrderManageDto);
    }

    @Override
    public List<StatisticsDto> orderStatusStatistics(WorkOrderManageDto workOrderManageDto) {
        return workOrderManageMapper.orderStatusStatistics(workOrderManageDto);
    }

    @Override
    public List<StatisticsDto> orderTypeStatistics(WorkOrderManageDto workOrderManageDto) {
        return workOrderManageMapper.orderTypeStatistics(workOrderManageDto);
    }

    @Override
    public List<StatisticsDto> orderDurationStatistics(WorkOrderManageDto workOrderManageDto) {
        List<StatisticsDto> result = new ArrayList<StatisticsDto>();
        List<StatisticsDto> list = workOrderManageMapper.orderDurationStatistics(workOrderManageDto);
        for(int i=1;i<=6;i++){
            StatisticsDto statisticsDto = new StatisticsDto();
            statisticsDto.setIndex(i);
            statisticsDto.setStatisticsName(String.valueOf(i));
            statisticsDto.setStatisticsValue(0.0);
            result.add(statisticsDto);
        }
        for(int i=0;i<list.size();i++){
            StatisticsDto statisticsDto = list.get(i);
            StatisticsDto statisticsDto1 = result.get(Integer.parseInt(statisticsDto.getStatisticsName())-1);
            statisticsDto1.setStatisticsValue(statisticsDto.getStatisticsValue());
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> dispatchTimesMonthStatistics(WorkOrderManageDto workOrderManageDto,List<String> idsList) throws ParseException {
        int days = differentDaysByMillisecond(workOrderManageDto.getStartDate(),workOrderManageDto.getEndDate());
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> list = workOrderManageMapper.dispatchTimesMonthStatistics(workOrderManageDto,idsList);
        for(int i=0; i<days; i++) {
            String strDate =  subDay(workOrderManageDto.getStartDate(),i);
            Map<String, Object> data = new HashMap<>();
            data.put("数量", 0);
            data.put("日期", strDate);
            data.put("序号",i+1);
            result.add(data);
        }
        for(int i=0;i<list.size();i++){
            Map<String,Object> map =list.get(i);
            int day = Integer.parseInt(map.get("日期").toString().substring(8,10));
            result.get(day-1).put("数量",map.get("数量"));
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> dispatchTimesYearStatistics(WorkOrderManageDto workOrderManageDto, List<String> idsList) throws ParseException {
        int months = differentMonths(workOrderManageDto.getStartDate(),workOrderManageDto.getEndDate());
        List<Map<String,Object>> list = workOrderManageMapper.dispatchTimesYearStatistics(workOrderManageDto,idsList);
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        for(int i=0; i<months; i++) {
            String strDate = workOrderManageDto.getStartDate().substring(0, 4) + String.format("-%02d", i + 1);
            Map<String, Object> data = new HashMap<>();
            data.put("数量", 0);
            data.put("日期", strDate);
            data.put("序号",i+1);
            result.add(data);
        }
        for(int i=0;i<list.size();i++){
            Map<String,Object> map =list.get(i);
            int month = Integer.parseInt(map.get("日期").toString().substring(5,7));
            result.get(month-1).put("数量",map.get("数量"));
        }
        return result;
    }

    @Override
    public Page<WorkOrderManageDto> selectByTime(IPage<WorkOrderManageDto> page, String tenantId, Integer userId, String startTime, String endTime) {
        return workOrderManageMapper.selectByTime(page, userId, tenantId, startTime, endTime);
    }

    @Override
    public WorkOrderManageDto findWorkFlowById(Integer id){
        return workOrderManageMapper.findWorkFlowById(id);
    }


    public int differentDaysByMillisecond(String date1,String date2) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt1 = sdf.parse(date1);
        Date dt2 = sdf.parse(date2);
        int days = (int) ((dt2.getTime() - dt1.getTime()) / (1000*3600*24));
        return days;
    }


    /**
     * 计算2个日期之间相差的  以年、月、日为单位，各自计算结果是多少
     * 比如：2011-02-02 到  2017-03-02
     *                                以年为单位相差为：6年
     *                                以月为单位相差为：73个月
     *                                以日为单位相差为：2220天
     * @param startDate
     * @param endDate
     * @return
     */
    public int differentMonths(String startDate,String endDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date fromDate = sdf.parse(startDate);
        Date toDate = sdf.parse(endDate);
        Calendar  from  =  Calendar.getInstance();
        from.setTime(fromDate);
        Calendar  to  =  Calendar.getInstance();
        to.setTime(toDate);
        //只要年月
        int fromYear = from.get(Calendar.YEAR);
        int fromMonth = from.get(Calendar.MONTH);

        int toYear = to.get(Calendar.YEAR);
        int toMonth = to.get(Calendar.MONTH);
        // int year = toYear  -  fromYear;
        int month = toYear *  12  + toMonth  -  (fromYear  *  12  +  fromMonth);
        // int day = (int) ((to.getTimeInMillis()  -  from.getTimeInMillis())  /  (24  *  3600  *  1000));
        return month;
    }


    /**
     *日期加一天
     */
    private String subDay(String date, int n) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = sdf.parse(date);
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.DATE, n);
        Date dt1 = rightNow.getTime();
        String reStr = sdf.format(dt1);
        return reStr;
    }
}
