package cn.wisenergy.service.impl;

import cn.wisenergy.common.utils.DateUtil;
import cn.wisenergy.common.utils.exception.BASE_RESP_CODE_ENUM;
import cn.wisenergy.common.utils.exception.BaseCustomException;
import cn.wisenergy.mapper.WorkCollectMapper;
import cn.wisenergy.mapper.WorkTimeOrderMapper;
import cn.wisenergy.model.app.WorkCollect;
import cn.wisenergy.model.app.WorkSubmitAdopt;
import cn.wisenergy.model.app.WorkTimeOrder;
import cn.wisenergy.model.app.WorkUser;
import cn.wisenergy.model.dto.CalendarDto;
import cn.wisenergy.model.dto.CalendarMonthDto;
import cn.wisenergy.model.dto.SubtotalDto;
import cn.wisenergy.model.enums.StatusEnum;
import cn.wisenergy.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * import java.util.Date;
 * import java.util.List;
 * <p>
 * /**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenqi
 * @since 2021-01-19
 */
@Service
@Slf4j
public class WorkCollectServiceImpl implements WorkCollectService {

    @Autowired
    private WorkCollectMapper workCollectMapper;

    @Autowired
    private WorkTimeOrderService workTimeOrderService;

    @Autowired
    private WorkCollectService workCollectService;

    @Autowired
    private WorkTimeOrderMapper workTimeOrderMapper;

    @Autowired
    private WorkSubmitAdoptService workSubmitAdoptService;

    @Autowired
    private WorkUserService workUserService;

    @Autowired
    private StatisticsService statisticsService;


    /**
     * 功能： 查询某年月的填报情况
     *
     * @param userId    用户id
     * @param workMonth 查询年月
     * @return List<CalendarDto>
     */
    @Override
    public CalendarMonthDto calendarMonth(Integer userId, Date workMonth) {
        log.info("WorkCollectServiceImpl[]calendarMonth[]input.param.userId:{},workMonth:{}", userId, workMonth);
        CalendarMonthDto calendarMonthDto = new CalendarMonthDto();
        if (null == userId || StringUtils.isEmpty(workMonth)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        List<CalendarDto> calendarDtoList = workCollectMapper.getWorkMonth(userId, workMonth);
        if (CollectionUtils.isEmpty(calendarDtoList)) {
            calendarDtoList.add(new CalendarDto().setWorkDay(DateUtil.getFirstDayOfMonth(workMonth)).setUserId(userId));
        }
        calendarMonthDto.setCalendarDtos(calendarDtoList);
        //返回当月被驳回次数
        int rejectMonth = 0;
        List<WorkTimeOrder> timeOrders = workTimeOrderMapper.geByMonth(userId, workMonth, StatusEnum.REJECTED.getCode());
        if (!CollectionUtils.isEmpty(timeOrders)) {
            rejectMonth = timeOrders.size();
        }
        calendarMonthDto.setRejectMonth(rejectMonth);

        WorkUser user = workUserService.getById(userId);
        // 如果查询的日期大于本月的日期，则不查询

        if (1 == user.getSubmitOrder() && workMonth.compareTo(new Date())<=0) {
            List<Date> notCompletedByMonth = getNotCompletedByMonth(userId, workMonth);
            StringBuffer sb = new StringBuffer();
            if (!CollectionUtils.isEmpty(notCompletedByMonth)) {
                notCompletedByMonth.forEach(notComplete -> sb.append(DateUtil.getDay(notComplete)).append("日,") );
                sb.deleteCharAt(sb.length() - 1);
                calendarMonthDto.setNotCompleteDay(sb.toString());
            }
        }else if(0 == user.getSubmitOrder()){
            calendarMonthDto.setNotCompleteDay("0");
        }
        return calendarMonthDto;
    }

    /**
     * 功能： 查询某日的填报小计
     *
     * @param userId  用户id
     * @param workDay 某日
     * @return List<CalendarDto>
     */

    @Override
    public SubtotalDto calendarDay(Integer userId, Date workDay) {
        log.info("WorkCollectServiceImpl[]calendarDay[]input.param.userId:{},workDay:{}", userId, workDay);
        if (null == userId || StringUtils.isEmpty(workDay)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        SubtotalDto subtotalDto = workTimeOrderService.getSubtotalReport(userId, workDay);
        if (null == subtotalDto) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_INFO_IS_NULL);
        }
        QueryWrapper<WorkCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("work_day", workDay);
        WorkCollect workCollect = workCollectMapper.selectOne(wrapper);
        if (workCollect != null) {
            subtotalDto.setStatus(workCollect.getStatus());
        }
        int modifyTime = 1;
        Date date = new Date();
        WorkSubmitAdopt submitAdopt = workSubmitAdoptService.getById(1);
        if (null != workCollect.getRejectTime()) {
            Date rejectTime = workCollect.getRejectTime();
            rejectTime = DateUtil.convertStrToDate(DateUtil.convertDateToStr(rejectTime, "yyyy-MM-dd"), "yyyy-MM-dd");
            if (DateUtil.isThanDay(rejectTime,date,submitAdopt.getSubmitTime())) {
                modifyTime = 0;
            }
        }
        subtotalDto.setModifyTime(modifyTime);
        return subtotalDto;
    }

