package com.clx.performance.service.impl.settle;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clx.performance.dao.settle.SettlementDriverDao;
import com.clx.performance.dao.settle.SettlementDriverDetailDao;
import com.clx.performance.enums.PerformanceResultEnum;
import com.clx.performance.enums.loan.OwnerLoanRecordEnum;
import com.clx.performance.enums.settle.SettlementDriverEnum;
import com.clx.performance.enums.settle.SettlementOrderChildRiskEnum;
import com.clx.performance.enums.settle.SettlementOwnerEnum;
import com.clx.performance.enums.settle.SettlementPlatformEnum;
import com.clx.performance.model.settle.SettlementDriver;
import com.clx.performance.model.settle.SettlementDriverDetail;
import com.clx.performance.param.pc.driver.BatchUpdatePayDriverSettlementParam;
import com.clx.performance.param.pc.driver.PageCarrierSettlementDriverParam;
import com.clx.performance.service.settle.SettlementDriverService;
import com.clx.performance.service.settle.SettlementMqHandlerService;
import com.clx.performance.struct.settle.SettlementDriverStruct;
import com.clx.performance.utils.excel.ExcelData;
import com.clx.performance.utils.excel.ExcelField;
import com.clx.performance.utils.excel.ExcelSheet;
import com.clx.performance.utils.excel.ExcelUtil;
import com.clx.performance.vo.pc.carrier.settle.CarrierPageSettlementDriverVO;
import com.clx.performance.vo.pc.carrier.settle.SettlementOrderChildRiskVO;
import com.msl.common.exception.ServiceSystemException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author liruixin
 * Date 2023-10-12
 * Time 09:43
 */
@Slf4j
@Service
@AllArgsConstructor
public class SettlementDriverServiceImpl implements SettlementDriverService {


    SettlementDriverDao settlementDriverDao;
    SettlementDriverDetailDao settlementDriverDetailDao;
    SettlementDriverStruct settlementDriverStruct;
    SettlementMqHandlerService settlementMqHandlerService;



    @Override
    public IPage<CarrierPageSettlementDriverVO> pageCarrierSettlementDriver(PageCarrierSettlementDriverParam param) {
        IPage<SettlementDriver> page = settlementDriverDao.pageCarrierSettlementDriver(param);
        List<CarrierPageSettlementDriverVO> list = settlementDriverStruct.covertList(
                page.getRecords());
        return new Page<CarrierPageSettlementDriverVO>().setRecords(list).setTotal(page.getTotal()).setPages(page.getPages());
    }

    @Override
    public void updateBatchPayDriverSettlement(BatchUpdatePayDriverSettlementParam param) {
        if(CollectionUtils.isEmpty(param.getIds())){
            throw new ServiceSystemException(PerformanceResultEnum.DATA_NOT_FIND,"参数不能为空");
        }
        List<SettlementDriverDetail> list = settlementDriverDetailDao.findByDriverSettlementIds(param.getIds());
        if(CollectionUtils.isEmpty(list)){
            throw new ServiceSystemException(PerformanceResultEnum.DATA_NOT_FIND);
        }
        if(!Objects.equals(param.getIds().size(),list.size())){
            throw new ServiceSystemException(PerformanceResultEnum.DATA_NOT_FIND,"所选数据有误，请重新选择");
        }
        StringBuffer returnMsg = new StringBuffer();
        list.forEach(item-> {
            String msg = settlementMqHandlerService.paySettlementDriver(item);
            if(StringUtils.isNotBlank(msg)){
                log.warn("结算单对应的的运单编号:{} 进行结算，结算失败，返回结果:{}",item.getChildNo(),msg);
                returnMsg.append(String.format("运单编号:【%s】结算失败，失败原因:【%s】;",item.getChildNo(),msg));
            }
        });
        if(StringUtils.isNotEmpty(returnMsg.toString())){
            throw new ServiceSystemException(PerformanceResultEnum.DATA_NOT_FIND,returnMsg.toString());
        }
    }

