package com.yeejoin.equipmanage.service.impl;

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.google.common.collect.Lists;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.entity.dto.AssociatedEqpDTO;
import com.yeejoin.equipmanage.common.entity.vo.AssociatedEquipmentVO;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentDetailVO;
import com.yeejoin.equipmanage.mapper.*;
import com.yeejoin.equipmanage.service.IEquipmentCategoryService;
import com.yeejoin.equipmanage.service.IEquipmentSpecificRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author keyong
 * @title: EquipmentSpecificRelationServiceImpl
 * <pre>
 * @description: TODO
 * </pre>
 * @date 2021/1/14 14:10
 */
@Service
public class EquipmentSpecificRelationServiceImpl extends ServiceImpl<EquipmentSpecificRelationMapper, EquipmentSpecificRelation> implements IEquipmentSpecificRelationService {

    @Autowired
    EquipmentSpecificMapper equipmentSpecificMapper;

    @Autowired
    EquipmentDetailMapper equipmentDetailMapper;

    @Autowired
    EquipmentCategoryMapper equipmentCategoryMapper;

    @Autowired
    IndustryMapper industryMapper;

    @Autowired
    IEquipmentCategoryService iEquipmentCategoryService;

    @Autowired
    EquipmentSpecificRelationMapper equipmentSpecificRelationMapper;

    @Override
    public IPage<AssociatedEquipmentVO> getAssociatedEquipmentByPage(Page page, Long eqpSpecificId, Integer type) {
        return this.baseMapper.getAssociatedEquipmentPageList(page, eqpSpecificId, type);
    }

    @Override
    public List<EquipmentDetailVO> getAssociatedEqpList(Long eqpSpecificId, Integer type) {
        return this.baseMapper.getAssociatedEqpList(eqpSpecificId, type);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRelationEquipments(Long eqpSpecificId, List<Long> eqpSpecificIds) {
//        QueryWrapper eqpSpecificWrapper = new QueryWrapper();
//        eqpSpecificWrapper.in("equipment_detail_id", eqpSpecificIds);
//        List<EquipmentSpecific> equipmentSpecificList = equipmentSpecificMapper.selectList(eqpSpecificWrapper);
//        List<Long> eqpSpecificIdList = Lists.transform(equipmentSpecificList, EquipmentSpecific::getId);

        QueryWrapper<EquipmentSpecificRelation> delRelationWrapper = new QueryWrapper();
        delRelationWrapper.or(wrapper -> wrapper.eq("equipment_specific_id", eqpSpecificId).in(
                "relation_equipment_specific_id",
                eqpSpecificIds)).or(wrapper -> wrapper.eq("relation_equipment_specific_id", eqpSpecificId).in(
                "equipment_specific_id", eqpSpecificIds));
        equipmentSpecificRelationMapper.delete(delRelationWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindRelationEquipments(AssociatedEqpDTO dto) {
        // 删除并重新生成dto.eqpSpecificId对应的关联设备关系
        // 1.删除dto.eqpSpecificId对应的记录
        EquipmentSpecific eqpSpecific = equipmentSpecificMapper.selectById(dto.getEqpSpecificId());
        EquipmentDetail eqpDetail = equipmentDetailMapper.selectById(eqpSpecific.getEquipmentDetailId());
        EquipmentCategory eqpCategory = equipmentCategoryMapper.getByEqpDetailId(eqpDetail.getId());

        QueryWrapper<Industry> industryQueryWrapper = new QueryWrapper();
        industryQueryWrapper.lambda().eq(Industry::getCode, eqpCategory.getIndustryCode());
        Industry industry = industryMapper.selectList(industryQueryWrapper).get(0);

        List<Long> ids = equipmentSpecificRelationMapper.queryByRelatedEqpSpecIds(eqpSpecific.getId());

        QueryWrapper<EquipmentSpecificRelation> deleteWrapper = new QueryWrapper();
        deleteWrapper.eq("equipment_specific_id", eqpSpecific.getId()).eq("type", dto.getType());
        equipmentSpecificRelationMapper.delete(deleteWrapper);

        // 2.删除关联设备对应的关系记录
        if (!CollectionUtils.isEmpty(ids)) {
            equipmentSpecificRelationMapper.deleteBatchIds(ids);
        }

        // 3.保存dto.equipId对应新的关联设备关系
        if(CollectionUtils.isEmpty(dto.getRelatedEqpSpecificIds())) {
            return;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("id", dto.getRelatedEqpSpecificIds());
        List<EquipmentSpecific> eqpSpecificList = equipmentSpecificMapper.selectList(queryWrapper);
        List<Long> toBeSavedIdList = Lists.transform(eqpSpecificList, EquipmentSpecific::getId);

        if (!CollectionUtils.isEmpty(toBeSavedIdList)) {
            List<EquipmentSpecificRelation> esrList = Lists.newArrayList();
            toBeSavedIdList.forEach(id -> {
                // 4.保存对应相互关系（保存A设备关联B及B设备关联A的关系）
                EquipmentSpecificRelation eqpSpecRelation = new EquipmentSpecificRelation();
                eqpSpecRelation.setType(dto.getType().toString());
                eqpSpecRelation.setEquipmentSpecificId(eqpSpecific.getId());
                eqpSpecRelation.setRelationEquipmentSpecificId(id);
                esrList.add(eqpSpecRelation);

                EquipmentSpecificRelation eqpSpecRelation2 = new EquipmentSpecificRelation();

                eqpSpecRelation2.setType(industry.getCode());
                eqpSpecRelation2.setEquipmentSpecificId(id);
                eqpSpecRelation2.setRelationEquipmentSpecificId(eqpSpecific.getId());

                esrList.add(eqpSpecRelation2);
            });
            this.saveBatch(esrList);
        }
    }

    @Override
    public List<EquipmentDetailVO> getEqpDetailListByCategoryIdAndEqpName(Long categoryId, String eqpName) {
        List<Long> categoryIdList = iEquipmentCategoryService.getAllChildCategoryIdList(categoryId);
        categoryIdList.add(categoryId);
        return this.baseMapper.getEqpDetailCategoryIdAndName(categoryIdList, eqpName);
    }
}
