package com.boman.web.core.service.leave;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.DateUtils;
import com.boman.web.core.service.common.ICommonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.boman.common.core.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;
import static com.boman.common.core.utils.obj.ObjectUtils.isEmpty;
import static com.boman.common.core.utils.obj.ObjectUtils.requireNonNull;
import static com.boman.domain.constant.LeaveConst.*;

/**
 * @author shiqian
 * @date 2021年06月17日 16:04
 **/
@Service
public class LeaveServiceImpl implements LeaveService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LeaveServiceImpl.class);

    @Resource
    private ICommonService commonService;

    /**
     * 功能描述: 直接查询一年的
     *
     * @param yyyy yyyy
     * @return int
     */
    @Override
    public Map<String, Integer> statisticByType(String yyyy) {
        requireNonNull(yyyy, "statisticByType yyyy is empty");
        Map<String, Integer> map = new HashMap<>(2);

        String yearStartTime = yyyy + "-01-01 00:00:00";
        String yearEndTime = yyyy + "-12-31 23:59:59";

        List<JSONObject> result = listByTime(yearStartTime, yearEndTime);
        if (isEmpty(result)) {
            map.put(YEAR_LEAVE_COUNT, 0);
            map.put(MONTH_LEAVE_COUNT, 0);
            return map;
        }

        Date firstDayOfMonth = DateUtils.dateTime(YYYY_MM_DD_HH_MM_SS, yyyy + "-" + DateUtils.getMonth() + "-01 00:00:00");
        Date lastDayOfMonth = DateUtils.dateTime(YYYY_MM_DD_HH_MM_SS, DateUtils.getLastDayOfMonthStr(yyyy));
        int count = 0;
        for (JSONObject jsonObject : result) {
            Timestamp startTime = jsonObject.getTimestamp(LEAVEFROM_START_TIME);
            // 并且是当月的
            if (startTime.after(firstDayOfMonth) && startTime.before(lastDayOfMonth)) {
                count++;
            }
        }

        map.put(YEAR_LEAVE_COUNT, result.size());
        map.put(MONTH_LEAVE_COUNT, count);
        return map;
    }

    private List<JSONObject> listByTime(String startTime, String endTime) {
        JSONObject condition = new JSONObject();
        condition.put(LEAVEFROM_START_TIME, startTime);
        condition.put(LEAVEFROM_END_TIME, endTime);
        return commonService.getByMap(TABLE_NAME, condition);
    }


}