    @Override
    public SXSSFWorkbook exportSettlementDriver(PageCarrierSettlementDriverParam param) {
        param.setPage(1);
        param.setPageSize(1000000);
        IPage<CarrierPageSettlementDriverVO> settlementDriverPage = pageCarrierSettlementDriver(param);

        List<CarrierPageSettlementDriverVO> list = settlementDriverPage.getRecords();

        // 组装表头
        List<ExcelField> fieldList = new ArrayList<>();
        fieldList.add(new ExcelField(0, "运单编号", "childNo", 5000));
        fieldList.add(new ExcelField(1, "货单编号", "orderGoodsNo", 5000));
        fieldList.add(new ExcelField(2, "订单编号", "orderNo", 5000));
        fieldList.add(new ExcelField(3, "车主编码", "driverUserNo", 5000));
        fieldList.add(new ExcelField(4, "车主名称", "driverName", 5000));
        fieldList.add(new ExcelField(5, "货物名称", "goodsName", 5000));
        fieldList.add(new ExcelField(6, "预付标识", "prepayFreightFlag", 5000));
        fieldList.add(new ExcelField(7, "借款标识", "loanFlagMsg", 5000));
        fieldList.add(new ExcelField(8, "车牌号", "truckNo", 5000));
        fieldList.add(new ExcelField(9, "开票标识", "invoiceType", 5000));
        fieldList.add(new ExcelField(10, "实际净重（吨）", "weight", 5000));
        fieldList.add(new ExcelField(11, "运费单价", "freightPrice", 5000));
        fieldList.add(new ExcelField(12, "实际运费金额", "freight", 5000));
        fieldList.add(new ExcelField(13, "货损单价", "lossPrice", 5000));
        fieldList.add(new ExcelField(14, "货损吨数", "lossWeight", 5000));
        fieldList.add(new ExcelField(15, "货损金额", "lossFreight", 5000));
        fieldList.add(new ExcelField(16, "结算金额", "settlementFreight", 5000));
        fieldList.add(new ExcelField(17, "状态", "status", 5000));
        fieldList.add(new ExcelField(18, "结算结果", "settlementResult", 5000));
        fieldList.add(new ExcelField(19, "结算单号", "settlementNo", 5000));
        fieldList.add(new ExcelField(20, "结算平台", "settlementPlatform", 5000));
        fieldList.add(new ExcelField(21, "创建时间", "createTime", 5000));
        fieldList.add(new ExcelField(22, "开票公司", "invoicingCompanyShorterName", 5000));
        fieldList.add(new ExcelField(23, "毛利率", "grossMargin", 5000));
        fieldList.add(new ExcelField(24, "毛利润", "grossProfit", 5000));

        // 组装数据
        List<List<ExcelData>> dataList = new ArrayList<>();
        for (CarrierPageSettlementDriverVO vo : list) {
            List<ExcelData> rowData = new ArrayList<>();
            rowData.add(new ExcelData(vo.getChildNo()));
            rowData.add(new ExcelData(vo.getOrderGoodsNo()));
            rowData.add(new ExcelData(vo.getOrderNo()));
            rowData.add(new ExcelData(vo.getDriverUserNo()+""));

            rowData.add(new ExcelData(vo.getDriverName()));
            rowData.add(new ExcelData(vo.getGoodsName()));
            rowData.add(new ExcelData(vo.getPrepayFreightFlag()==null?null:SettlementDriverEnum.PrepayFreightFlag.getMsgByCode(vo.getPrepayFreightFlag())));

            rowData.add(new ExcelData(vo.getLoanFlagMsg()));
            rowData.add(new ExcelData(vo.getTruckNo()));
            rowData.add(new ExcelData(vo.getInvoiceType()==null?null:SettlementDriverEnum.InvoiceType.getMsgByCode(vo.getInvoiceType())));
            rowData.add(new ExcelData(vo.getWeight()));
            rowData.add(new ExcelData(vo.getFreightPrice()));

            rowData.add(new ExcelData(vo.getFreight()));
            rowData.add(new ExcelData(vo.getLossPrice()));
            rowData.add(new ExcelData(vo.getLossWeight()));
            rowData.add(new ExcelData(vo.getLossFreight()));
            rowData.add(new ExcelData(vo.getSettlementFreight()));

            rowData.add(new ExcelData(SettlementDriverEnum.Status.getMsgByCode(vo.getStatus())));
            rowData.add(new ExcelData("-"));
            rowData.add(new ExcelData(vo.getSettlementNo()));
            rowData.add(new ExcelData(SettlementPlatformEnum.Platform.getMsgByCode(Integer.parseInt(vo.getSettlementPlatform()))));
            rowData.add(new ExcelData(vo.getCreateTime()));

            rowData.add(new ExcelData(vo.getInvoicingCompanyShorterName()));
            rowData.add(new ExcelData("0"));
            rowData.add(new ExcelData("0"));

            dataList.add(rowData);
        }

        ExcelSheet excelSheet = new ExcelSheet("车主结算单", "车主结算单", fieldList, dataList);

        //创建excel
        return ExcelUtil.create(excelSheet);
    }

    public static String formatPayMsg(Integer settlementStatus,String payMsg) {
        if (!Objects.equals(settlementStatus, SettlementDriverEnum.Status.SETTLED.getCode()) || StringUtils.equals("success",payMsg)) {
            return null;
        }
        return payMsg;
    }

    public static String formatLoanMsg(Integer loanFlag) {
        if (Objects.equals(loanFlag, OwnerLoanRecordEnum.LoanFlag.LOAN.getCode())) {
            return OwnerLoanRecordEnum.LoanFlag.LOAN.getMsg();
        }else if (Objects.equals(loanFlag, OwnerLoanRecordEnum.LoanFlag.NO_LOAN.getCode())) {
            return OwnerLoanRecordEnum.LoanFlag.NO_LOAN.getMsg();
        } else if (Objects.equals(loanFlag, OwnerLoanRecordEnum.LoanFlag.RE_PAY.getCode())) {
            return OwnerLoanRecordEnum.LoanFlag.RE_PAY.getMsg();
        }
        return "无需借款";
    }
}
