package com.yuchen.saas.park.service.service.elevator.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.elevator.*;
import com.yuchen.saas.park.api.entity.elevator.SaasParkElevatorManageLocationEntity;
import com.yuchen.saas.park.api.entity.elevator.SaasParkElevatorPermissionElevatorGroup;
import com.yuchen.saas.park.api.request.ElevatorPointGroupReq;
import com.yuchen.saas.park.api.request.ElevatorTreeRequest;
import com.yuchen.saas.park.api.response.ElevatorPointResponse;
import com.yuchen.saas.park.api.vo.elevator.ElevatorPointGroupVO;
import com.yuchen.saas.park.service.mapper.elevator.SaasParkElevatorManageLocationMapper;
import com.yuchen.saas.park.service.mapper.elevator.SaasParkElevatorPermissionElevatorGroupMapper;
import com.yuchen.saas.park.service.service.elevator.ISaasParkElevatorPermissionElevatorGroupService;
import com.yuchen.saas.park.service.wrapper.ElevatorGroupWrapper;
import lombok.extern.slf4j.Slf4j;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
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.nest.springwrap.core.tool.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 梯控分组 服务实现类
 * </p>
 *
 * @author baichaojie
 * @since 2024-07-08
 */
@Service
@Slf4j
public class SaasParkElevatorPermissionElevatorGroupServiceImpl extends BaseServiceImpl<SaasParkElevatorPermissionElevatorGroupMapper, SaasParkElevatorPermissionElevatorGroup> implements ISaasParkElevatorPermissionElevatorGroupService {


    @Autowired
    private ElevatorGroupWrapper elevatorGroupWrapper;
    @Autowired
    private SaasParkElevatorManageLocationMapper saasParkElevatorManageLocationMapper;

    @Override
    public IPage<PermissionDTO> tree(Page<ElevatorTreeRequest> pageReq, ElevatorTreeRequest req) {

        IPage<PermissionDTO> iPagePermissionDTO = new Page<>();

        Page<SaasParkElevatorPermissionElevatorGroup> page = new Page<>(pageReq.getCurrent(), pageReq.getSize());
        LambdaQueryWrapper<SaasParkElevatorPermissionElevatorGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Func.isNotEmpty(req.getParkId()), SaasParkElevatorPermissionElevatorGroup::getParkId, req.getParkId());
        Page<SaasParkElevatorPermissionElevatorGroup> page1 = this.page(page, wrapper);

        List<SaasParkElevatorPermissionElevatorGroup> records = page1.getRecords();
        List<PermissionDTO> permissionDTOList = new ArrayList<>();
        PermissionDTO permissionDTO = new PermissionDTO();
        permissionDTO.setLabel("所有");
        permissionDTO.setId("0");
        permissionDTO.setIsSelected(false);
        permissionDTO.setIsDisabled(false);
        List<GroupDTO> groupList = new ArrayList<>();
        for (SaasParkElevatorPermissionElevatorGroup group : records) {
            GroupDTO groupDTO = new GroupDTO();
            groupDTO.setIsSelected(false);
            groupDTO.setIsDisabled(false);
            groupDTO.setId(permissionDTO.getId() + "_" + group.getId() + "");
            groupDTO.setGroupId(group.getId());
            groupDTO.setLabel(group.getGroupName());

            groupDTO.setChildren(getPoint(group.getElevatorRange(), groupDTO.getId()));
            groupList.add(groupDTO);
        }
        permissionDTO.setChildren(groupList);

        permissionDTOList.add(permissionDTO);

