package com.prolog.rdc.tms.service.impl.report;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.constant.BussinessConstant;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.dao.mapper.TmsLoadingBillDetailMapper;
import com.prolog.rdc.tms.dao.mapper.TmsLoadingBillHeaderMapper;
import com.prolog.rdc.tms.dao.mapper.TmsTemperatureDataMapper;
import com.prolog.rdc.tms.model.dto.DriverledgerBillDTO;
import com.prolog.rdc.tms.model.dto.report.YogurtOperationExportDTO;
import com.prolog.rdc.tms.model.dto.report.YogurtOperationReportDTO;
import com.prolog.rdc.tms.model.entity.SysRefdatadModel;
import com.prolog.rdc.tms.model.entity.TmsLoadingBillDetailModel;
import com.prolog.rdc.tms.model.entity.TmsLoadingBillHeaderModel;
import com.prolog.rdc.tms.model.entity.TmsTemperatureData;
import com.prolog.rdc.tms.model.vo.DriverledgerBillPageVO;
import com.prolog.rdc.tms.model.vo.report.YogurtOperationReportVO;
import com.prolog.rdc.tms.rmi.feign.ShipBillRecordFeign;
import com.prolog.rdc.tms.service.report.YogurtOperationReportService;
import com.prolog.rdc.tms.util.ConvertorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 酸奶运营统计报表实现层
 * <p>
 * Company: 湖北普罗格科技股份有限公司
 *
 * @author lhb
 * @since 2022/7/15 14:01
 */
@Slf4j
@Service
public class YogurtOperationReportServiceImpl implements YogurtOperationReportService {

    @Autowired
    private TmsLoadingBillHeaderMapper tmsLoadingBillHeaderMapper;

    @Autowired
    private TmsTemperatureDataMapper tmsTemperatureDataMapper;

    @Autowired
    private ConvertorUtil convertorUtil;

    @Autowired
    private ShipBillRecordFeign bmsBillRecordFeign;

    @Override
    public Page<YogurtOperationReportDTO> pageYogurtOperationReport(YogurtOperationReportVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        if (ToolKits.isEmpty(vo.getPageNum()) || ToolKits.isEmpty(vo.getPageSize())) {
            throw new PrologException("分页参数不能为空");
        }
        if (ToolKits.isNotEmpty(vo.getCargoOwnerName())) {
            if (vo.getCargoOwnerName().contains("其他")) {
                vo.setIsMilk("NO");
            } else {
                vo.setIsMilk("YES");
            }
        }
        vo.setUserType(user.getUserType());
        vo.setEnterpriseId(user.getEnterpriseId());
        if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {// 自有账号
            vo.setDepts(ToolKits.isEmpty(user.getDepts()) ? null : user.getDepts().stream().toArray(String[]::new));
            if (BussinessConstant.USER_DEPARTMENT_AUTH_Y.equals(user.getOwnedAllDataAuthFlag())) {// 部门权限
                vo.setIsDept("YES");
            } else {// 业务员权限
                vo.setIsDept("NO");
                // 货主
                vo.setConsignors(ToolKits.isEmpty(user.getConsignors()) ? null : user.getConsignors().stream().toArray(Long[]::new));
                // 客户
                vo.setCustomers(ToolKits.isEmpty(user.getCustomers()) ? null : user.getCustomers().stream().toArray(Long[]::new));
                // 供应商
                vo.setSuppliers(ToolKits.isEmpty(user.getSuppliers()) ? null : user.getSuppliers().stream().toArray(Long[]::new));
                // 仓库
                vo.setWsarehouses(ToolKits.isEmpty(user.getWarehouses()) ? null : user.getWarehouses().stream().toArray(Long[]::new));
            }
        } else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {// 承运商账号
            vo.setCarrierId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
        }
        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        List<YogurtOperationReportDTO> reportDTOS = tmsLoadingBillHeaderMapper.queryYogurtOperationReport(vo);

        if (ToolKits.isEmpty(reportDTOS)) {
            return null;
        }
        processData(reportDTOS,user);
        // 分页重组
        Page<YogurtOperationReportDTO> page = PageUtils.getPage(reportDTOS);
        return page;
    }

