package com.yuchen.saas.park.service.service.door.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuchen.saas.park.api.dto.door.DoorDeviceGroupDTO;
import com.yuchen.saas.park.api.entity.device.PmgBatSmartEquipment;
import com.yuchen.saas.park.api.entity.door.*;
import com.yuchen.saas.park.api.entity.door.DoorDeviceGroup;
import com.yuchen.saas.park.api.entity.door.config.DoorAccessControlConfigMapping;
import com.yuchen.saas.park.api.entity.park.PmgBatParkInfo;
import com.yuchen.saas.park.api.vo.door.DoorDeviceGroupVO;
import com.yuchen.saas.park.api.vo.door.DoorDeviceGroupVO;
import com.yuchen.saas.park.service.mapper.door.DoorDeviceGroupItemMapper;
import com.yuchen.saas.park.service.mapper.door.DoorDeviceGroupMapper;
import com.yuchen.saas.park.service.mapper.door.DoorHolidayGroupMapper;
import com.yuchen.saas.park.service.mapper.door.config.DoorAccessControlConfigMappingRepository;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import com.yuchen.saas.park.service.service.PmgBatSmartEquipmentService;
import com.yuchen.saas.park.service.service.door.DoorDeviceGroupItemService;
import com.yuchen.saas.park.service.service.door.DoorDeviceGroupService;
import com.yuchen.saas.park.service.service.door.DoorDevicePointService;
import com.yuchen.saas.payment.api.util.PageConverterUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.NestPage;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.BeanUtil;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 门禁分组 服务实现类
 * </p>
 *
 * @author miaoqs
 * @since 2023-12-20
 */
@Service
@Slf4j
public class DoorDeviceGroupServiceImpl extends BaseServiceImpl<DoorDeviceGroupMapper, DoorDeviceGroup> implements DoorDeviceGroupService {
    
    @Resource
    private DoorDeviceGroupItemService deviceGroupItemService;
    @Resource
    private DoorDevicePointService devicePointService;
    @Resource
    private PmgBatParkInfoService pmgBatParkInfoService;
    @Resource
    private PmgBatSmartEquipmentService batSmartEquipmentService;
    @Resource
    private DoorDeviceGroupItemMapper deviceGroupItemMapper;
    @Resource
    private DoorAccessControlConfigMappingRepository doorAccessControlConfigMappingRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdateByParam(DoorDeviceGroupDTO doorDeviceGroupDTO) {
        DoorDeviceGroup deviceGroup = new DoorDeviceGroup();
        BeanUtil.copyProperties(doorDeviceGroupDTO,deviceGroup);
        Long id = deviceGroup.getId();
        if(Func.isNotEmpty(doorDeviceGroupDTO.getDoorDeviceGroupItemList())) {
            deviceGroup.setNumber(doorDeviceGroupDTO.getDoorDeviceGroupItemList().size());
        }
        saveOrUpdate(deviceGroup);
        //移除原有门禁点
        if(Func.isNotEmpty(id)){
            deviceGroupItemService.remove(new LambdaQueryWrapper<DoorDeviceGroupItem>()
                    .eq(DoorDeviceGroupItem::getDeviceGroupId, id));
        }
        //新增门禁点
        if(Func.isNotEmpty(doorDeviceGroupDTO.getDoorDeviceGroupItemList())){
            List<DoorDeviceGroupItem> doorDeviceGroupItemList = doorDeviceGroupDTO.getDoorDeviceGroupItemList();
            for (DoorDeviceGroupItem item : doorDeviceGroupItemList) {
                item.setDeviceGroupId(deviceGroup.getId());
            }
            deviceGroupItemService.saveBatch(doorDeviceGroupItemList);
        }
        return true;
    }

