package com.muyu.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.domain.*;
import com.muyu.domain.req.*;
import com.muyu.domain.resp.CarFenceGroupResp;
import com.muyu.domain.resp.CarFenceGroupsResp;
import com.muyu.domain.resp.CarFenceResp;
import com.muyu.enterprise.cache.fence.VehicleCacheFenceAddService;
import com.muyu.enterprise.cache.fence.VehicleCacheFenceService;
import com.muyu.server.mapper.CarFenceMapper;
import com.muyu.server.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 围栏数据业务实现层
 * @Author：yang
 * @Package：com.muyu.server.service.impl
 * @Project：cloud-electronic
 * @name：CarFenceServiceImpl
 * @Date：2024/9/17 16:57
 */
@Service
@Log4j2
@AllArgsConstructor
public class CarFenceServiceImpl
        extends ServiceImpl<CarFenceMapper, CarFence>
        implements CarFenceService {

    @Autowired
    private CarFenceClazzService carFenceClazzService;
    @Autowired
    private CarFenceTypeService carFenceTypeService;
    @Autowired
    private CarMiddleGroupService carMiddleGroupService;
    @Autowired
    private CarFenceGroupService carFenceGroupService;
    @Autowired
    private CarMiddleSerivce carMiddleSerivce;
    @Autowired
    private CarInformationService carInformationService;
    private final VehicleCacheFenceService vehicleCacheFenceService;
    private final VehicleCacheFenceAddService vehicleCacheFenceAddService;
    /**
     * 查询围栏信息
     */
    @Override
    public Page<CarFenceResp> selectCarFence(CarFenceReq req) {

        LambdaQueryWrapper<CarFence> queryWrapper = new LambdaQueryWrapper<>();
        //数据来源类型
        queryWrapper.eq(
                StringUtils.isNoneEmpty(req.getName()),
                CarFence::getName, req.getName()
        );
        queryWrapper.eq(
                StringUtils.isNoneEmpty(req.getName()),
                CarFence::getName, req.getName()
        );
        queryWrapper.eq(
                StringUtils.isNoneEmpty(req.getName()),
                CarFence::getName, req.getName()
        );

        //使用MyBatis-Plus的分页功能进行查询
        Page<CarFence> carFencePage = this.page(
                //创建分页参数，包括页码和每页显示的记录数
                new Page<>(req.getPageNum(),
                        req.getPageSize()),
                //传递查询条件
                queryWrapper
        );
        List<CarFenceClazz> carFenceClazzList = carFenceClazzService.list()
                .stream()
                .map(CarFenceClazz::carFenceClazzBuild)
                .toList();
        List<CarFenceType> carFenceTypeList = carFenceTypeService.list()
                .stream()
                .map(CarFenceType::carFenceTypeBuild)
                .toList();
        List<CarFence> carFenceList = carFencePage.getRecords();
        this.optimizeEntity(carFenceList,carFenceClazzList,carFenceTypeList);

        //构建一个新的分页响应对象
        Page<CarFenceResp> carFenceRespPage = new Page<>() {{
            //从查询结果中获取记录，并使用流式处理将每条记录转换为EtlDataScoreResp对象
            List<CarFenceResp> etlDataScoreRespList = carFencePage.getRecords().stream()
                    //使用map操作将EtlDataScore对象转换为EtlDataScoreResp对象
                    .map(CarFenceResp::carFenceResqListBuilder)
                    //收集流中的元素到列表中
                    .toList();
            //设置分页响应中的记录列表
            setRecords(etlDataScoreRespList);
            //设置分页响应中的总记录数
            setTotal(carFencePage.getTotal());
            //设置分页响应中的当前页码
            setCurrent(carFencePage.getCurrent());
            //设置分页响应中的每页记录数
            setSize(carFencePage.getSize());
        }};
        List<CarFenceResp> records = carFenceRespPage.getRecords();
        records.forEach(carFenceResp -> {
            List<CarInformation> list = carInformationService
                    .list(new LambdaQueryWrapper<CarInformation>()
                            .eq(CarInformation::getCarInformationFence, carFenceResp.getId()));
            list.forEach(carInformation -> {
                vehicleCacheFenceService.put(vehicleCacheFenceService.keyPre()+carInformation.getCarInformationVIN(),carFenceResp);
            });

        });
        return carFenceRespPage;
    }

    /**
     * 电子围栏添加
     */
    @Override
    public Boolean addCarFence(CarFence carFence) {
        boolean connects = this.save(carFence);
        System.out.println(carFence.getId());
        List<CarFenceGroup> carFenceGroups = carFence.getCarFenceGroups();
        carFenceGroupService.saveBatch(carFenceGroups);
        carFenceGroups.forEach(carFenceGroup -> {
            Integer id = carFenceGroup.getId();
            CarMiddleGroup carMiddleGroup = new CarMiddleGroup();
            carMiddleGroup.setCarFenceId(carFence.getId());
            carMiddleGroup.setFenceGroupId(carFenceGroup.getId());
            carMiddleGroupService.save(carMiddleGroup);
        });
        List<CarInformation> list = carInformationService
                .list(new LambdaQueryWrapper<CarInformation>()
                        .eq(CarInformation::getCarInformationFence, carFence.getId()));
        list.forEach(carInformation -> {
            vehicleCacheFenceAddService.put(vehicleCacheFenceAddService.keyPre()+carInformation.getCarInformationVIN(),carFence);
        });
        return connects;
    }

    /**
     * 添加电子围栏和车辆中间表
     */
    @Override
    public Boolean addCarGroup(CarGroupReq req) {
        List<CarInformation> carInformations = req.getCarInformations();
        List<CarFenceGroup> carFenceGroups = req.getCarFenceGroups();
        List<CarMiddle> carMiddles = new ArrayList<>();
        carFenceGroups.forEach(carFenceGroup -> {

            carInformations.forEach(carInformation -> {
                Integer carFenceGroupId = carFenceGroup.getId();
                Long carInformationId = carInformation.getCarInformationId();
                carMiddles.add(new CarMiddle(carFenceGroupId,carInformationId));
            });
        });
        return carMiddleSerivce.saveBatch(carMiddles);
    }

    /**
     * 添加围栏和围栏组中间表
     */
    @Override
    public Boolean addFenceGroup(FenceGroupReq req) {
        List<CarFence> carInformations = req.getCarFences();
        List<CarFenceGroup> carFenceGroups = req.getCarFenceGroups();
        List<CarMiddleGroup> carMiddles = new ArrayList<>();
        carFenceGroups.forEach(carFenceGroup -> {

            carInformations.forEach(carFence -> {
                Integer carFenceGroupId = carFenceGroup.getId();
                Integer id = carFence.getId();
                carMiddles.add(new CarMiddleGroup(carFenceGroupId,id));
            });
        });
        return carMiddleGroupService.saveBatch(carMiddles);
    }

    /**
     * 查询围栏和围栏组中间围栏
     */
    @Override
    public List<CarFenceGroupResp> selectCarFenceGroupList(Integer id) {
        List<CarMiddleGroup> list = carMiddleGroupService.list(
                new LambdaQueryWrapper<CarMiddleGroup>()
                        .eq(CarMiddleGroup::getFenceGroupId,id))
                        .stream()
                        .map(CarMiddleGroup::carMiddleGroupBuilder)
                        .toList();
        List<CarFenceGroupResp> carFenceGroupResps = new ArrayList<>();
        list.forEach(carMiddleGroup -> {
            this.carMiddleList(carMiddleGroup, carFenceGroupResps);
        });
        return carFenceGroupResps;
    }
    /**
     * 查询中间围栏
     */
    @Override
    public Boolean carFenceGroupDel(CarGroupIdReq carGroupIdReq) {

        List<CarMiddleGroup> list = carMiddleGroupService.list(
                new LambdaQueryWrapper<CarMiddleGroup>()
                        .eq(CarMiddleGroup::getCarFenceId, carGroupIdReq.getId())
                        .eq(CarMiddleGroup::getFenceGroupId, carGroupIdReq.getIds()))
        .stream()
        .map(CarMiddleGroup::carMiddleGroupBuilder)
        .toList();
        return carMiddleGroupService.removeBatchByIds(list);
    }

    private void carMiddleList(CarMiddleGroup carMiddleGroup, List<CarFenceGroupResp> carFenceGroupResps) {
        Integer carFenceId = carMiddleGroup.getCarFenceId();
        Integer fenceGroupId = carMiddleGroup.getFenceGroupId();
        List<CarFence> carFenceList = this.list(
                        new LambdaQueryWrapper<CarFence>()
                                .eq(CarFence::getId,carFenceId))
                .stream()
                .map(CarFence::carFenceBuild)
                .toList();
        List<CarFenceGroup> carFenceGroupsList = carFenceGroupService.list(
                        new LambdaQueryWrapper<CarFenceGroup>()
                                .eq(CarFenceGroup::getId,fenceGroupId))
                .stream()
                .map(CarFenceGroup::carFenceBuild)
                .toList();
        carFenceList.forEach(carFence -> {
            CarFenceGroupResp carFenceGroupResp = new CarFenceGroupResp();
            carFenceGroupResp.setId(carFence.getId());
            carFenceGroupResp.setName(carFence.getName());
            carFenceGroupResp.setClazzId(carFence.getClazzId());
            carFenceGroupResp.setTypeId(carFence.getTypeId());
            carFenceGroupResp.setFenceText(carFence.getFenceText());
            carFenceGroupResp.setFenceStart(carFence.getFenceStart());
            carFenceGroupResp.setFenceEnd(carFence.getFenceEnd());
            carFenceGroupResp.setFenceCreate(carFence.getFenceCreate());

            carFenceGroupResps.add(carFenceGroupResp);
        });
        carFenceGroupsList.forEach(carFenceGroup -> {
            carFenceGroupResps.forEach(carFenceGroupResp -> {
                carFenceGroupResp.setPriority(carFenceGroup.getPriority());
                carFenceGroupResp.setStatus(carFenceGroup.getStatus());
                carFenceGroupResp.setGroupType(carFenceGroup.getGroupType());
            });
        });
    }


    /**
     * 优化查询返回值
     * @param carFenceList  电子围栏数据
     * @param carFenceClazzList 业务数据
     * @param carFenceTypeList 类型数据
     */
    private void optimizeEntity(
                                List<CarFence> carFenceList,
                                List<CarFenceClazz> carFenceClazzList,
                                List<CarFenceType> carFenceTypeList) {
        carFenceList.forEach(carFence -> {
            carFenceClazzList.forEach(carFenceClazz -> {
                if (carFenceClazz.getClazzId().equals(carFence.getClazzId())) {
                    carFence.setClazzName(carFenceClazz.getClazzName());
                }else {
                    return;
                }
            });
            carFenceTypeList.forEach(carFenceType -> {
                if (carFenceType.getTypeId().equals(carFence.getTypeId())) {
                    carFence.setTypeName(carFenceType.getTypeName());
                }else{
                    return;
                }
            });
        });
    }
    /**
     * 查询车辆围栏组信息
     */
    @Override
    public List<CarFenceGroupsResp> carGroupList(CarFenceGroupReq req) {

        List<CarFenceGroupsResp> fenceGroupList = new ArrayList<>();
        CarFenceGroupsResp carFenceGroupsResp = new CarFenceGroupsResp();

        List<CarMiddleGroup> list = carMiddleGroupService.list(
                        new LambdaQueryWrapper<CarMiddleGroup>()
                                .eq(CarMiddleGroup::getCarFenceId, req.getId()))
                .stream()
                .map(CarMiddleGroup::carMiddleGroupBuilder)
                .toList();
        List<CarFence> carFenceList = this.list()
                .stream()
                .map(CarFence::carFenceBuild)
                .toList();
        list.forEach(carMiddleGroup -> {
            List<CarMiddle> carMiddleGroupList = carMiddleSerivce.list(
                            new LambdaQueryWrapper<CarMiddle>()
                                    .eq(CarMiddle::getFenceGroupId, carMiddleGroup.getFenceGroupId()))
                    .stream()
                    .map(CarMiddle::carMiddleBuilder)
                    .toList();
            carMiddleGroupList.forEach(carMiddle -> {
                List<CarFenceGroup> carFenceGroupList = carFenceGroupService.list(
                                new LambdaQueryWrapper<CarFenceGroup>()
                                        .eq(CarFenceGroup::getId, carMiddle.getFenceGroupId()))
                        .stream()
                        .map(CarFenceGroup::carFenceBuild)
                        .toList();
                List<CarInformation> carInformationList = carInformationService.list(
                                new LambdaQueryWrapper<CarInformation>()
                                        .eq(CarInformation::getCarInformationId, carMiddle.getCarInformationId()))
                        .stream()
                        .map(CarInformation::carInformationBuilder)
                        .toList();
                carFenceList.forEach(carFence -> {

                    carFenceGroupsResp.setFenceText(carFence.getFenceText());

                });
                carFenceGroupList.forEach(carFenceGroup -> {
                    carFenceGroupsResp.setId(carFenceGroup.getId());
                    carFenceGroupsResp.setStatus(carFenceGroup.getStatus());
                    carFenceGroupsResp.setPriority(carFenceGroup.getPriority());
                    carFenceGroupsResp.setGroupType(carFenceGroup.getGroupType());

                });
                carInformationList.forEach(carInformation -> {
                    carFenceGroupsResp.setCarInformationLicensePlate(carInformation.getCarInformationLicensePlate());
                });
                fenceGroupList.add(carFenceGroupsResp);
            });
        });
        return fenceGroupList;
    }

    @Override
    public List<CarFence> CarFenceList(Integer carInformationFence) {
        return this.list(new LambdaQueryWrapper<CarFence>().eq(CarFence::getId,carInformationFence))
                .stream()
                .map(CarFence::carFenceBuild)
                .toList();
    }
}
