/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.rotationPlan.info.modular.businessrpreport.service.impl;
import java.text.SimpleDateFormat;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.rotationPlan.info.modular.businessrpreport.entity.BusinessQcQualityInspection;
import com.unis.rotationPlan.info.modular.businessrpreport.entity.BusinessRpInbound;
import com.unis.rotationPlan.info.modular.businessrpreport.entity.BusinessRpOutbound;
import com.unis.rotationPlan.info.modular.businessrpreport.entity.vo.BusinessRpReportVO;
import com.unis.rotationPlan.info.modular.businessrpreport.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.exception.CommonException;
import com.unis.rotationPlan.info.modular.businessrpreport.entity.BusinessRpReport;
import com.unis.rotationPlan.info.modular.businessrpreport.mapper.BusinessRpReportMapper;
import com.unis.rotationPlan.info.modular.businessrpreport.param.BusinessRpReportAddParam;
import com.unis.rotationPlan.info.modular.businessrpreport.param.BusinessRpReportEditParam;
import com.unis.rotationPlan.info.modular.businessrpreport.param.BusinessRpReportIdParam;
import com.unis.rotationPlan.info.modular.businessrpreport.param.BusinessRpReportPageParam;
import com.unis.rotationPlan.info.modular.businessrpreport.service.BusinessRpReportService;

import javax.annotation.Resource;
import java.time.Year;
import java.util.*;

import static com.unis.rotationPlan.info.modular.businessrpreport.util.DataConverter.convertData;

/**
 * 轮换计划-上报Service接口实现类
 *
 * @author ZeroLiYi
 * @date  2024/05/14 18:05
 **/
@Service
@Slf4j
public class BusinessRpReportServiceImpl extends ServiceImpl<BusinessRpReportMapper, BusinessRpReport> implements BusinessRpReportService {

    @Resource
    private BusinessRpReportMapper businessRpReportMapper;

