package com.njzscloud.supervisory.money.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
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.common.security.util.SecurityUtil;
import com.njzscloud.supervisory.biz.pojo.result.SearchCompanyResult;
import com.njzscloud.supervisory.money.contant.MoneyDetailType;
import com.njzscloud.supervisory.money.mapper.MoneyChangeDetailMapper;
import com.njzscloud.supervisory.money.pojo.entity.MoneyChangeDetailEntity;
import com.njzscloud.supervisory.money.pojo.result.MoneyChangeDetailExportResult;
import com.njzscloud.supervisory.order.utils.FileUtil;
import com.njzscloud.supervisory.sys.auth.mapper.AuthMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.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 MoneyChangeDetailService extends ServiceImpl<MoneyChangeDetailMapper, MoneyChangeDetailEntity> implements IService<MoneyChangeDetailEntity> {

    private final AuthMapper authMapper;

    /**
     * 新增
     */
    public void add(MoneyChangeDetailEntity moneyChangeDetailEntity) {
        moneyChangeDetailEntity.setUserId(SecurityUtil.currentUserId());
        moneyChangeDetailEntity.setNewMoney(moneyChangeDetailEntity.getOldMoney().add(moneyChangeDetailEntity.getDelta()));
        this.save(moneyChangeDetailEntity);
    }

    /**
     * 修改
     */
    public void modify(MoneyChangeDetailEntity moneyChangeDetailEntity) {
        this.updateById(moneyChangeDetailEntity);
    }

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

    /**
     * 根据订单ID和类型查询资金明细
     */
    public MoneyChangeDetailEntity getByOrderIdAndType(Long orderId, MoneyDetailType type) {
        return this.lambdaQuery()
                .eq(MoneyChangeDetailEntity::getOrderId, orderId)
                .eq(MoneyChangeDetailEntity::getType, type)
                .one();
    }

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

    /**
     * 分页查询
     */
    public PageResult<MoneyChangeDetailEntity> paging(PageParam pageParam, MoneyChangeDetailEntity moneyChangeDetailEntity) {
        Page<MoneyChangeDetailEntity> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
        IPage<MoneyChangeDetailEntity> result = baseMapper.page(page, moneyChangeDetailEntity);
        return PageResult.of(result);
    }

    public PageResult<MoneyChangeDetailExportResult> selectPagingByCompanyId(PageParam pageParam, MoneyChangeDetailEntity entity) {
        Page<MoneyChangeDetailExportResult> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
        Long userId = SecurityUtil.currentUserId();
        SearchCompanyResult company = authMapper.selectCompanyInfo(userId);
        IPage<MoneyChangeDetailExportResult> result = new Page<>();
        if (null != company) {
            entity.setCompanyId(company.getId());
            result = baseMapper.exportList(page, entity);
        }
        return PageResult.of(result);
    }

    public void export(HttpServletResponse response, MoneyChangeDetailEntity entity) throws IOException {
        List<MoneyChangeDetailExportResult> list = baseMapper.exportList(entity);
        List<Map<String, Object>> downList = new ArrayList<>();
        int i = 1;
        for (MoneyChangeDetailExportResult result : list) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("编号", i);
            map.put("订单号", result.getSn());
            map.put("车牌号", result.getLicensePlate());
            map.put("变动类型", result.getMoneyChangeCategory());
            map.put("变动金额", result.getDelta());
            map.put("余额", result.getNewMoney());
            map.put("产品名称", result.getGoodsName());
            map.put("单价", result.getUnitPrice());
            map.put("入场磅重（吨）", result.getRoughWeight());
            map.put("皮重（吨）", result.getTareWeight());
            map.put("净重（吨）", result.getSettleWeight());
            map.put("进场时间", result.getInTime());
            map.put("出场时间", result.getOutTime());
            map.put("备注", result.getMemo());
            downList.add(map);
            i++;
        }
        FileUtil.downloadExcel(downList, response, "资金变动明细.xlsx");

    }
}