    @Override
    public DoorDeviceGroupVO detailById(Long id) {
        DoorDeviceGroupVO deviceGroupVO = new DoorDeviceGroupVO();
        DoorDeviceGroup deviceGroup = getById(id);
        BeanUtil.copyProperties(deviceGroup,deviceGroupVO);
        //门禁点列表
        List<DoorDeviceGroupItem> itemList = deviceGroupItemService.list(new LambdaQueryWrapper<DoorDeviceGroupItem>()
                .eq(DoorDeviceGroupItem::getDeviceGroupId, id));
        if(Func.isNotEmpty(itemList)){
            List<Long> devicePointIdList = itemList.stream().map(DoorDeviceGroupItem::getDevicePointId).collect(Collectors.toList());
            List<DoorDevicePoint> devicePointList = devicePointService.listByIds(devicePointIdList);
            if(Func.isNotEmpty(devicePointList)){
                for (DoorDevicePoint devicePoint : devicePointList) {
                    //设备名称
                    PmgBatSmartEquipment equipment = batSmartEquipmentService.getById(devicePoint.getEquipmentId());
                    if(Func.isNotEmpty(equipment)){
                        devicePoint.setDeviceName(equipment.getName());
                    }
                    //园区名称
                    PmgBatParkInfo parkInfo = pmgBatParkInfoService.getById(devicePoint.getParkId());
                    if(Func.isNotEmpty(parkInfo)){
                        devicePoint.setParkName(parkInfo.getParkName());
                    }
                }
            }
            deviceGroupVO.setDoorDevicePointList(devicePointList);
        }
        return deviceGroupVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteById(Long id) throws Exception {
        String msg = "";
        //查询门禁分组是否被引用
        List<DoorAccessControlConfigMapping> mappingList = doorAccessControlConfigMappingRepository.selectList(new LambdaQueryWrapper<DoorAccessControlConfigMapping>()
                .eq(DoorAccessControlConfigMapping::getDoorAccessControlRefId, id));
        if(Func.isNotEmpty(mappingList)){
            log.info("======门禁分组被引用");
            msg = "门禁分组被引用";
            return msg;
        }

        removeById(id);
        deviceGroupItemService.remove(new LambdaQueryWrapper<DoorDeviceGroupItem>()
                .eq(DoorDeviceGroupItem::getDeviceGroupId, id));
        return msg;
    }

    @Override
    public String batchRemoveId(List<Long> idList) throws Exception {
        String msg = "";
        if(Func.isNotEmpty(idList)){
            for (Long id : idList) {
                msg = deleteById(id);
                if(Func.isNotEmpty(msg)){
                    break;
                }
            }
        }
        return msg;
    }

    @Override
    public NestPage<DoorDevicePoint> devicePointPage(Page<DoorDeviceGroupItem> page, PageDeviceGroupItemReqDTO req) {
        Page<DoorDevicePoint> devicePointPage = new Page<>();
        Page<DoorDeviceGroupItem> itemPage = deviceGroupItemMapper.devicePointList(page, req);
        if(Func.isNotEmpty(itemPage.getRecords())){
            List<Long> devicePointIdList = itemPage.getRecords().stream().map(DoorDeviceGroupItem::getDevicePointId).collect(Collectors.toList());
            Map<Long, Long> idMap = itemPage.getRecords().stream().collect(Collectors.toMap(DoorDeviceGroupItem::getDevicePointId, DoorDeviceGroupItem::getId));
            List<DoorDevicePoint> devicePointList = devicePointService.listByIds(devicePointIdList);
            if(Func.isNotEmpty(devicePointList)){
                for (DoorDevicePoint devicePoint : devicePointList) {
                    //设备名称
                    PmgBatSmartEquipment equipment = batSmartEquipmentService.getById(devicePoint.getEquipmentId());
                    if(Func.isNotEmpty(equipment)){
                        devicePoint.setDeviceName(equipment.getName());
                    }
                    //园区名称
                    PmgBatParkInfo parkInfo = pmgBatParkInfoService.getById(devicePoint.getParkId());
                    if(Func.isNotEmpty(parkInfo)){
                        devicePoint.setParkName(parkInfo.getParkName());
                    }
                    devicePoint.setId(idMap.get(devicePoint.getId()));
                }
            }
            BeanUtil.copyProperties(itemPage,devicePointPage);
            //转换中间表id
            devicePointPage.setRecords(devicePointList);
        }
        return PageConverterUtils.convert(devicePointPage);
    }

    @Override
    public List<DoorDeviceGroup> listByparam(DoorDeviceGroup doorDeviceGroup) {
        return list(new LambdaQueryWrapper<DoorDeviceGroup>()
                .like(DoorDeviceGroup::getGroupName,doorDeviceGroup.getGroupName()));
    }

}
