package com.czg.service.account.service.impl;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.czg.account.entity.ShopUserFlow;
import com.czg.account.service.ShopInfoService;
import com.czg.account.service.ShopUserFlowService;
import com.czg.account.vo.ShopUserFlowVO;
import com.czg.service.account.mapper.ShopUserFlowMapper;
import com.czg.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.dubbo.config.annotation.DubboService;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

/**
 * 用户余额流水 服务层实现。
 *
 * @author zs
 * @since 2025-02-13
 */
@DubboService
public class ShopUserFlowServiceImpl extends ServiceImpl<ShopUserFlowMapper, ShopUserFlow> implements ShopUserFlowService {
    @Resource
    private ShopInfoService shopInfoService;

    @Override
    public void updateRefund(Long id, BigDecimal refundAmount) {
        UpdateChain.of(ShopUserFlow.class)
                .setRaw(ShopUserFlow::getRefundAmount, "refund_amount + " + refundAmount)
                .eq(ShopUserFlow::getId, id)
                .update();
    }

    @Override
    public Page<ShopUserFlowVO> pageInfo(Long shopId, Integer userId, String bizCode, String startTime, String endTime) {
        PageHelper.startPage(PageUtil.buildPageHelp());
        return PageUtil.convert(new PageInfo<>(mapper.pageInfo(shopId, userId, bizCode, startTime, endTime)));
    }

    @Override
    public void flowDownload(Long shopId, Integer userId, String bizCode, String startTime, String endTime, HttpServletResponse response) throws IOException {
        PageHelper.startPage(PageUtil.buildPageHelp());
        List<ShopUserFlowVO> shopUserFlowVOS = mapper.pageInfo(shopId, userId, bizCode, startTime, endTime);

        // 1. 创建 ExcelWriter
        // true 表示使用 XLSX 格式
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 2. 写入数据
        writer.write(shopUserFlowVOS, true);

        // 3. 设置响应头，返回 Excel
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("余额明细.xlsx", "UTF-8"));

        // 4. 写入到响应流
        writer.flush(response.getOutputStream(), true);
        writer.close();
    }
}
