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.dto.CalendarDto;
import cn.wisenergy.model.dto.CalendarMonthDto;
import cn.wisenergy.model.dto.SubtotalDto;
import cn.wisenergy.model.enums.StatusEnum;
import cn.wisenergy.service.WorkCollectService;
import cn.wisenergy.service.WorkSubmitAdoptService;
import cn.wisenergy.service.WorkTimeOrderService;
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.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;


    /**
     * 功能： 查询某年月的填报情况
     *
     * @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);
        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;
    }

    /**
     * 功能：修改某日的审批工时情况
     *
     * @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;
    }
}
