package com.gci.boot.modules.gis.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gci.boot.common.util.JsonUtil;
import com.gci.boot.common.util.RedisUtil;
import com.gci.boot.constant.CommonConstant;
import com.gci.boot.exception.GciBootException;
import com.gci.boot.modules.gis.entity.TbGisSpeedingThreshold;
import com.gci.boot.modules.gis.mapper.TbGisSpeedingThresholdMapper;
import com.gci.boot.modules.gis.service.ITbGisSpeedingThresholdService;
import com.gci.boot.modules.projects.entity.Projects;
import com.gci.boot.modules.projects.service.IProjectsService;
import com.gci.boot.modules.system.service.ISysDictService;
import com.gci.boot.modules.system.vo.DictModel;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

/**
 * <p>
 * 超速阈值设置 服务实现类
 * </p>
 *
 * @author 2464
 * @since 2023-12-25
 */
@Service
public class TbGisSpeedingThresholdServiceImpl extends ServiceImpl<TbGisSpeedingThresholdMapper, TbGisSpeedingThreshold>
    implements ITbGisSpeedingThresholdService {

    @Autowired
    private IProjectsService projectsService;

    @Autowired
    private ISysDictService sysDictService;

    @Override
    public void saveItem(TbGisSpeedingThreshold tbGisSpeedingThreshold) {
        // 为0时时全局通用数据
        if ("0".equals(tbGisSpeedingThreshold.getThresholdType())) {
            tbGisSpeedingThreshold.setProjectId(null);
            tbGisSpeedingThreshold.setVehicleType(null);
            throw new GciBootException("全局通用暂不支持新增");
        } else {
            check(tbGisSpeedingThreshold);
        }
        save(tbGisSpeedingThreshold);
        rel();
    }

    /**
     * 校验数据
     *
     * @param tbGisSpeedingThreshold
     */
    private void check(TbGisSpeedingThreshold tbGisSpeedingThreshold) {
        if (StrUtil.isBlank(tbGisSpeedingThreshold.getProjectId())) {
            throw new GciBootException("项目不能为空！");
        }
        if ("1".equals(tbGisSpeedingThreshold.getThresholdType())) {
            tbGisSpeedingThreshold.setVehicleType(null);
        } else if ("2".equals(tbGisSpeedingThreshold.getThresholdType())) {
            if (StrUtil.isBlank(tbGisSpeedingThreshold.getVehicleType())) {
                throw new GciBootException("车辆种类通用时车辆种类不能为空！");
            }
        } else {
            throw new GciBootException("非法字典值！");
        }
    }

    @Override
    public void updateItem(TbGisSpeedingThreshold tbGisSpeedingThreshold) {
        if (tbGisSpeedingThreshold.getId().equals(CommonConstant.DEFAULT_THRESHOLD)) {
            throw new GciBootException("全局通用暂不支持编辑");
        }
        // 为0时时全局通用数据
        if ("0".equals(tbGisSpeedingThreshold.getThresholdType())) {
            tbGisSpeedingThreshold.setProjectId(null);
            tbGisSpeedingThreshold.setVehicleType(null);
            throw new GciBootException("全局通用暂不支持编辑");
        } else {
            check(tbGisSpeedingThreshold);
        }
        if (tbGisSpeedingThreshold.getIsValid() == 1) {
            int count =
                count(new LambdaUpdateWrapper<TbGisSpeedingThreshold>()
                    .eq(TbGisSpeedingThreshold::getThresholdType, tbGisSpeedingThreshold.getThresholdType())
                    .eq(TbGisSpeedingThreshold::getProjectId, tbGisSpeedingThreshold.getProjectId())
                    .eq(StrUtil.isNotBlank(tbGisSpeedingThreshold.getVehicleType()),
                        TbGisSpeedingThreshold::getVehicleType, tbGisSpeedingThreshold.getVehicleType())
                    .eq(TbGisSpeedingThreshold::getIsValid, 1));
            if (count > 0) {
                throw new GciBootException("编辑失败！同一个类型内只能有一条启用数据！");
            }
        }
        updateById(tbGisSpeedingThreshold);
        rel();
    }

    @Override
    public void cancel(String id) {
        if (id.equals(CommonConstant.DEFAULT_THRESHOLD)) {
            throw new GciBootException("默认全局通用不支持禁用！");
        }
        TbGisSpeedingThreshold byId = getById(id);
        if (BeanUtil.isEmpty(id)) {
            throw new GciBootException("id错误！");
        } else {
            byId.setIsValid(0);
            updateById(byId);
            rel();
        }
    }

    @Override
    public void unCancel(String id) {
        TbGisSpeedingThreshold byId = getById(id);
        if (BeanUtil.isEmpty(id)) {
            throw new GciBootException("id错误！");
        } else {
            int count = count(new LambdaUpdateWrapper<TbGisSpeedingThreshold>()
                .eq(TbGisSpeedingThreshold::getThresholdType, byId.getThresholdType())
                .eq(TbGisSpeedingThreshold::getProjectId, byId.getProjectId())
                .eq(StrUtil.isNotBlank(byId.getVehicleType()), TbGisSpeedingThreshold::getVehicleType,
                    byId.getVehicleType())
                .eq(TbGisSpeedingThreshold::getIsValid, 1));
            if (count > 0) {
                throw new GciBootException("启用失败！同一个类型内只能有一条启用数据！");
            }
            byId.setIsValid(1);
            updateById(byId);
            rel();
        }
    }

    @Override
    public void removeItem(String id) {
        if (id.equals(CommonConstant.DEFAULT_THRESHOLD)) {
            throw new GciBootException("默认全局通用不支持删除！");
        }
        removeById(id);
        rel();
    }

    @Override
    public void rel() {
        List<Projects> projectsList = projectsService.list();
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("vehicle_type");

        Map<String, Object> stringStringHashMap = new HashMap<>();

        List<TbGisSpeedingThreshold> gisSpeedingThresholdList = list(new LambdaQueryWrapper<TbGisSpeedingThreshold>()
            .eq(TbGisSpeedingThreshold::getIsValid, 1).orderByDesc(TbGisSpeedingThreshold::getThresholdType));
        for (Projects projects : projectsList) {
            for (DictModel dictModel : dictModelList) {
                TbGisSpeedingThreshold tbGisSpeedingThreshold1 = gisSpeedingThresholdList.stream()
                    .filter(t -> "2".equals(t.getThresholdType()) && projects.getId().equals(t.getProjectId())
                        && dictModel.getValue().equals(t.getVehicleType()))
                    .findFirst().orElse(null);
                if (tbGisSpeedingThreshold1 != null) {
                    stringStringHashMap.put(CommonConstant.THRESHOLD + projects.getId() + ":" + dictModel.getValue(),
                        JsonUtil.object2JsonAll(tbGisSpeedingThreshold1));
                } else {
                    TbGisSpeedingThreshold tbGisSpeedingThreshold2 = gisSpeedingThresholdList.stream()
                        .filter(t -> "1".equals(t.getThresholdType()) && projects.getId().equals(t.getProjectId()))
                        .findFirst().orElse(null);
                    if (tbGisSpeedingThreshold2 != null) {
                        stringStringHashMap.put(
                            CommonConstant.THRESHOLD + projects.getId() + ":" + dictModel.getValue(),
                            JsonUtil.object2JsonAll(tbGisSpeedingThreshold2));
                    } else {
                        TbGisSpeedingThreshold tbGisSpeedingThreshold = gisSpeedingThresholdList.stream()
                            .filter(t -> t.getId().equals(CommonConstant.DEFAULT_THRESHOLD)).findFirst().orElse(null);
                        if (tbGisSpeedingThreshold != null) {
                            stringStringHashMap.put(
                                CommonConstant.THRESHOLD + projects.getId() + ":" + dictModel.getValue(),
                                JsonUtil.object2JsonAll(tbGisSpeedingThreshold));
                        }
                    }
                }
            }
        }
        RedisUtil.multiSet(stringStringHashMap);
    }
}
