package org.dromara.zjk.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.zjk.domain.ZjkExpert;
import org.dromara.zjk.domain.ZjkExpertItem;
import org.dromara.zjk.domain.ZjkItemExtreation;
import org.dromara.zjk.domain.ZjkReviewPhase;
import org.dromara.zjk.domain.bo.ZjkItemExtreationBo;
import org.dromara.zjk.domain.vo.ZjkExpertVo;
import org.dromara.zjk.domain.vo.ZjkItemExtreationVo;
import org.dromara.zjk.domain.vo.ZjkProductVo;
import org.dromara.zjk.domain.vo.ZjkReviewPhaseVo;
import org.dromara.zjk.mapper.*;
import org.dromara.zjk.service.IZjkItemExtreationService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 抽取Service业务层处理
 *
 * @author ygh
 * @date 2024-10-29
 */
@RequiredArgsConstructor
@Service
public class ZjkItemExtreationServiceImpl implements IZjkItemExtreationService {

    @Resource
    private final ZjkItemExtreationMapper baseMapper;

    @Resource
    private final ZjkProductMapper zjkProductMapper;

    @Resource
    private final ZjkExpertItemMapper zjkExpertItemMapper;

    @Resource
    private final ZjkExpertMapper zjkExpertMapper;

    @Resource
    private final ZjkReviewPhaseMapper zjkReviewPhaseMapper;

