package com.njzscloud.dispose.finance.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.dispose.finance.mapper.BillMapper;
import com.njzscloud.dispose.finance.pojo.entity.BillEntity;
import com.njzscloud.dispose.finance.pojo.result.BillStatisticsResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 对账单
 *
 * @author ljw
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BillService extends ServiceImpl<BillMapper, BillEntity> {

    /**
     * 新增
     */
    public void add(BillEntity billEntity) {
        this.save(billEntity);
    }

    /**
     * 修改
     */
    public void modify(BillEntity billEntity) {
        this.updateById(billEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     */
    public BillEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     */
    public PageResult<BillEntity> paging(PageParam pageParam, BillEntity billEntity) {
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.query(billEntity)));
    }

    /**
     * 生成对账单
     *
     * @param startTime 统计开始时间
     * @param endTime   统计结束时间
     * @return 生成的账单数量
     */
    @Transactional(rollbackFor = Exception.class)
    public int generateBill(LocalDateTime startTime, LocalDateTime endTime) {
        log.info("开始生成对账单，时间范围：{} ~ {}", startTime, endTime);

        // 统计对账单数据
        List<BillStatisticsResult> statisticsList = baseMapper.statisticsBillData(startTime, endTime);
        log.info("统计到 {} 条对账单数据", statisticsList.size());

        int count = 0;
        for (BillStatisticsResult statistics : statisticsList) {
            BillEntity billEntity = BeanUtil.copyProperties(statistics, BillEntity.class);
            // 转换统计数据为对账单实体
            billEntity.setBillPeriod(LocalDate.now());
            billEntity.setStartTime(startTime.toLocalDate());
            billEntity.setEndTime(endTime.toLocalDate());
            // 设置备注
            billEntity.setMemo("系统自动生成");
            this.save(billEntity);
            count++;
            log.info("已生成对账单，客户ID：{}，订单数：{}，总金额：{}",
                statistics.getCustomerId(), statistics.getOrderCount(), statistics.getTotalMoney());
        }

        log.info("对账单生成完成，共生成 {} 条对账单", count);
        return count;
    }

}
