package com.bonus.material.push.controller;

import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.poi.ExcelUtil;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.material.clz.domain.vo.MaterialRetainedEquipmentInfo;
import com.bonus.material.clz.domain.vo.lease.LeaseTotalInfo;
import com.bonus.material.push.domain.IwsCostPushBean;
import com.bonus.material.push.domain.vo.IwsCostPushExportVo;
import com.bonus.material.push.service.IwsCostPushService;
import com.bonus.material.settlement.domain.SltAgreementInfo;
import com.bonus.material.settlement.service.impl.SltAgreementInfoServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : 阮世耀
 * @version : 1.0
 * @PackagePath: com.bonus.material.push.controller
 * @CreateTime: 2025-01-23  15:04
 * @Description: i皖送费用推送控制器
 */
@RestController
@RequestMapping("/iws_cost_push")
@Validated
public class IwsCostPushController extends BaseController {

    @Resource
    private IwsCostPushService iwsCostPushService;

    @Resource
    private SltAgreementInfoServiceImpl sltAgreementInfoService;


    /**
     * 查询协议推送匹配列表
     * @param obj 查询条件
     */
    @ApiOperation("查询协议推送匹配列表--分页")
    @GetMapping("/findAgreementPushMatchList")
    public TableDataInfo findAgreementPushMatchList(IwsCostPushBean obj) {
        startPage();
        List<IwsCostPushBean> list = iwsCostPushService.findAgreement(obj);
        return getDataTable(list);
    }

    /**
     * 导出协议推送匹配列表
     */
    @PostMapping("/export")
    @ApiOperation("导出协议推送匹配列表--后端处理")
    public void export(HttpServletResponse response, IwsCostPushBean obj) {
        List<IwsCostPushBean> list = iwsCostPushService.findAgreement(obj);
        ExcelUtil<IwsCostPushBean> util = new ExcelUtil<>(IwsCostPushBean.class);
        util.exportExcel(response, list, "协议推送匹配");
    }

    /**
     * 查询费用推送审核列表
     * @param obj 查询条件
     */
    @GetMapping("/getCostPushCheckList")
    @ApiOperation("查询费用推送审核列表--不分页")
    public TableDataInfo getCostPushCheckList(IwsCostPushBean obj) {
        //startPage(); 取消分页
        List<IwsCostPushBean> list = iwsCostPushService.getCostPushCheckList(obj);
        return getDataTable(list);
    }