    /**
     * 查询抽取
     *
     * @param id 主键
     * @return 抽取
     */
    @Override
    public ZjkItemExtreationVo queryById(Long id) {
        try {
            ZjkItemExtreationVo zjkItemExtreationVo = baseMapper.selectVoById(id);
            //项目信息
            ZjkProductVo zjkProjectVo = zjkProductMapper.selectVoById(zjkItemExtreationVo.getItemId());
            zjkItemExtreationVo.setZjkProductVo(zjkProjectVo);
            //抽取条件详情
            Long reviewId = zjkItemExtreationVo.getReviewId();
            LambdaQueryWrapper<ZjkReviewPhase> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(zjkItemExtreationVo.getReviewId() != null, ZjkReviewPhase::getId, reviewId);
            ZjkReviewPhase zjkReviewPhase = zjkReviewPhaseMapper.selectOne(queryWrapper1);
            //获取专家信息
            LambdaQueryWrapper<ZjkExpert> queryWrapper = new LambdaQueryWrapper();
            LambdaQueryWrapper<ZjkExpertItem> lambdaQueryWrapper = new LambdaQueryWrapper();
            List<ZjkExpertItem> zjkExpertItems = new ArrayList<>();

            //转化为，拼接
            if (zjkReviewPhase.getDesignatedNumber() != null && zjkReviewPhase.getDesignatedNumber().length() >= 1) {
                String substring = zjkReviewPhase.getDesignatedNumber().substring(1, zjkReviewPhase.getDesignatedNumber().length() - 1);
                zjkReviewPhase.setDesignatedNumber(substring);
            }
            //指定专家和屏蔽专家的集合
            String avoidanceExpert = zjkReviewPhase.getAvoidanceExpert();
            List<String> list = new ArrayList<>();
            if (avoidanceExpert != null) {
                String substring = avoidanceExpert.substring(1, zjkReviewPhase.getAvoidanceExpert().length() - 1);
                zjkReviewPhase.setAvoidanceExpert(substring);
                String[] phoneNumberArray = avoidanceExpert.replace("[", "").replace("]", "").split(", ");
                List<String> phoneNumbersList = Arrays.asList(phoneNumberArray);
                list.addAll(phoneNumbersList);
            }
            String designatedNumber = zjkReviewPhase.getDesignatedNumber();
            if (designatedNumber != null) {
                String[] designatedNumberArray = designatedNumber.replace("[", "").replace("]", "").split(", ");
                List<String> designatedNumberList = Arrays.asList(designatedNumberArray);
                list.addAll(designatedNumberList);
            }
            if (list != null && list.size() > 0) {
                LambdaQueryWrapper<ZjkExpert> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.in(ZjkExpert::getExpertId, list);
                List<ZjkExpert> zjkExperts = zjkExpertMapper.selectList(lambdaQueryWrapper1);
                zjkItemExtreationVo.setDesignatedNumbers(zjkExperts);
            }
            String avoidanceUnit = zjkReviewPhase.getAvoidanceUnit();
            if (avoidanceUnit != null && avoidanceUnit.length() > 1) {
                String newString = avoidanceUnit.substring(1, avoidanceUnit.length() - 1);
                if (newString != null && !newString.equals("")) {
                    zjkReviewPhase.setAvoidanceUnit(newString);
                } else {
                    zjkReviewPhase.setAvoidanceUnit(null);
                }
                String[] avoidanceUnitArray = avoidanceUnit.replace("[", "").replace("]", "").split(", ");
                List<String> avoidanceUnitList = Arrays.asList(avoidanceUnitArray);
                LambdaQueryWrapper<ZjkExpert> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.in(ZjkExpert::getWorkUnit, avoidanceUnitList);
                List<ZjkExpertVo> vos = zjkExpertMapper.selectVoList(lambdaQueryWrapper1);
                zjkItemExtreationVo.setAvoidanceUnitList(vos);
            }
            zjkItemExtreationVo.setZjkReviewPhase(zjkReviewPhase);
            lambdaQueryWrapper.eq(reviewId != null, ZjkExpertItem::getReviewId, reviewId);
//                lambdaQueryWrapper.ne(ZjkExpertItem::getAcceptStatus, 2);
//                lambdaQueryWrapper.eq(ZjkExpertItem::getLeaveStatus, 0);
            zjkExpertItems = zjkExpertItemMapper.selectList(lambdaQueryWrapper);
            //获取专家信息
            if (!zjkExpertItems.isEmpty()) {
                List<Long> idList = zjkExpertItems.stream()
                    .peek(item -> {
                        if (item.getLeaveStatus().equals("1")) {
                            item.setAcceptStatus("3");
                        }
                    })
                    .map(ZjkExpertItem::getExpertId)
                    .collect(Collectors.toList());
                Map<Long, String> collect = zjkExpertItems.stream()
                    .peek(item -> {
                        if (item.getLeaveStatus() != null && item.getLeaveStatus().equals("1")) {
                            item.setAcceptStatus("3");
                        }
                        if (item.getAcceptStatus() == null) {
                            item.setAcceptStatus("*");
                        }
                    })
                    .collect(Collectors.toMap(ZjkExpertItem::getExpertId,
                        item -> item.getAcceptStatus() + "-" + item.getIsSource(),
                        (oldValue, newValue) -> oldValue));
                queryWrapper.in(ZjkExpert::getExpertId, idList);
                List<ZjkExpertVo> zjkExpertVos = zjkExpertMapper.selectVoList(queryWrapper);
                for (ZjkExpertVo zjkExpertVo : zjkExpertVos) {
                    String s = collect.get(zjkExpertVo.getExpertId());
                    if (s != null) {
                        String[] split = s.split("-");
                        List<Integer> list1 = Arrays.stream(split).map(Integer::parseInt).collect(Collectors.toList());
                        zjkExpertVo.setAcceptStatus(list1.get(0));
                        zjkExpertVo.setIsSource(list1.get(1));
                    }
                    //2024/12/3 add操作 在expert专家的信息中加上 zjk expertitem中对应的extraction_status
                    //查询抽取状态  根据项目id 专家id 规则id 查询到记录
                    LambdaQueryWrapper<ZjkExpertItem> zjkExpertItemLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    zjkExpertItemLambdaQueryWrapper.eq(ZjkExpertItem::getItemId, zjkItemExtreationVo.getItemId());
                    zjkExpertItemLambdaQueryWrapper.eq(ZjkExpertItem::getExpertId, zjkExpertVo.getExpertId());
                    zjkExpertItemLambdaQueryWrapper.eq(ZjkExpertItem::getReviewId, zjkItemExtreationVo.getReviewId());
                    ZjkExpertItem zjkExpertItem = zjkExpertItemMapper.selectOne(zjkExpertItemLambdaQueryWrapper);
                    if (zjkExpertItem != null && zjkExpertItem.getId() != null) {//zjkExpertItem有记录有id   旧数据可能extractionstatus 抽取状态可能为null
                        zjkExpertVo.setExtractionStatus(zjkExpertItem.getExtractionStatus());
                    }
                }
                zjkItemExtreationVo.setZjkExpertVo(zjkExpertVos);
            }
            return zjkItemExtreationVo;
        } catch (Exception e) {
            throw new ServiceException("暂无记录");
        }
    }

