package com.ruoyi.project.business.service.quotation.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.ruoyi.common.enums.FileBuzType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.project.business.domain.*;
import com.ruoyi.project.business.domain.bo.quotation.SpecificationQueryBO;
import com.ruoyi.project.business.domain.vo.quotation.DescFileVO;
import com.ruoyi.project.business.domain.vo.quotation.ElevatorExportVO;
import com.ruoyi.project.business.domain.vo.quotation.NonStandardVO;
import com.ruoyi.project.business.domain.vo.quotation.SpecificationParamVO;
import com.ruoyi.project.business.domain.vo.quotation.SpecificationVO;
import com.ruoyi.project.business.enums.DelFlagEnum;
import com.ruoyi.project.business.enums.ParamTypeEnum;
import com.ruoyi.project.business.enums.QuotationStatusEnum;
import com.ruoyi.project.business.mapper.quotation.TqSpecificationMapper;
import com.ruoyi.project.business.mapper.quotation.TqSpecificationNonStandardMapper;
import com.ruoyi.project.business.service.ITbFileService;
import com.ruoyi.project.business.service.quotation.ITqQuotationService;
import com.ruoyi.project.business.service.quotation.ITqSpecificationDetailService;
import com.ruoyi.project.business.service.quotation.ITqSpecificationService;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-10
 */