    public void processData(List<YogurtOperationReportDTO> reportDTOS,UserEntity user) {
        if (ToolKits.isEmpty(reportDTOS)) {
            return;
        }
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[] { DataDictionaryConstant.LOADING_BILL_STATUS});
        Criteria criteriaTemperature = Criteria.forClass(TmsTemperatureData.class);

        List<DriverledgerBillDTO> driverFees = Lists.newArrayList();
        List<String> loadingBillNos = reportDTOS.stream()
                                                .map(YogurtOperationReportDTO::getLoadingBillNo)
                                                .collect(Collectors.toList());
        if (ToolKits.isNotEmpty(loadingBillNos)) {
            DriverledgerBillPageVO vo = new DriverledgerBillPageVO();
            vo.setLoadingBillNos(loadingBillNos);
            RestMessage<List<DriverledgerBillDTO>> driverFeeRestMessage = bmsBillRecordFeign.queryDriverFeeByBillExecute(vo);

            if (driverFeeRestMessage.isSuccess()) {
                driverFees = driverFeeRestMessage.getData();
            }
        }

        for (YogurtOperationReportDTO reportDTO : reportDTOS) {
            reportDTO.setDisDate(reportDTO.getCreatetime());
            reportDTO.setStatusName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LOADING_BILL_STATUS, String.valueOf(reportDTO.getStatus())));
            if (ToolKits.isNotEmpty(driverFees)) {
                List<BigDecimal> fees =
                        driverFees.stream()
                                  .filter(fee -> reportDTO.getLoadingBillNo().equals(fee.getLoadingBillNo()))
                                  .map(DriverledgerBillDTO::getPayAmount)
                                  .collect(Collectors.toList());
                if (ToolKits.isNotEmpty(fees)) {
                    reportDTO.setTotalAmt(fees.get(0));
                }
            }

            if (DataDictionaryConstant.LOADING_BILL_STATUS_SD.intValue() <= reportDTO.getStatus().intValue()) {
                continue;
            }
            Restriction r1 = Restrictions.eq(TmsTemperatureData::getLoadingBillId, reportDTO.getLoadingBillId());
            Restriction r2 = Restrictions.eq(TmsTemperatureData::getEnterpriseId, user.getEnterpriseId());
            criteriaTemperature.setRestriction(Restrictions.and(r1, r2));
            criteriaTemperature.setOrder(Order.newInstance().desc(new String[] { "time" }));
            List<TmsTemperatureData> temperatureDataList = tmsTemperatureDataMapper.findByCriteria(criteriaTemperature);
            if (ToolKits.isNotEmpty(temperatureDataList)) {
                reportDTO.setTemperature(temperatureDataList.get(0).getTemperature());
            }
        }
    }

    @Override
    public List<YogurtOperationExportDTO> exportData(YogurtOperationReportVO vo) {
        ToolKits.isParamNull(vo, "查询请求不为空");
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");

        if (ToolKits.isNotEmpty(vo.getCargoOwnerName())) {
            if (vo.getCargoOwnerName().contains("其他")) {
                vo.setIsMilk("NO");
            } else {
                vo.setIsMilk("YES");
            }
        }
        vo.setUserType(user.getUserType());
        vo.setEnterpriseId(user.getEnterpriseId());
        if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {// 自有账号
            vo.setDepts(ToolKits.isEmpty(user.getDepts()) ? null : user.getDepts().stream().toArray(String[]::new));
            if (BussinessConstant.USER_DEPARTMENT_AUTH_Y.equals(user.getOwnedAllDataAuthFlag())) {// 部门权限
                vo.setIsDept("YES");
            } else {// 业务员权限
                vo.setIsDept("NO");
                // 货主
                vo.setConsignors(ToolKits.isEmpty(user.getConsignors()) ? null : user.getConsignors().stream().toArray(Long[]::new));
                // 客户
                vo.setCustomers(ToolKits.isEmpty(user.getCustomers()) ? null : user.getCustomers().stream().toArray(Long[]::new));
                // 供应商
                vo.setSuppliers(ToolKits.isEmpty(user.getSuppliers()) ? null : user.getSuppliers().stream().toArray(Long[]::new));
                // 仓库
                vo.setWsarehouses(ToolKits.isEmpty(user.getWarehouses()) ? null : user.getWarehouses().stream().toArray(Long[]::new));
            }
        } else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {// 承运商账号
            vo.setCarrierId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
        }
        List<YogurtOperationReportDTO> reportDTOS = null;
        reportDTOS = tmsLoadingBillHeaderMapper.queryYogurtOperationReport(vo);
        if (ToolKits.isEmpty(reportDTOS)) {
            return null;
        }
        List<YogurtOperationExportDTO> exportDTOS = Lists.newArrayList();
        processData(reportDTOS,user);
        if (ToolKits.isEmpty(reportDTOS)) {
            return null;
        }
        reportDTOS.stream().forEach(dto -> {
            YogurtOperationExportDTO exportDTO = new YogurtOperationExportDTO();
            BeanUtils.copyProperties(dto, exportDTO);
            exportDTOS.add(exportDTO);
        });
        return exportDTOS;
    }

    @Override
    public List<YogurtOperationExportDTO> exportPageData(YogurtOperationReportVO vo) {
        ToolKits.isParamNull(vo, "查询请求不为空");
        if (ToolKits.isEmpty(vo.getPageNum()) || ToolKits.isEmpty(vo.getPageSize())) {
            throw new PrologException("分页参数不能为空");
        }
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");

        if (ToolKits.isNotEmpty(vo.getCargoOwnerName())) {
            if (vo.getCargoOwnerName().contains("其他")) {
                vo.setIsMilk("NO");
            } else {
                vo.setIsMilk("YES");
            }
        }
        vo.setUserType(user.getUserType());
        vo.setEnterpriseId(user.getEnterpriseId());
        if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {// 自有账号
            vo.setDepts(ToolKits.isEmpty(user.getDepts()) ? null : user.getDepts().stream().toArray(String[]::new));
            if (BussinessConstant.USER_DEPARTMENT_AUTH_Y.equals(user.getOwnedAllDataAuthFlag())) {// 部门权限
                vo.setIsDept("YES");
            } else {// 业务员权限
                vo.setIsDept("NO");
                // 货主
                vo.setConsignors(ToolKits.isEmpty(user.getConsignors()) ? null : user.getConsignors().stream().toArray(Long[]::new));
                // 客户
                vo.setCustomers(ToolKits.isEmpty(user.getCustomers()) ? null : user.getCustomers().stream().toArray(Long[]::new));
                // 供应商
                vo.setSuppliers(ToolKits.isEmpty(user.getSuppliers()) ? null : user.getSuppliers().stream().toArray(Long[]::new));
                // 仓库
                vo.setWsarehouses(ToolKits.isEmpty(user.getWarehouses()) ? null : user.getWarehouses().stream().toArray(Long[]::new));
            }
        } else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {// 承运商账号
            vo.setCarrierId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
        }
        List<YogurtOperationReportDTO> reportDTOS = null;

        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        reportDTOS = tmsLoadingBillHeaderMapper.queryYogurtOperationReport(vo);
        if (ToolKits.isEmpty(reportDTOS)) {
            return null;
        }
        List<YogurtOperationExportDTO> exportDTOS = Lists.newArrayList();
        processData(reportDTOS,user);
        if (ToolKits.isEmpty(reportDTOS)) {
            return null;
        }
        reportDTOS.stream().forEach(dto -> {
            YogurtOperationExportDTO exportDTO = new YogurtOperationExportDTO();
            BeanUtils.copyProperties(dto, exportDTO);
            exportDTOS.add(exportDTO);
        });


        return exportDTOS;
    }
}
