package com.njzscloud.dispose.finance.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.common.utils.FileUtil;
import com.njzscloud.dispose.finance.mapper.MoneyFlowMapper;
import com.njzscloud.dispose.finance.pojo.entity.MoneyFlowEntity;
import com.njzscloud.dispose.finance.pojo.param.SearchMoneyFlowParam;
import com.njzscloud.dispose.finance.pojo.result.MoneyFlowResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 资金流水
 *
 * @author ljw
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MoneyFlowService extends ServiceImpl<MoneyFlowMapper, MoneyFlowEntity> {

    /**
     * 新增
     */
    public void add(MoneyFlowEntity moneyFlowEntity) {
        this.save(moneyFlowEntity);
    }

    /**
     * 修改
     */
    public void modify(MoneyFlowEntity moneyFlowEntity) {
        this.updateById(moneyFlowEntity);
    }

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

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

    /**
     * 构建查询条件
     */
    private QueryWrapper<MoneyFlowEntity> buildQueryWrapper(SearchMoneyFlowParam param) {
        return Wrappers.<MoneyFlowEntity>query()
            .eq("fmf.deleted", Boolean.FALSE)
            .eq(param.getOrderId() != null, "fmf.order_id", param.getOrderId())
            .like(StrUtil.isNotBlank(param.getOrderSn()), "fmf.order_sn", param.getOrderSn())
            .eq(param.getTrainNum() != null, "fmf.train_num", param.getTrainNum())
            .eq(param.getMoneyAccountId() != null, "fmf.money_account_id", param.getMoneyAccountId())
            .eq(param.getMoneyChangeCategory() != null, "fmf.money_change_category", param.getMoneyChangeCategory())
            .and(StrUtil.isNotBlank(param.getAccountName()), wrapper ->
                wrapper.like("cc.customer_name", param.getAccountName())
                    .or()
                    .like("co.org_name", param.getAccountName())
            )
            .eq(param.getAccountType() != null, "fma.account_type", param.getAccountType())
            .ge(param.getStartTime() != null, "fmf.create_time", param.getStartTime())
            .le(param.getEndTime() != null, "fmf.create_time", param.getEndTime());
    }

    /**
     * 分页查询
     */
    public PageResult<MoneyFlowResult> paging(PageParam pageParam, SearchMoneyFlowParam param) {
        return PageResult.of(baseMapper.paging(pageParam.toPage(), buildQueryWrapper(param)));
    }

    /**
     * 导出
     */
    public void export(HttpServletResponse response, SearchMoneyFlowParam param) throws IOException {
        List<MoneyFlowResult> exportList = baseMapper.paging(buildQueryWrapper(param));
        List<Map<String, Object>> downList = new ArrayList<>();
        int i = 1;
        for (MoneyFlowResult result : exportList) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("编号", i);
            map.put("账户名称", result.getAccountName());
            map.put("账户类型", result.getAccountType().getTxt());
            map.put("订单号", result.getOrderSn());
            map.put("车次", result.getTrainNum());
            map.put("变动类型", result.getMoneyChangeCategory().getTxt());
            map.put("变动前金额", result.getBeforeBalance());
            map.put("变动金额", result.getDelta());
            map.put("变动后金额", result.getAfterBalance());
            map.put("备注", result.getMemo());
            downList.add(map);
            i++;
        }
        FileUtil.downloadExcel(downList, response, "资金变动明细.xlsx");
    }
}