    /**
     * 导出费用推送审核列表
     */
    @PostMapping("/exportCostPushExamList")
    @ApiOperation("导出费用推送审核列表--后端处理")
    public void exportCostPushList(HttpServletResponse response, IwsCostPushBean obj) {
        try {
            // 获取费用推送审核列表
            List<IwsCostPushBean> list = iwsCostPushService.getCostPushCheckList(obj);

            // 将数据转换为导出对象列表
            String month = Optional.ofNullable(obj).map(IwsCostPushBean::getMonth).orElse("");
            List<IwsCostPushExportVo> exportVoList = list.stream()
                    .map(bean -> {
                        IwsCostPushExportVo vo = new IwsCostPushExportVo();
                        BeanUtils.copyProperties(bean, vo);
                        vo.setMonth(month); // 直接使用提取的月份
                        return vo;
                    })
                    .collect(Collectors.toList());

            // 计算统计信息
            BigDecimal totalLeaseMoney = exportVoList.stream().map(IwsCostPushExportVo::getLeaseMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal totalRepairMoney = exportVoList.stream().map(IwsCostPushExportVo::getRepairMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal totalLostMoney = exportVoList.stream().map(IwsCostPushExportVo::getLostMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal totalScrapMoney = exportVoList.stream().map(IwsCostPushExportVo::getScrapMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

            // 创建统计行
            IwsCostPushExportVo summaryVo = new IwsCostPushExportVo();
            summaryVo.setMonth("合计租赁费用");
            summaryVo.setLeaseMoney(totalLeaseMoney);

            // 将统计行添加到数据列表中
            exportVoList.add(summaryVo);

            // 导出Excel
            ExcelUtil<IwsCostPushExportVo> excelUtil = new ExcelUtil<>(IwsCostPushExportVo.class);
            excelUtil.exportExcel(response, exportVoList, "费用推送审核表");
        } catch (Exception e) {
            // 记录异常并抛出自定义异常
            System.err.println("导出异常 = " + e.getMessage());
            throw new ServiceException("导出异常,请联系运维人员查询日志");
        }
    }


    /**
     * 根据协议ID及月份查询当月租赁费用明细
     * @param obj 查询条件
     * @return 分页数据
     */
    @GetMapping("/getLeaseCostsByAgreementIdAndMonth")
    @ApiOperation("根据协议ID及月份查询当月租赁费用明细--不分页")
    public TableDataInfo getLeaseCostsByAgreementIdAndMonth(IwsCostPushBean obj) {
        if (Objects.isNull(obj) || Objects.isNull(obj.getAgreementId()) || Objects.isNull(obj.getMonth())) {
            System.err.println("查询信息为空 = " + obj);
            return getDataTable(Collections.emptyList());
        }
        //startPage(); 取消分页
        try {
            List<IwsCostPushBean> list = iwsCostPushService.getLeaseCostsByAgreementIdAndMonth(obj);
            return getDataTable(list);
        } catch (Exception e) {
            System.err.println("数据查询异常 = " + e.getMessage());
            throw new ServiceException("数据查询异常，请联系运维人员查询日志处理");
        }
    }

    /**
     * 根据协议ID查询结算的维修费用明细
     * @param obj 查询条件
     */
    @GetMapping("/getRepairCostsByAgreementId")
    @ApiOperation("根据协议ID查询维修费用结算明细--不分页")
    public TableDataInfo getRepairCostsByAgreementId(IwsCostPushBean obj) {
        if (Objects.isNull(obj) || Objects.isNull(obj.getAgreementId())) {
            System.err.println("查询信息为空 = " + obj);
            return getDataTable(Collections.emptyList());
        }
        try {
            SltAgreementInfo sltAgreementInfo = new SltAgreementInfo();
            sltAgreementInfo.setAgreementId(obj.getAgreementId());
            List<SltAgreementInfo> repairList = sltAgreementInfoService.getRepairList(sltAgreementInfo);
            return getDataTable(repairList);
        } catch (NumberFormatException e) {
            System.err.println("数据错误 = " + e.getMessage());
            throw new ServiceException("数据查询异常，请联系运维人员查询日志处理");
        }
    }

    /**
     * 根据协议ID查询结算的丢失费用明细
     * @param obj 查询条件
     */
    @GetMapping("/getLoseCostsByAgreementId")
    @ApiOperation("根据协议ID查询丢失费用结算明细--不分页")
    public TableDataInfo getLoseCostsByAgreementId(IwsCostPushBean obj) {
        if (Objects.isNull(obj) || Objects.isNull(obj.getAgreementId())) {
            System.err.println("查询信息为空 = " + obj);
            return getDataTable(Collections.emptyList());
        }
        SltAgreementInfo sltAgreementInfo = new SltAgreementInfo();
        try {
            sltAgreementInfo.setAgreementId(obj.getAgreementId());
            List<SltAgreementInfo> loseList = sltAgreementInfoService.getLoseList(sltAgreementInfo);
            return getDataTable(loseList);
        } catch (NumberFormatException e) {
            System.err.println("数据错误 = " + e.getMessage());
            throw new RuntimeException("数据查询异常，请联系运维人员查询日志处理");
        }
    }

    /**
     * 根据协议ID查询结算的报废费用明细
     * @param obj 查询条件
     */
    @GetMapping("/getScrapCostsByAgreementId")
    @ApiOperation("根据协议ID查询报废费用结算明细--不分页")
    public TableDataInfo getScrapCostsByAgreementId(IwsCostPushBean obj) {
        if (Objects.isNull(obj) || Objects.isNull(obj.getAgreementId())) {
            System.err.println("查询信息为空 = " + obj);
            return getDataTable(Collections.emptyList());
        }
        SltAgreementInfo sltAgreementInfo = new SltAgreementInfo();
        try {
            sltAgreementInfo.setAgreementId(obj.getAgreementId());
            List<SltAgreementInfo> scrapList = sltAgreementInfoService.getScrapList(sltAgreementInfo);
            return getDataTable(scrapList);
        } catch (NumberFormatException e) {
            System.err.println("数据错误 = " + e.getMessage());
            throw new ServiceException("数据查询异常，请联系运维人员查询日志处理");
        }
    }

    @PostMapping("/computeTheMonthCost")
    @ApiOperation("计算当月费用")
    public AjaxResult computeTheMonthCost(@RequestBody IwsCostPushBean obj) {
        return iwsCostPushService.computeTheMonthCost(obj);
    }

    /**
     * 根据工程查询领用信息
     * @author jsk
     * @param info
     * @return
     */
    @ApiOperation(value = "根据工程查询领用信息")
    @GetMapping("/getProLeaseInfo")
    public AjaxResult getProLeaseInfo(IwsCostPushBean info) {
        startPage();
        List<IwsCostPushBean> list = iwsCostPushService.getProLeaseInfo(info);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 根据机具类型查询机具列表接口
     * @author jsk
     * @param info
     * @return
     */
    @ApiOperation(value = "根据机具类型查询机具列表接口")
    @GetMapping("/getDeviceInfoPageByMaType")
    public AjaxResult getEquipmentListByType(IwsCostPushBean info) {
        startPage();
        List<MaterialRetainedEquipmentInfo> list = iwsCostPushService.getEquipmentListByType(info);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 根据工程/往来单位/协议号查询机具信息
     * @author jsk
     * @param info
     * @return
     */
    @ApiOperation(value = "根据工程/往来单位/协议号查询机具信息")
    @GetMapping("/getDeviceInfoPageByAgreementProject")
    public AjaxResult getEquipmentListByAgreementCode(IwsCostPushBean info) {
        startPage();
        List<MaterialRetainedEquipmentInfo> list = iwsCostPushService.getEquipmentListByAgreementCode(info);
        return AjaxResult.success(getDataTable(list));
    }
}