    /**
     * 专家抽取查询列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 抽取分页列表
     */
    @Override
    public TableDataInfo<ZjkItemExtreationVo> queryPageList(ZjkItemExtreationBo bo, PageQuery pageQuery) {
        if (StringUtils.isEmpty(bo.getRecordsExpert())) {
            bo.setRecordsExpert("expert");
        }
        // 查询分页结果
        IPage<ZjkItemExtreationVo> zjkItemExtreationVoIPage = baseMapper.selectExtreationList(bo, pageQuery.build());
        List<ZjkItemExtreationVo> records = zjkItemExtreationVoIPage.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            return TableDataInfo.build(zjkItemExtreationVoIPage);
        }

        // 获取 itemId 的集合
        Set<Long> itemSet = records.stream().map(ZjkItemExtreationVo::getItemId).filter(Objects::nonNull).collect(Collectors.toSet());

        // 查询关联的产品信息并构建映射
        Map<Long, ZjkProductVo> productMap = zjkProductMapper.selectVoBatchIds(itemSet).stream().collect(Collectors.toMap(ZjkProductVo::getId, Function.identity(), (k1, k2) -> k1));

        // 获取 id 集合
        List<Long> idSet = records.stream().map(ZjkItemExtreationVo::getId).filter(Objects::nonNull).collect(Collectors.toList());

        // 查询关联的评审阶段信息并构建映射
        Map<Long, ZjkReviewPhase> reviewPhaseMap = zjkReviewPhaseMapper.selectList(new LambdaQueryWrapper<ZjkReviewPhase>().in(ZjkReviewPhase::getItemExtreationId, idSet))
            .stream().collect(Collectors.toMap(ZjkReviewPhase::getItemExtreationId, Function.identity(), (k1, k2) -> k1));

