package com.casic.missiles.service.Impl.equipment;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.page.PageFactory;
import com.casic.missiles.dto.IdDTO;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.equipment.FixedAssetRequest;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.MeterFixedAssetsMapper;
import com.casic.missiles.mapper.equipment.EquipmentStandardSupportMapper;
import com.casic.missiles.model.equipment.EquipmentFixedAssets;
import com.casic.missiles.model.equipment.EquipmentStandardApplyEquipment;
import com.casic.missiles.model.equipment.EquipmentStandardEquipment;
import com.casic.missiles.model.equipment.EquipmentStandardSupportEquipment;
import com.casic.missiles.model.page.PageQuery;
import com.casic.missiles.service.equipment.IEquipmentStandardEquipmentService;
import com.casic.missiles.service.equipment.IEquipmentStandardSupportEquipmentService;
import com.casic.missiles.utils.DictCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 标准装置-标准配套设备表 服务实现类
 * </p>
 *
 * @author cuicheng
 * @since 2022-12-15
 */
@Service
public class EquipmentStandardSupportEquipmentServiceImpl extends ServiceImpl<EquipmentStandardSupportMapper, EquipmentStandardSupportEquipment> implements IEquipmentStandardSupportEquipmentService {

    @Autowired(required = false)
    private EquipmentStandardSupportMapper meterStandardSupportEquipmentMapper;

    @Autowired
    private IEquipmentStandardEquipmentService meterStandardEquipmentService;

    @Autowired(required = false)
    private MeterFixedAssetsMapper meterFixedAssetsMapper;

    @Override
    public Page<EquipmentStandardSupportEquipment> listPage(Page<EquipmentStandardSupportEquipment> page, IdDTO request) throws Exception {
        // 获取列表
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("standard_equipment_id", request.getId());
        // 通过标准装置id查询出关联的设备id
        Page<EquipmentStandardSupportEquipment> supportEquipmentPage = meterStandardSupportEquipmentMapper.selectPage(page, wrapper);
        if (!CollectionUtils.isEmpty(supportEquipmentPage.getRecords())) {
            // 配套设备的ids
            List<Long> ids = supportEquipmentPage.getRecords().stream()
                    .map(EquipmentStandardSupportEquipment::getEquipmentId).collect(Collectors.toList());
            FixedAssetRequest fixedAssetRequest = new FixedAssetRequest();
            fixedAssetRequest.setIds(ids);
            PageQuery pageQuery = new PageQuery();
            pageQuery.setPageNo(0);
            pageQuery.setPageSize(ids.size());
            Page<EquipmentFixedAssets> page1 = PageFactory.createPage(pageQuery);
            // 通过ids查询出对应的测量设备详细信息
            Page<EquipmentFixedAssets> meterFixedAssetsPage = meterFixedAssetsMapper.listPage(page1, fixedAssetRequest);
            Map<Long, EquipmentFixedAssets> existMap = CollectionUtils.newHashMap(ids.size());
            if (!CollectionUtils.isEmpty(meterFixedAssetsPage.getRecords())){
                existMap = meterFixedAssetsPage.getRecords().stream().collect(Collectors.toMap(EquipmentFixedAssets::getId, item -> item));
            }
            // 将对应的设备信息补充到返回参数中
            for (EquipmentStandardSupportEquipment record : supportEquipmentPage.getRecords()) {
                EquipmentFixedAssets meterFixedAssets = existMap.get(record.getEquipmentId());
                if(null != meterFixedAssets){
                    record.setSupportEquipmentId(record.getId());
                    BeanUtils.copyProperties(meterFixedAssets, record);
                    DictCodeUtils.convertDictCodeToName(record);
                }
            }
            // 将已经不存在的测量设备排除
            supportEquipmentPage.setRecords(supportEquipmentPage.getRecords().stream().filter(item -> StringUtils.isNotEmpty(item.getEquipmentNo())).collect(Collectors.toList()));
            supportEquipmentPage.setTotal(supportEquipmentPage.getRecords().size());
        }
        return supportEquipmentPage;
    }

