package com.persagy.dmp.rwd.delivery.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.persagy.dmp.common.constant.ValidEnum;
import com.persagy.dmp.common.model.entity.BaseEntity;
import com.persagy.dmp.define.entity.ObjectInfoDefine;
import com.persagy.dmp.define.entity.ObjectTypeDefine;
import com.persagy.dmp.delivery.dto.ObjectTypeCollectDTO;
import com.persagy.dmp.delivery.entity.ObjectTypeCollect;
import com.persagy.dmp.rwd.define.service.IObjectTypeService;
import com.persagy.dmp.rwd.delivery.dao.ObjectTypeCollectMapper;
import com.persagy.dmp.rwd.delivery.service.IObjectTypeCollectService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目，现场交付范围管理-对象类型
 * @author:linhuili
 * @date:2021/10/13
 */
@Service
public class ObjectTypeCollectServiceImpl extends ServiceImpl<com.persagy.dmp.rwd.delivery.dao.ObjectTypeCollectMapper, ObjectTypeCollect> implements IObjectTypeCollectService {

    @Autowired
    private com.persagy.dmp.rwd.delivery.dao.ObjectTypeCollectMapper ObjectTypeCollectMapper;

    @Autowired
    private IObjectTypeService objectTypeService;

    /**
     * 数量统计
     * @param queryWrapper 查询条件
     * @return
     */
    @Override
    public Integer queryCount(Wrapper<ObjectTypeCollect> queryWrapper) {
        return ObjectTypeCollectMapper.selectCount(queryWrapper);
    }

    /**
     * 查询对象类型交付范围
     * @param queryWrapper 查询条件
     * @return
     */
    @Override
    public List<ObjectTypeCollect> queryByCondition(Wrapper<ObjectTypeCollect> queryWrapper) {
        return ObjectTypeCollectMapper.selectList(queryWrapper);
    }

    /**
     * 分页查询对象类型交付范围
     * @param page 分页条件
     * @param queryWrapper 查询条件
     * @return
     */
    @Override
    public Page queryByCondition(Page page, Wrapper<ObjectTypeCollect> queryWrapper) {
        //查询交付范围内的对象类型信息
        Page selectPage = ObjectTypeCollectMapper.selectPage(page, queryWrapper);
        List<ObjectTypeCollect> records = (List<ObjectTypeCollect>)selectPage.getRecords();
        if(CollUtil.isEmpty(records)){
            return selectPage;
        }
        Map<String, ObjectTypeDefine> typeDefineMap = queryDefineObjectType(records);

        List<ObjectTypeCollectDTO> result = new ArrayList<>();
        records.forEach(item->{
            ObjectTypeCollectDTO collectType = new ObjectTypeCollectDTO();
            //设置标准类型定义信息
            String defineTypeId = item.getDefineTypeId();
            if(StringUtils.isNotEmpty(defineTypeId)){
                ObjectTypeDefine objectTypeDefine = typeDefineMap.get(defineTypeId);
                if(objectTypeDefine != null){
                    BeanUtils.copyProperties(objectTypeDefine,collectType);
                }
            }
            BeanUtils.copyProperties(item,collectType);
            result.add(collectType);
        });
        selectPage.setRecords(result);
        return selectPage;
    }

    /**
     * 查询标准类型定义
     * @return
     */
    private Map<String, ObjectTypeDefine> queryDefineObjectType(List<ObjectTypeCollect> records){
        Set<String> ids = records.stream().map(ObjectTypeCollect::getDefineTypeId).collect(Collectors.toSet());
        QueryWrapper<ObjectTypeDefine> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        //queryWrapper.select("id","name");
        List<ObjectTypeDefine> objectTypeDefines = objectTypeService.queryByCondition(queryWrapper);
        if(CollUtil.isEmpty(objectTypeDefines)){
            return new HashMap<>();
        }
        return objectTypeDefines.stream().collect(Collectors.toMap(ObjectTypeDefine::getId, item->item, (k1, k2) -> k1));
    }

    /**
     * 设定对象类型交付范围
     * @param voList 待新增数据
     * @return
     */
    @Override
    public List<ObjectTypeCollect> insert(List<ObjectTypeCollect> voList) throws Exception{
        //填充信息点采集ID
        fillObjectTypeCollectId(voList);
        //新增采集信息点
        saveOrUpdateBatch(voList);
        return voList;
    }

    /**
     * 修改对象类型交付范围
     * @param voList 待修改数据
     * @return
     */
    @Override
    public List<ObjectTypeCollect> update(List<ObjectTypeCollect> voList) throws Exception {
        //填充信息点采集ID
        fillObjectTypeCollectId(voList);
        //修改采集信息点
        saveOrUpdateBatch(voList);
        return voList;
    }

    /**
     * 删除对象类型交付范围
     * @param idList 主键
     */
    @Override
    public void delete(List<String> idList) {
        if(CollUtil.isEmpty(idList)) {
            return;
        }
        List<ObjectTypeCollect> dbList = ObjectTypeCollectMapper.selectBatchIds(idList);
        Map<String, ObjectTypeCollect> dbMap = CollectionUtil.fieldValueMap(dbList, BaseEntity.PROP_ID);
        idList.forEach(id -> {
            ObjectTypeCollect dbVO = MapUtil.get(dbMap, id, ObjectTypeCollect.class);
            // 容错处理
            if(dbVO == null) {
                return;
            }
            // 删除
            ObjectTypeCollect vo = new ObjectTypeCollect();
            vo.setId(id);
            vo.setValid(ValidEnum.FALSE.getType());
            ObjectTypeCollectMapper.updateById(vo);
        });
    }

    /**
     * 填充已交付的对象类ID
     * @param voList
     */
    private void fillObjectTypeCollectId(List<ObjectTypeCollect> voList){
        if(CollUtil.isEmpty(voList)){
            return;
        }
        for (ObjectTypeCollect typeCollect : voList) {
            if(StringUtils.isNotEmpty(typeCollect.getId()) || StringUtils.isEmpty(typeCollect.getDefineTypeId())){
                continue;
            }
            //查询采集信息点
            LambdaQueryWrapper<ObjectTypeCollect> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ObjectTypeCollect::getGroupCode,typeCollect.getGroupCode());
            wrapper.eq(ObjectTypeCollect::getProjectId,typeCollect.getProjectId());
            wrapper.eq(ObjectTypeCollect::getDeliveryType,typeCollect.getDeliveryType());
            wrapper.eq(ObjectTypeCollect::getDefineTypeId,typeCollect.getDefineTypeId());
            wrapper.eq(ObjectTypeCollect::getValid,true);
            List<ObjectTypeCollect> ObjectTypeCollects = queryByCondition(wrapper);
            if(CollUtil.isEmpty(ObjectTypeCollects)){
                //信息点未被采集
                continue;
            }else{
                //信息点已采集
                typeCollect.setId(ObjectTypeCollects.get(0).getId());
            }
        }
    }
}