        // 合并数据到 records
        records.forEach(record -> {
            record.setZjkProductVo(productMap.get(record.getItemId()));
            record.setZjkReviewPhase(reviewPhaseMap.get(record.getId()));
        });
        return TableDataInfo.build(zjkItemExtreationVoIPage);
    }

    /**
     * 查询符合条件的抽取列表
     *
     * @param bo 查询条件
     * @return 抽取列表
     */
    @Override
    public List<ZjkItemExtreationVo> queryList(ZjkItemExtreationBo bo) {
        LambdaQueryWrapper<ZjkItemExtreation> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZjkItemExtreation> buildQueryWrapper(ZjkItemExtreationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZjkItemExtreation> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getItemId() != null, ZjkItemExtreation::getItemId, bo.getItemId());
        lqw.eq(bo.getExpertSum() != null, ZjkItemExtreation::getExpertSum, bo.getExpertSum());
        lqw.eq(bo.getExtractionCount() != null, ZjkItemExtreation::getExtractionCount, bo.getExtractionCount());
        lqw.eq(bo.getExtractedSum() != null, ZjkItemExtreation::getExtractedSum, bo.getExtractedSum());
        lqw.eq(bo.getExtractionStatus() != null, ZjkItemExtreation::getExtractionStatus, bo.getExtractionStatus());
        lqw.eq(bo.getExtractionTime() != null, ZjkItemExtreation::getExtractionTime, bo.getExtractionTime());
        lqw.eq(StringUtils.isNotBlank(bo.getExtractionUser()), ZjkItemExtreation::getExtractionUser, bo.getExtractionUser());
        lqw.eq(StringUtils.isNotBlank(bo.getExtractionSn()), ZjkItemExtreation::getExtractionSn, bo.getExtractionSn());
        return lqw;
    }

    /**
     * 新增抽取
     *
     * @param bo 抽取
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ZjkItemExtreationBo bo) {
        ZjkItemExtreation add = MapstructUtils.convert(bo, ZjkItemExtreation.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改抽取
     *
     * @param bo 抽取
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ZjkItemExtreationBo bo) {
        ZjkItemExtreation update = MapstructUtils.convert(bo, ZjkItemExtreation.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZjkItemExtreation entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除抽取信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public ZjkItemExtreationVo queryExtractionById(Long id) {
        ZjkItemExtreationVo zjkItemExtreationVo = baseMapper.selectVoById(id);
        //项目信息
        ZjkProductVo zjkProjectVo = zjkProductMapper.selectVoById(zjkItemExtreationVo.getItemId());
        zjkItemExtreationVo.setZjkProductVo(zjkProjectVo);
        List<ZjkReviewPhaseVo> zjkReviewPhaseVos = zjkReviewPhaseMapper.selectVoByExtreationId(id);

        for (ZjkReviewPhaseVo zjkReviewPhaseVo : zjkReviewPhaseVos) {
            String designatedNumber = zjkReviewPhaseVo.getDesignatedNumber();
            if(StringUtils.isNotBlank(designatedNumber)){
                designatedNumber = designatedNumber.replace("[", "").replace("]", "");
                zjkReviewPhaseVo.setDesignatedNumber(designatedNumber);
            }
        }


        ZjkReviewPhaseVo zjkReviewPhaseVo = zjkReviewPhaseVos.stream()
            .filter(vo -> vo.getEffective() == 1).findFirst().orElse(null);
        if (zjkReviewPhaseVo != null) {
            //获取专家信息
            LambdaQueryWrapper<ZjkExpert> queryWrapper = new LambdaQueryWrapper();
            LambdaQueryWrapper<ZjkExpertItem> lambdaQueryWrapper = new LambdaQueryWrapper();
            List<ZjkExpertItem> zjkExpertItems = new ArrayList<>();

            String unit = zjkReviewPhaseVo.getAvoidanceUnit();
            if(StringUtils.isNotBlank(unit)){
                unit = unit.replace("[", "").replace("]", "");
                zjkReviewPhaseVo.setAvoidanceUnit(unit);
            }
            //转化为，拼接
            if (zjkReviewPhaseVo.getDesignatedNumber() != null && zjkReviewPhaseVo.getDesignatedNumber().length() >= 1) {
                String designatedNumber = zjkReviewPhaseVo.getDesignatedNumber();
                designatedNumber = designatedNumber.replace("[", "").replace("]", "");
                zjkReviewPhaseVo.setDesignatedNumber(designatedNumber);
            }
            //指定专家和屏蔽专家的集合
            String avoidanceExpert = zjkReviewPhaseVo.getAvoidanceExpert();
            List<Long> list = new ArrayList<>();
            if (StringUtils.isNotBlank(avoidanceExpert)) {
                List<Long> avoidanceExpertList= JSONArray.parseArray(avoidanceExpert, Long.class);
                if (CollectionUtil.isNotEmpty(avoidanceExpertList)) {
                    list.addAll(avoidanceExpertList);
                }
                avoidanceExpert = avoidanceExpert.replace("[", "").replace("]", "");
                // 转回 JSON 字符串并设置到对象中
                zjkReviewPhaseVo.setAvoidanceExpert(avoidanceExpert);
            }
            String designatedNumber = zjkReviewPhaseVo.getDesignatedNumber();
            // 指定专家
            if (StringUtils.isNotBlank(designatedNumber)) {
                //designatedNumber = designatedNumber.replace("[", "").replace("]", "");
                //String[] parts = designatedNumber.split(",");
                //List<String> avoidanceUnitList = Arrays.asList(parts);
                designatedNumber = "["+designatedNumber+"]";
                //zjkReviewPhaseVo.setDesignatedNumber(designatedNumber);
                List<Long> designatedNumberList= JSONArray.parseArray(designatedNumber, Long.class);
                if (CollectionUtil.isNotEmpty(designatedNumberList)) {
                    list.addAll(designatedNumberList);
                }
            }
            if (CollectionUtil.isNotEmpty(list)){
                LambdaQueryWrapper<ZjkExpert> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.in(ZjkExpert::getExpertId, list);
                List<ZjkExpert> zjkExperts = zjkExpertMapper.selectList(lambdaQueryWrapper1);
                zjkItemExtreationVo.setDesignatedNumbers(zjkExperts);
            }
            // 回避单位
            //String avoidanceUnit = zjkReviewPhaseVo.getAvoidanceUnit();
            //if (StringUtils.isNotBlank(avoidanceUnit)) {
            //    avoidanceUnit = avoidanceUnit.replace("[", "").replace("]", "");
            //    String[] parts = avoidanceUnit.split(",");
            //    List<String> avoidanceUnitList = Arrays.asList(parts);
            //    if (CollectionUtil.isNotEmpty(avoidanceUnitList)) {
            //        LambdaQueryWrapper<ZjkExpert> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            //        lambdaQueryWrapper1.in(ZjkExpert::getWorkUnit, avoidanceUnitList);
            //        List<ZjkExpertVo> vos = zjkExpertMapper.selectVoList(lambdaQueryWrapper1);
            //        String workIds = vos.stream()
            //            .map(ZjkExpertVo::getWorkUnit)
            //            .collect(Collectors.joining(","));
            //        zjkItemExtreationVo.setAvoidanceUnits(workIds);
            //    }
            //}

            ZjkReviewPhase zjkReviewPhase = null;
            // 拷贝
            if (zjkReviewPhaseVo != null) {
                zjkReviewPhase = new ZjkReviewPhase();
                BeanUtils.copyProperties(zjkReviewPhaseVo, zjkReviewPhase);
            }

            zjkItemExtreationVo.setZjkReviewPhase(zjkReviewPhase);
            lambdaQueryWrapper.eq( ZjkExpertItem::getReviewId, zjkReviewPhaseVo.getId());
//                lambdaQueryWrapper.ne(ZjkExpertItem::getAcceptStatus, 2);
//                lambdaQueryWrapper.eq(ZjkExpertItem::getLeaveStatus, 0);
            zjkExpertItems = zjkExpertItemMapper.selectList(lambdaQueryWrapper);
            //获取专家信息
            if (!zjkExpertItems.isEmpty()) {
                List<Long> idList = zjkExpertItems.stream()
                    .peek(item -> {
                        if (item.getLeaveStatus().equals("1")) {
                            item.setAcceptStatus("3");
                        }
                    })
                    .map(ZjkExpertItem::getExpertId)
                    .collect(Collectors.toList());
                Map<Long, String> collect = zjkExpertItems.stream()
                    .peek(item -> {
                        if (item.getLeaveStatus() != null && item.getLeaveStatus().equals("1")) {
                            item.setAcceptStatus("3");
                        }
                        if (item.getAcceptStatus() == null) {
                            item.setAcceptStatus("*");
                        }
                    })
                    .collect(Collectors.toMap(ZjkExpertItem::getExpertId,
                        item -> item.getAcceptStatus() + "-" + item.getIsSource(),
                        (oldValue, newValue) -> oldValue));
                queryWrapper.in(ZjkExpert::getExpertId, idList);
                List<ZjkExpertVo> zjkExpertVos = zjkExpertMapper.selectVoList(queryWrapper);
                for (ZjkExpertVo zjkExpertVo : zjkExpertVos) {
                    String s = collect.get(zjkExpertVo.getExpertId());
                    if (s != null) {
                        String[] split = s.split("-");
                        List<Integer> list1 = Arrays.stream(split).map(Integer::parseInt).collect(Collectors.toList());
                        zjkExpertVo.setAcceptStatus(list1.get(0));
                        zjkExpertVo.setIsSource(list1.get(1));
                    }
                    //2024/12/3 add操作 在expert专家的信息中加上 zjk expertitem中对应的extraction_status
                    //查询抽取状态  根据项目id 专家id 规则id 查询到记录
                    LambdaQueryWrapper<ZjkExpertItem> zjkExpertItemLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    zjkExpertItemLambdaQueryWrapper.eq(ZjkExpertItem::getItemId, zjkItemExtreationVo.getItemId());
                    zjkExpertItemLambdaQueryWrapper.eq(ZjkExpertItem::getExpertId, zjkExpertVo.getExpertId());
                    zjkExpertItemLambdaQueryWrapper.eq(ZjkExpertItem::getReviewId, zjkItemExtreationVo.getReviewId());
                    ZjkExpertItem zjkExpertItem = zjkExpertItemMapper.selectOne(zjkExpertItemLambdaQueryWrapper);
                    if (zjkExpertItem != null && zjkExpertItem.getId() != null) {//zjkExpertItem有记录有id   旧数据可能extractionstatus 抽取状态可能为null
                        zjkExpertVo.setExtractionStatus(zjkExpertItem.getExtractionStatus());
                    }
                }
                zjkItemExtreationVo.setZjkExpertVo(zjkExpertVos);
            }
            zjkItemExtreationVo.setZjkReviewPhaseVoList(zjkReviewPhaseVos);
        }
        return zjkItemExtreationVo;
    }
}
