package com.gree.mall.miniapp.logic.material;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.miniapp.bean.material.NormRecordVO;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.commonmapper.MaterialMapper;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

@Service
@Slf4j
public class NormRecordLogic {

    @Resource
    MaterialMapper materialMapper;
    @Resource
    CommonLogic commonLogic;

    public IPage<NormRecordVO> list(String orderId, String goodsType, String yearMonth, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        String startTime = null;
        String endTime = null;
        if (StringUtils.isNotBlank(yearMonth)) {
            String[] monthDateTime = computeMonthDateTime(yearMonth);
            startTime = monthDateTime[0];
            endTime = monthDateTime[1];
        }
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);
        IPage<NormRecordVO> page = materialMapper.normRecordList(new Page<>(pageNum, pageSize), wechat.getCurrentCompanyWechatId(),
                wechat.getUserId(), orderId, goodsType, startTime, endTime);
        return page;
    }


    private String[] computeMonthDateTime(String month) throws RemoteServiceException {
        try {
            String startDate = String.format("%s-01 00:00:00", month);
            Date date = DateUtils.parseDate(startDate);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            String endDate = DateUtils.formatDate1(cal.getTime()) + " 23:59:59";
            return new String[] { startDate, endDate };
        } catch (ParseException e) {
            log.error("computeMonthDateTime() 月份转换出错", e);
            throw new RemoteServiceException("月份转换出错");
        }
    }
}