    /**
     * 获取轮换计划接受列表
     * @param businessRpReportPageParam
     * @return
     */
    @Override
    public IPage<Map<String, Object>> page(BusinessRpReportPageParam businessRpReportPageParam) {
        //条形查询器
        QueryWrapper<BusinessRpReport> queryWrapper = new QueryWrapper<>();
        //分页相关
        if(StringUtils.isNotBlank(businessRpReportPageParam.getUnitName())){
            queryWrapper.like("b.dwmc",businessRpReportPageParam.getUnitName());
        }
        if(businessRpReportPageParam.getRotationYear()!=null){
            queryWrapper.like(" brr.rotation_year",businessRpReportPageParam.getRotationYear());
        }


        Page<BusinessRpReport> p =new Page<>(businessRpReportPageParam.getCurrent(),businessRpReportPageParam.getSize());
        IPage<Map<String,Object>> page = businessRpReportMapper.selectMyMapsPage(p,queryWrapper);
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BusinessRpReportAddParam businessRpReportAddParam) {
        BusinessRpReport businessRpReport = BeanUtil.toBean(businessRpReportAddParam, BusinessRpReport.class);
        this.save(businessRpReport);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BusinessRpReportEditParam businessRpReportEditParam) {
        BusinessRpReport businessRpReport = this.queryEntity(businessRpReportEditParam.getId());
        BeanUtil.copyProperties(businessRpReportEditParam, businessRpReport);
        this.updateById(businessRpReport);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BusinessRpReportIdParam> businessRpReportIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(businessRpReportIdParamList, BusinessRpReportIdParam::getId));
    }

    @Override
    public List<Map<String,Object>> detail(BusinessRpReportIdParam businessRpReportIdParam) {

        List<Map<String,Object>> details = businessRpReportMapper.getDetail(businessRpReportIdParam.getId());
        if(ObjectUtil.isEmpty(details)) {
            throw new CommonException("轮换计划-轮换半月报表不存在，id值为：{}", businessRpReportIdParam.getId());
        }
        return details;
    }

    @Override
    public BusinessRpReport queryEntity(Integer id) {
        BusinessRpReport businessRpReport = this.getById(id);
        if(ObjectUtil.isEmpty(businessRpReport)) {
            throw new CommonException("轮换计划-上报不存在，id值为：{}", id);
        }
        return businessRpReport;
    }
    /**
     * 轮换计划制定查询详情
     * @param businessRpReportIdParam
     * @return
     */
    @Override
    public Map<String,Object> createReport(BusinessRpReportIdParam businessRpReportIdParam) {
        List<BusinessRpReportVO> businessRpReports = businessRpReportMapper.createReportDetail(businessRpReportIdParam);
          // List<BusinessRpReportVO> businessRpReports = businessRpReportMapper.createReport(businessRpReportIdParam);
        List<TableColumns> list =new ArrayList<>();
        List<Map<String, Object>> list1=new ArrayList<>();
        Map<String, Object> sumByGrain = new HashMap<>();
        TableColumns tb =new TableColumns();
        Map<String,Object> tableColumnsMap = new HashMap<>();
        UnitInfo unitInfo =new UnitInfo();
        OrgInfo orgInfo=new OrgInfo();
        Map<String, Grain> grainMap = new HashMap<>();
        int index = 1; // Initialize index for dynamic indexing if needed
        Map<String, Map<String, Object>> sumByOrgId = new HashMap<>();
        // Process the list to identify unique grain types and build grain objects with columns
        for (BusinessRpReportVO report : businessRpReports) {
            String orgId = report.getOrgId()+"";


            String grainType = safeGetGrainType(report.getGrainVarietyName()); // Safely get the grain type

            if (grainType == null) {
                continue; // Skip if grain type cannot be determined
            }
            if(report.getDwmc()!=null){
                unitInfo.setTitle("单位名称");
                unitInfo.setAlign("center");
                unitInfo.setDataIndex("dwmc");
            }
            if(report.getOrgId()!=null){
                orgInfo.setTitle("存储库点");
                orgInfo.setAlign("center");
                orgInfo.setDataIndex("orgName");
            }


            Grain grain = grainMap.computeIfAbsent(grainType, k -> {
                Grain newGrain = new Grain();
                newGrain.setAlign("center");
                newGrain.setName("grainVarietyName");

                newGrain.setColumns(new ArrayList<>());
                return newGrain;
            });

            // Add columns only if there's corresponding quantity
            if (report.getOutboundQuantity() != null) {
                TableColumn outboundColumn = new TableColumn();
                outboundColumn.setTitle("轮出数量");
                outboundColumn.setAlign("center");
                // Use dynamic indexing if required
                outboundColumn.setDataIndex(report.getGrainVarietyId()+"outboundQuantity");
                grain.getColumns().add(outboundColumn);
            }
            if (report.getInboundQuantity() != null) {
                TableColumn inboundColumn = new TableColumn();
                inboundColumn.setTitle("轮入数量");
                inboundColumn.setAlign("center");
                inboundColumn.setDataIndex(report.getGrainVarietyId()+"inboundQuantity");
                grain.getColumns().add(inboundColumn);
            }
           sumByGrain = sumByOrgId.computeIfAbsent(orgId, k -> new HashMap<>());

            // 更新或设置非数量字段，确保使用最新的值
            sumByGrain.put("dwmc",report.getDwmc());
            sumByGrain.put("orgName",report.getOrgName());
            sumByGrain.put("grainVarietyName",report.getGrainVarietyName());
            sumByGrain.put(report.getGrainVarietyId()+"outboundQuantity", report.getOutboundQuantity());
            sumByGrain.put(report.getGrainVarietyId()+"inboundQuantity", report.getInboundQuantity());
            tableColumnsMap.put("unitInfo",unitInfo);
            tableColumnsMap.put("orgInfo",orgInfo);
            tableColumnsMap.put("grainMap",grainMap);

        }
        list1.addAll(sumByOrgId.values());
        tableColumnsMap.put("businessRpReports",list1);
        return tableColumnsMap;
    }

    @Override
    public  Tab reportList(BusinessRpReportIdParam businessRpReportIdParam) {

        if(businessRpReportIdParam.getRotationYear()==null){
            businessRpReportIdParam.setRotationYear(Year.now());
        }

        List<BusinessRpReportVO> businessRpReports = businessRpReportMapper.createReport(businessRpReportIdParam);
        List<BusinessRpReportVO> list =new ArrayList<>();

        List tc = new ArrayList<>();
        String name =null;
        Tab tab =new Tab();
        List<Map<String, Object>> list1=new ArrayList<>();
        Map<String, Object> sumByGrain = new HashMap<>();
        Map<String,Object> map =new HashMap<>();
        for (BusinessRpReportVO report : businessRpReports) {
            BusinessRpReportVO businessRpReportVO=new BusinessRpReportVO();
            if (report.getOutboundQuantity() != null) {
                TableColumn outboundColumn = new TableColumn();
                outboundColumn.setTitle(report.getGrainVarietyName()+"轮出数量");
                outboundColumn.setAlign("center");
                // Use dynamic indexing if required
                outboundColumn.setDataIndex(report.getGrainVarietyId());
                Date date =new Date();
                if( report.getRotationYear()!=null){
                    date = report.getRotationYear(); // 假设这是你获取到的 Date 对象
                }

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                String yearAsString = sdf.format(date);
                name =yearAsString+"年度省级政府储备粮轮换计划表";
//                map.put("name",name);
//                map.put("rotationYear",report.getRotationYear());
//                map.put(report.getGrainVarietyId(),report.getOutboundQuantity());
//                Double singleValue = report.getOutboundQuantity();

               // sumByGrain.get(report.getGrainVarietyId()).add(singleValue);
                sumByGrain.put("name",name);
                sumByGrain.put("rotationYear",yearAsString);
                sumByGrain.put(report.getGrainVarietyId(), report.getOutboundQuantity());
                businessRpReportVO.setName(name);
                businessRpReportVO.setRotationYear(report.getRotationYear());
                String key = report.getGrainVarietyName();

                businessRpReportVO.setOutboundQuantity(report.getOutboundQuantity());
                tc.add(outboundColumn);


            }
        }
        list1.add(sumByGrain);
        tab.setList((ArrayList) tc);
        tab.setBusinessRpReportVO(list1);
       // tab.setMap(map);
       // tab.setCombinedMap(sumByGrain);
        IPage<Tab> iPage =new Page();
        Page<Tab> p =new Page<>(1,20);
        return tab;
    }

    /**
     * 轮换计划接受详情
     * @param rpReportId
     * @param orgId
     * @return
     */
    @Override
    public BusinessRpReportVO getRpReportDetail(String rpReportId, Integer orgId) {
        BusinessRpReportVO businessRpReportRecVO =businessRpReportMapper.getRpReportByReportId(rpReportId,orgId);

        List<BusinessRpOutbound> outboundList = businessRpReportMapper.findOutByRpReportId(rpReportId,orgId);
        //businessRpReportRecVO.setBusinessRpOutboundList(outboundList);

        List<BusinessRpInbound> inboundList = businessRpReportMapper.findInByRpReportId(rpReportId,orgId);
        List<Map<String, Object>> convertedData = convertData(outboundList, inboundList);
        // 输出或进一步处理转换后的数据
        for (Map<String, Object> data : convertedData) {
            System.out.println(data);
        }
        businessRpReportRecVO.setComplexDataList(convertedData);


        //businessRpReportRecVO.setBusinessRpInboundList(inboundList);

        return businessRpReportRecVO;

    }

    /**
     * 根据货位号和检验类别查询质检报告
     * @param jylb
     * @param warehouseId
     * @return
     */
    @Override
    public List<BusinessQcQualityInspection> getQualityInspectionFindByWarehouseId(String jylb, Integer warehouseId) {

        List<BusinessQcQualityInspection> list =businessRpReportMapper.getQualityInspectionFindByWarehouseId(jylb,warehouseId);
        return list;
    }

    /**
     * 计划信息查询列表
     * @param pageParam
     * @return
     */
    @Override
    public List<Map<String, Object>> getRecList(BusinessRpReportPageParam pageParam) {
        List<Map<String, Object>> list = businessRpReportMapper.selectRecListByPageParam(pageParam);
        return list;
    }

    /**
     * 计划信息查询明细
     * @param rpReportId
     * @param orgId
     * @return
     */
    @Override
    public BusinessRpReportVO getPlanRpReportDetail(String rpReportId, Integer orgId) {
        //BusinessRpReportVO businessRpReportRecVO =businessRpReportMapper.getPlanRpReportByReportId(rpReportId,orgId);
        BusinessRpReportVO businessRpReportRecVO =new BusinessRpReportVO();
        List<BusinessRpOutbound> outboundList = businessRpReportMapper.findPlanOutByRpReportId(rpReportId,orgId);
        for (BusinessRpOutbound out:outboundList) {
            out.setZylx("出库");
        }
        businessRpReportRecVO.setBusinessRpOutboundList(outboundList);

        List<BusinessRpInbound> inboundList = businessRpReportMapper.findPlanInByRpReportId(rpReportId,orgId);
        for (BusinessRpInbound in:inboundList) {
            in.setZylx("出库");
        }
        businessRpReportRecVO.setBusinessRpInboundList(inboundList);

        return businessRpReportRecVO;
    }

    private static String safeGetGrainType(String varietyName) {
        return varietyName != null ? varietyName.split("及")[0] : null;
    }

    // Simulated method to fetch reports, replace with your actual method
    private static List<BusinessRpReportVO> fetchReportsFromDatabase() {
        return Collections.emptyList(); // Return actual data here
    }
}