        iPagePermissionDTO.setRecords(permissionDTOList);
        return iPagePermissionDTO;

    }

    public List<DeviceDTO> getPoint(String strPoint, String id) {
        if (strPoint == null) {
            return null;
        }
        String[] strPointList = strPoint.split(",");
        List<String> list = new ArrayList<>(Arrays.asList(strPointList));
        List<SaasParkElevatorManageLocationEntity> listByIds = saasParkElevatorManageLocationMapper.getListByIds(list);

        List<DeviceDTO> deviceList = new ArrayList<>();
        for (SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity : listByIds) {
            DeviceDTO deviceDTO = new DeviceDTO();
            deviceDTO.setId(id + "_" + saasParkElevatorManageLocationEntity.getId() + "");
            deviceDTO.setDeviceId(saasParkElevatorManageLocationEntity.getId());
            deviceDTO.setLabel(saasParkElevatorManageLocationEntity.getElevatorName());
            deviceDTO.setIsSelected(false);
            deviceDTO.setIsDisabled(false);

            deviceDTO.setChildren(getFloor(saasParkElevatorManageLocationEntity.getStartFloor(), saasParkElevatorManageLocationEntity.getEndFloor(), deviceDTO.getId()));
            deviceList.add(deviceDTO);
        }
        return deviceList;

    }


    private List<FloorDTO> getFloor(Integer start, Integer end, String id) {

        List<FloorDTO> listFloorDTO = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            FloorDTO floorDTO = new FloorDTO();
            floorDTO.setId(id + "_" + Long.parseLong(i + ""));
            floorDTO.setFloorId(Long.parseLong(i + ""));

            floorDTO.setLabel(i + "层");
            floorDTO.setIsSelected(false);
            floorDTO.setIsDisabled(false);

            if (i != 0) {
                listFloorDTO.add(floorDTO);
            }
        }
        return listFloorDTO;
    }




    @Override
    public IPage<ElevatorPointGroupVO> pageByParam(Page<ElevatorPointGroupReq> pageReq, ElevatorPointGroupReq req) {
        IPage<ElevatorPointGroupVO> voPages = new Page<>();

        Page<SaasParkElevatorPermissionElevatorGroup> page = new Page<>(pageReq.getCurrent(), pageReq.getSize());
        LambdaQueryWrapper<SaasParkElevatorPermissionElevatorGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Func.isNotEmpty(req.getParkId()), SaasParkElevatorPermissionElevatorGroup::getParkId, req.getParkId());
        wrapper.like(Func.isNotEmpty(req.getPointGroupName()), SaasParkElevatorPermissionElevatorGroup::getGroupName, req.getPointGroupName());
        wrapper.like(Func.isNotEmpty(req.getDoorName()), SaasParkElevatorPermissionElevatorGroup::getElevatorRangeString, req.getDoorName());
        wrapper.orderByDesc(SaasParkElevatorPermissionElevatorGroup::getCreateTime);
        Page<SaasParkElevatorPermissionElevatorGroup> page1 = this.page(page, wrapper);

        voPages = elevatorGroupWrapper.pageVO(page1);

        return voPages;

    }


    /**
     * 保存电梯组
     * 1、电梯组表基本数据的保存
     * 2、根据传入的elevatorRange转换成elevatorRangeString保存到电梯组表
     *
     * @param saasParkElevatorPermissionElevatorGroupDTO
     * @return
     */
    @Override
    public boolean saveOrUpdateByParam(SaasParkElevatorPermissionElevatorGroupDTO saasParkElevatorPermissionElevatorGroupDTO) {
        SaasParkElevatorPermissionElevatorGroup elevatorGroup = new SaasParkElevatorPermissionElevatorGroup();
        BeanUtil.copyProperties(saasParkElevatorPermissionElevatorGroupDTO, elevatorGroup);


        if (saasParkElevatorPermissionElevatorGroupDTO.getElevatorRange() != null) {
            String[] str = saasParkElevatorPermissionElevatorGroupDTO.getElevatorRange().split(",");
            List<String> list = new ArrayList<>(Arrays.asList(str));
            List<SaasParkElevatorManageLocationEntity> listByIds = saasParkElevatorManageLocationMapper.getListByIds(list);


            String elvatorRangeStr = "";
            for (int i = 0; i < listByIds.size(); i++) {
                if (i != listByIds.size() - 1) {
                    elvatorRangeStr += listByIds.get(i).getElevatorName() + ",";
                } else {
                    elvatorRangeStr += listByIds.get(i).getElevatorName();
                }
            }
            elevatorGroup.setElevatorRangeString(elvatorRangeStr);
        }

        saveOrUpdate(elevatorGroup);

        return true;
    }


    @Override
    public ElevatorPointGroupVO detailById(Long id) {
        ElevatorPointGroupVO elevatorGroupVO = new ElevatorPointGroupVO();
        SaasParkElevatorPermissionElevatorGroup elevatorGroup = getById(id);
        if (elevatorGroup != null) {
            BeanUtil.copyProperties(elevatorGroup, elevatorGroupVO);
        }
        return elevatorGroupVO;
    }

    /**
     * 判断电梯组是否关联到电梯点,没关联才能删除
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id) throws Exception {
        //查询电梯分组是否被引用
        ElevatorPointGroupVO elevatorPointGroupVO = this.detailById(id);
        if (elevatorPointGroupVO != null) {
            if (elevatorPointGroupVO.getElevatorList() != null && elevatorPointGroupVO.getElevatorList().size() > 0) {
                throw new RuntimeException("要删除的电梯组存在关联电梯,请先移除关联");
            }
        } else {
            throw new RuntimeException("要删除的电梯组不存在");
        }
        return removeById(id);
    }


}