    @Override
    public Boolean insertCollect(WorkCollect workCollect) {
        log.info("WorkCollectServiceImpl[]insertCollect[]input.param.WorkCollect{}" + workCollect);
        if (null == workCollect) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        int insertRow = workCollectMapper.insertWorkCollect(workCollect);
        if (insertRow == 0) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INSERT_DATA_IS_FAIL);
        }
        return true;
    }

    /**
     * 功能：判断当日是否已经填报
     *
     * @param userId  用户名
     * @param workDay 某日
     * @return 当日填报情况
     */
    @Override
    public WorkCollect getByUserIdAndWorkDay(Integer userId, Date workDay) {
        log.info("WorkCollectServiceImpl[]getByUserIdAndWorkDay[]input.param.userId：{}, workDay:{}" + userId, workDay);
        if (null == userId || null == workDay) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        QueryWrapper<WorkCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("work_day", workDay);
        WorkCollect workCollect = workCollectMapper.selectOne(wrapper);
        if (null == workCollect) {
            return null;
        }
        return workCollect;
    }

    /**
     * 获取当月已经填的并满8小时
     * @param userId 用户id
     * @param month 日期
     * @return 日期集合
     */
    private List<Date> getNotCompletedByMonth(Integer userId,Date month) {
        boolean flag = DateUtil.isYearAndMonthEqual(month, new Date());
        List<Date> workDays = statisticsService.currentMonthWorkDays(month, flag);
        List<WorkCollect> completedCollect = workCollectMapper.getCompletedByUserIdAndMonth(userId, month);
        List<Date> completedDays = new ArrayList<>();
        completedCollect.forEach(collect -> completedDays.add(collect.getWorkDay()));
        workDays.removeAll(completedDays);
        return workDays;
    }
    /**
     * 功能：修改某日的审批工时情况
     *
     * @param workCollect 实体类
     * @return 是否成功
     */
    @Override
    public Boolean update(WorkCollect workCollect) {
        log.info("WorkCollectServiceImpl[]getByUserIdAndWorkDay[]input.param.workCollect：{}, " + workCollect);
        if (null == workCollect) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        Integer id = getByUserIdAndWorkDay(workCollect.getUserId(), workCollect.getWorkDay()).getId();
        int updateRow = workCollectMapper.updateStatusOrTotalTime(id, workCollect.getStatus(), workCollect.getTotalTime());
        if (updateRow == 0) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.UPDATE_DATA_FAIL);
        }
        return true;
    }

    @Transactional
    @Override
    public Boolean updateByWorkTimeOrder(List<WorkTimeOrder> workTimeOrders) {
        log.info("WorkCollectServiceImpl[]updateByWorkTimeOrder[]input.param.workTimeOrders：{}, " + workTimeOrders);
        for (WorkTimeOrder workTimeOrder : workTimeOrders) {
            List<WorkTimeOrder> byDay = workTimeOrderMapper.getByDay(workTimeOrder.getUserId(), workTimeOrder.getWorkDay());
            int total_time = 0;
            for (WorkTimeOrder timeOrder : byDay) {
                total_time += timeOrder.getWorkTime();
            }
            int status = workTimeOrderService.statusYes(workTimeOrder.getUserId(), workTimeOrder.getWorkDay());
            WorkCollect workCollect = workCollectService.getByUserIdAndWorkDay(workTimeOrder.getUserId(), workTimeOrder.getWorkDay());
            workCollect.setStatus(status);
            workCollect.setTotalTime(total_time);
            workCollectService.update(workCollect);
        }

        return true;
    }
}