    @Override
    public ReturnDTO add(EquipmentStandardSupportEquipment meterStandardSupportEquipment) throws Exception {
        // 配套信息校验
        validInfo(meterStandardSupportEquipment);
        // 首先判断是否存在，不存在再插入
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("standard_equipment_id", meterStandardSupportEquipment.getStandardEquipmentId());
        wrapper.eq("equipment_id", meterStandardSupportEquipment.getEquipmentId());

        EquipmentStandardSupportEquipment existUser = meterStandardSupportEquipmentMapper.selectOne(wrapper);
        if (existUser == null) {
            meterStandardSupportEquipmentMapper.insert(meterStandardSupportEquipment);
        }
        return ReturnUtil.success();
    }

    @Override
    public List<EquipmentStandardSupportEquipment> list(Long id) throws Exception {
        // 获取列表
        QueryWrapper<EquipmentStandardSupportEquipment> wrapper = new QueryWrapper<>();
        wrapper.eq("standard_equipment_id", id);
        // 通过标准装置id查询出关联的设备id
        List<EquipmentStandardSupportEquipment> supportEquipmentList = meterStandardSupportEquipmentMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(supportEquipmentList)) {
            // 配套设备的ids
            List<Long> ids = supportEquipmentList.stream()
                    .map(EquipmentStandardSupportEquipment::getEquipmentId).collect(Collectors.toList());
            FixedAssetRequest fixedAssetRequest = new FixedAssetRequest();
            fixedAssetRequest.setIds(ids);
            // 通过ids查询出对应的测量设备详细信息
            List<EquipmentFixedAssets> equipmentFixedAssetsList = meterFixedAssetsMapper.listPage(fixedAssetRequest);
            Map<Long, EquipmentFixedAssets> existMap = CollectionUtils.newHashMap(ids.size());
            if (!CollectionUtils.isEmpty(equipmentFixedAssetsList)){
                existMap = equipmentFixedAssetsList.stream().collect(Collectors.toMap(EquipmentFixedAssets::getId, item -> item));
            }
            // 将对应的设备信息补充到返回参数中
            for (EquipmentStandardSupportEquipment record : supportEquipmentList) {
                EquipmentFixedAssets meterFixedAssets = existMap.get(record.getEquipmentId());
                if(null != meterFixedAssets){
                    meterFixedAssets.setId(record.getId());
                    BeanUtils.copyProperties(meterFixedAssets, record);
                    DictCodeUtils.convertDictCodeToName(record);
                }
            }
        }
        return supportEquipmentList.stream().filter(item -> StringUtils.isNotEmpty(item.getEquipmentNo())).collect(Collectors.toList());
    }

    @Override
    public ReturnDTO batchDelete(List<Long> ids) {
        this.removeBatchByIds(ids);
        return ReturnUtil.success();
    }

    @Override
    public int deleteByList(List<EquipmentStandardApplyEquipment> equipmentStandardApplyEquipments, String standardEquipmentId) {
        return meterStandardSupportEquipmentMapper.deleteByList(equipmentStandardApplyEquipments, standardEquipmentId);
    }

    /**
     * 信息校验
     * @param meterStandardSupportEquipment
     * @return
     */
    private boolean validInfo (EquipmentStandardSupportEquipment meterStandardSupportEquipment) throws Exception {
        // 判断标准装置是否存在
        EquipmentStandardEquipment meterStandardEquipment = meterStandardEquipmentService.getById(meterStandardSupportEquipment.getStandardEquipmentId());
        if (meterStandardEquipment == null) {
            throw new BusinessException(BusinessExceptionEnum.STANDARD_EQUIPMENT_ID_EXIST);
        }
        // 判断标准配套设备是否存在
        EquipmentFixedAssets meterFixedAssets = meterFixedAssetsMapper.selectById(meterStandardSupportEquipment.getEquipmentId());
        if (meterFixedAssets == null) {
            throw new BusinessException(BusinessExceptionEnum.STANDARD_SUPPORT_EQUIPMENT_ID_EXIST);
        }
        return true;
    }
}
