package com.yami.shop.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.PointsRecord;
import com.yami.shop.bean.po.PointsRecordPo;
import com.yami.shop.bean.vo.PointsRecordVo;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.dao.PointsRecordMapper;
import com.yami.shop.service.PointsRecordService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 积分记录详细 Service实现类
 *
 * @author fbj
 * @since 2025-09-XX
 */
@Service
@AllArgsConstructor
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements PointsRecordService {

    private final PointsRecordMapper pointsRecordMapper;

    /**
     * 生成所有用户的当天过期定时任务
     */
    @Override
    public void expiredPoints(String todayStr, String yesterdayStr) {

        Date today = getDate(todayStr, true);
        if (today == null) {
            throw new ClassCastException("当天定时任务时间类型转换异常");
        }
        Date yesterday = getDate(yesterdayStr, false);
        if (yesterday == null) {
            throw new ClassCastException("昨天定时任务时间类型转换异常");
        }
        List<PointsRecord> pointsRecords= pointsRecordMapper.findByExpiredPoints(today,yesterday);
        if (pointsRecords==null||pointsRecords.isEmpty()){
            System.out.println("当前时间没有过期积分，开始时间："+yesterdayStr+";结束时间："+todayStr);
            return;
        }
        System.out.println("处理数据长度"+pointsRecords.size());
        for (PointsRecord pointsRecord : pointsRecords) {
            pointsRecord.setId(null);
            Long l = pointsRecordMapper.statisticsPoint(pointsRecord.getUserId(), pointsRecord.getChannelId());
            if (l==null){
                pointsRecord.setCurrentlyAvailablePoints(BigDecimal.ZERO);
            }else {
                pointsRecord.setCurrentlyAvailablePoints(BigDecimal.valueOf(l));
            }
            pointsRecordMapper.insert(pointsRecord);
        }
    }

    @Override
    public IPage<PointsRecordVo> backendPointsRecordList(PointsRecordPo po) {
        return baseMapper.backendPointsRecordList(new Page<>(po.getCurrent(), po.getSize()), po);
    }

    @Override
    public void backendPointsRecordListExport(HttpServletResponse response, PointsRecordPo po) {
        try {
            List<PointsRecordVo> list = baseMapper.backendPointsRecordList2(po);
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("积分使用记录表", String.valueOf(StandardCharsets.UTF_8)).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), PointsRecordVo.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("列表").doWrite(list);
        } catch (IOException e) {
            throw new GlobalException("文件下载异常");
        }
    }

    /**
     * @param dateStr string类型的时间
     * @param type    标识是否为当天
     * @return
     */
    private Date getDate(String dateStr, Boolean type) {
        Date date = null;
        // 获取前一天0点
        if (StringUtils.isNotEmpty(dateStr)) {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //将当前时间转换为date类型
            try {
                date = sdf1.parse(dateStr);
            } catch (ParseException e) {
                return null;
            }
        } else {
            LocalDate today = LocalDate.now();
            if (type) {
                // 获取当天0点
                date = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
            } else {
                LocalDate yesterday = today.minusDays(1);
                date = Date.from(yesterday.atStartOfDay(ZoneId.systemDefault()).toInstant());
            }

        }

        return date;
    }
}