@Service
public class TqSpecificationServiceImpl extends ServiceImpl<TqSpecificationMapper, TqSpecification> implements
    ITqSpecificationService {

    // 装潢包默认类别
    public static final String DECORATE = "99";

    @Resource
    private TqSpecificationMapper tqSpecificationMapper;

    @Resource
    private TqSpecificationNonStandardMapper tqSpecificationNonStandardMapper;

    @Resource
    private ITqSpecificationDetailService iTqSpecificationDetailService;

    @Resource
    private ITbFileService tbFileService;
    @Resource
    @Lazy
    private ITqQuotationService iTqQuotationService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public TqSpecification selectTqSpecificationById(Long id) {
        return tqSpecificationMapper.selectTqSpecificationById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param tqSpecification 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<SpecificationVO> selectTqSpecificationList(SpecificationQueryBO tqSpecification) {
        List<SpecificationVO> specificationVOS = tqSpecificationMapper.selectSpecificationVOList(tqSpecification);
        Map<Long, List<TbFile>> fileMap = CollectionUtils.isNotEmpty(specificationVOS) ?
                tbFileService.list(Wrappers.<TbFile>lambdaQuery()
                        .eq(TbFile::getBusinessType, FileBuzType.SPECIFICATION_CIVIL_IMG.getType())
                        .in(TbFile::getBusinessId, specificationVOS.stream().map(SpecificationVO::getId).collect(Collectors.toList()))
                        .eq(TbFile::getDelFlag, DelFlagEnum.NORMAL.getValue())
                ).stream().collect(Collectors.groupingBy(TbFile::getBusinessId)): Maps.newHashMap();
        specificationVOS.forEach(item -> {
            List<TbFile> files = fileMap.get(item.getId());
            if (CollectionUtils.isNotEmpty(files)){
                item.setFile(files.stream().map(TbFile::getFilePath).filter(StringUtils::isNotBlank).collect(Collectors.joining(",")));
            }
        });
        // 获取电梯的参数配置
        List<Long> collect = specificationVOS.stream().map(TqSpecification::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            // 获取非标描述
            List<TqSpecificationNonStandard> tqSpecificationNonStandards = tqSpecificationNonStandardMapper
                .selectList(Wrappers.<TqSpecificationNonStandard>lambdaQuery()
                    .eq(TqSpecificationNonStandard::getDelFlag, DelFlagEnum.NORMAL.getValue())
                    .in(TqSpecificationNonStandard::getSpecificationId, collect));
            List<Long> nonStandardDescIdList = tqSpecificationNonStandards.stream()
                .map(TqSpecificationNonStandard::getId)
                .collect(Collectors.toList());
            Map<Long, List<TqSpecificationNonStandard>> nonStandardMap = tqSpecificationNonStandards.stream()
                .collect(Collectors.groupingBy(TqSpecificationNonStandard::getSpecificationId));

            // 获取非标描述文件
            Map<Long, List<DescFileVO>> descFileVOMap = tbFileService.getDescFileVOMap(nonStandardDescIdList);
            specificationVOS.forEach(item -> {
                List<TqSpecificationNonStandard> orDefault = nonStandardMap.getOrDefault(item.getId(),
                    new ArrayList<>());
                List<NonStandardVO> nonStandardVOList = orDefault.stream().map(a -> {
                    NonStandardVO nonStandardVO = new NonStandardVO();
                    nonStandardVO.setNonStandardDesc(a.getNonStandardDesc());
                    // 非标描述文件
                    List<DescFileVO> orDefault1 = descFileVOMap.getOrDefault(a.getId(), new ArrayList<>());
                    nonStandardVO.setFileList(orDefault1);
                    return nonStandardVO;
                }).collect(Collectors.toList());
                item.setNonStandardList(nonStandardVOList);
            });
            // 普通参数
            List<TqSpecificationDetail> paramList = iTqSpecificationDetailService.list(
                Wrappers.<TqSpecificationDetail>lambdaQuery()
                    .in(TqSpecificationDetail::getSpecificationId, collect)
                    .eq(TqSpecificationDetail::getDelFlag, DelFlagEnum.NORMAL.getValue())
                    .isNull(TqSpecificationDetail::getParabarId)
            );
            Map<Long, List<TqSpecificationDetail>> paramMap = paramList.stream()
                .collect(Collectors.groupingBy(TqSpecificationDetail::getSpecificationId));
            specificationVOS.forEach(item -> {
                List<TqSpecificationDetail> orDefault = paramMap.getOrDefault(item.getId(), new ArrayList<>());
                List<SpecificationParamVO> paramVOList = orDefault.stream().map(SpecificationParamVO::covertNormal)
                    .collect(Collectors.toList());
                if (CollUtil.isNotEmpty(item.getParamList())) {
                    item.getParamList().addAll(paramVOList);
                } else {
                    item.setParamList(paramVOList);
                }
            });
            // 参数包参数
            List<TqSpecificationDetail> tqSpecificationDetailList = iTqSpecificationDetailService.list(
                Wrappers.<TqSpecificationDetail>lambdaQuery()
                    .in(TqSpecificationDetail::getSpecificationId, collect)
                    .eq(TqSpecificationDetail::getDelFlag, DelFlagEnum.NORMAL.getValue())
                    .isNotNull(TqSpecificationDetail::getParabarId)
            );
            Map<Long, List<TqSpecificationDetail>> parabarParamMap = tqSpecificationDetailList.stream()
                .collect(Collectors.groupingBy(TqSpecificationDetail::getSpecificationId));

            specificationVOS.forEach(item -> {
                List<TqSpecificationDetail> orDefault = parabarParamMap.getOrDefault(item.getId(), new ArrayList<>());
                List<SpecificationParamVO> convertList = orDefault.stream().map(SpecificationParamVO::covertParabar)
                    .collect(Collectors.toList());
                item.getParamList().addAll(convertList);
                // 参数包
                List<SpecificationParamVO> parabarParamList = new ArrayList<>();
                Map<Long, List<SpecificationParamVO>> collect1 = convertList.stream()
                    // 过滤非装潢包
                    .filter(a -> !DECORATE.equals(a.getParaCategory()))
                    .collect(Collectors.groupingBy(SpecificationParamVO::getParabarDetailId));
                for (Map.Entry<Long, List<SpecificationParamVO>> entry : collect1.entrySet()) {
                    SpecificationParamVO anyOne = entry.getValue().get(0);
                    SpecificationParamVO build = SpecificationParamVO.builder()
                        .paraCategory(anyOne.getParaCategory())
                        .paraCode(anyOne.getParabarId().toString())
                        .paraValue(anyOne.getParabarDetailId().toString())
                        .paramType(ParamTypeEnum.BAR.getCode())
                        .build();
                    parabarParamList.add(build);
                }
                item.getParamList().addAll(parabarParamList);
                item.setCreateTime1(item.getCreateTime());
            });
        }
        // 计算层站差价等信息
        TqQuotation tqQuotation = iTqQuotationService.getById(specificationVOS.get(0).getQuotationId());
        if (!QuotationStatusEnum.DRAFT.getCode().equals(tqQuotation.getQuotationStatus())){
            Boolean discountFlag = Objects.nonNull(tqQuotation.getDiscountFlag()) && tqQuotation.getDiscountFlag();
            BigDecimal exchangeRate = tqQuotation.getExchangeRate();
            specificationVOS.forEach(item -> {
                if (Objects.nonNull(item.getDefaultRate())){
                    BigDecimal discountRate = item.getDefaultRate().divide(new BigDecimal(100));
                    item.setFloorDiffPrice(item.getFloorDiffPrice().multiply(exchangeRate).multiply(discountFlag ? discountRate: new BigDecimal(1)).setScale(0, BigDecimal.ROUND_HALF_UP));
                    item.setOtherOptionalPrice(item.getOptionalPrice().subtract(item.getFloorDiffPrice()));
                }
            });
        }

        return specificationVOS;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param tqSpecification 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertTqSpecification(TqSpecification tqSpecification) {
        return tqSpecificationMapper.insertTqSpecification(tqSpecification);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param tqSpecification 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateTqSpecification(TqSpecification tqSpecification) {
        return tqSpecificationMapper.updateTqSpecification(tqSpecification);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTqSpecificationByIds(Long[] ids) {
        return tqSpecificationMapper.deleteTqSpecificationByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTqSpecificationById(Long id) {
        return tqSpecificationMapper.deleteTqSpecificationById(id);
    }

    @Override
    public List<SpecificationVO> listMoreByQuotationNoAndVersion(SpecificationQueryBO tqSpecification) {
        List<SpecificationVO> result = new ArrayList<>();
        List<SpecificationVO> specificationVOS = tqSpecificationMapper.listByQuotationNoAndVersion(tqSpecification);
        // 获取电梯的参数配置
        List<Long> collect = specificationVOS.stream().map(TqSpecification::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            // 普通参数
            List<TqSpecificationDetail> paramList = iTqSpecificationDetailService.list(
                Wrappers.<TqSpecificationDetail>lambdaQuery()
                    .in(TqSpecificationDetail::getSpecificationId, collect)
                    .eq(TqSpecificationDetail::getDelFlag, DelFlagEnum.NORMAL.getValue())
                    .isNull(TqSpecificationDetail::getParabarId)
            );
            Map<Long, List<TqSpecificationDetail>> paramMap = paramList.stream()
                .collect(Collectors.groupingBy(TqSpecificationDetail::getSpecificationId));
            specificationVOS.forEach(item -> {
                List<TqSpecificationDetail> orDefault = paramMap.getOrDefault(item.getId(), new ArrayList<>());
                List<SpecificationParamVO> paramVOList = orDefault.stream().map(SpecificationParamVO::covertNormal)
                    .collect(Collectors.toList());
                if (CollUtil.isNotEmpty(item.getParamList())) {
                    item.getParamList().addAll(paramVOList);
                } else {
                    item.setParamList(paramVOList);
                }
            });
        }
        specificationVOS.forEach(item -> {
            if (StringUtils.isNotBlank(item.getElevatorCode())) {
                String[] split = item.getElevatorCode().split(",");
                for (String itemElevatorCode : split) {
                    SpecificationVO one = new SpecificationVO();
                    BeanUtils.copyProperties(item, one);
                    one.setElevatorCode(itemElevatorCode);
                    result.add(one);
                }
            }
        });
        return result;
    }

    @Override
    public List<ElevatorExportVO> listElevatorExport(List<Long> quotationIdList) {
        return this.baseMapper.listElevatorExport(quotationIdList);
    }
}
