package com.ruoyi.platform.service.impl;

import com.google.gson.Gson;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.domain.Component;
import com.ruoyi.platform.service.ComponentService;
import com.ruoyi.platform.mapper.ComponentDao;
import com.ruoyi.platform.utils.ConvertUtil;
import com.ruoyi.platform.vo.ComponentVo;
import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.platform.utils.GsonUtil.gson;

/**
 * (Component)表服务实现类
 *
 * @author Xidaray
 * @since 2023-11-30 11:36:02
 */
@Service("componentService")
public class ComponentServiceImpl implements ComponentService {
    @Resource
    private ComponentDao componentDao;

    @Value("${pipeline.control_strategy}")
    private String controlStrategy;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Component queryById(Integer id) {
        Component component = this.componentDao.queryById(id);
        if (component == null) {
            throw new RuntimeException("组件不存在");
        }

        return component;
    }

    @Override
    public List<Map> queryAllGroupedByCategory() throws Exception {
        List<Component> componentList = this.componentDao.queryAll();
        List<Map> result = new ArrayList<>();
        if (componentList.isEmpty()) {
            return result;
        }
        List<SysDictData> categoryTypeList = DictUtils.getDictCache("category_type");
        Map<Integer, List<Component>> groupedComponent = componentList.stream().collect(Collectors.groupingBy(Component::getCategoryId));
        for (Map.Entry<Integer, List<Component>> entry : groupedComponent.entrySet()) {
            List<SysDictData> categorys = categoryTypeList.stream().filter(sysDictData -> StringUtils.equals(sysDictData.getDictValue(), String.valueOf(entry.getKey()))).collect(Collectors.toList());
            if (categorys.size() == 0) {
                throw new Exception("组件类型不存在");
            }
            Map map = new HashMap();
            map.put("key", entry.getKey());
            map.put("name", categorys.get(0).getDictLabel());
            map.put("value", entry.getValue());
            result.add(map);
        }
        return result;
    }

    /**
     * 分页查询
     *
     * @param component   筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<Component> queryByPage(Component component, PageRequest pageRequest) {
        long total = this.componentDao.count(component);
        return new PageImpl<>(this.componentDao.queryAllByLimit(component, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param componentVo 实例对象
     * @return 实例对象
     */
    @Override
    public Component insert(ComponentVo componentVo) {
        //把那几个Object转成String类型
        Gson gson = new Gson();
        Component component = ConvertUtil.entityToVo(componentVo, Component.class);
        component.setControlStrategy(controlStrategy);

        //json转换,存数据库
        String inParameters = gson.toJson(componentVo.getInParameters(), LinkedHashMap.class);
        String outParameters = gson.toJson(componentVo.getOutParameters(), LinkedHashMap.class);
        String envVariable = gson.toJson(componentVo.getEnvVirables(), LinkedHashMap.class);
        component.setEnvVirables(envVariable);
        component.setInParameters(inParameters);
        component.setOutParameters(outParameters);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        component.setCreateBy(loginUser.getUsername());
        component.setUpdateBy(loginUser.getUsername());
        component.setUpdateTime(new Date());
        component.setCreateTime(new Date());
        component.setState(1);

        // 检查相同category_id下的component_name是否已存在
        Integer existingCount = this.componentDao.countByNameAndCategoryId(component.getComponentName(), component.getCategoryId());

        if (existingCount != null && existingCount > 0) {
            throw new RuntimeException("该类别下已有同名组件");
        }

        this.componentDao.insert(component);
        return component;
    }

    /**
     * 修改数据
     *
     * @param componentVo 实例对象
     * @return 实例对象
     */
    @Override
    public Component update(ComponentVo componentVo) {
        Component component = this.queryById(componentVo.getId());
        //只能更新当前存在的组件

        if (component == null) {
            throw new RuntimeException("组件不存在，无法更新");
        }

        //将object转成string类型
        component = ConvertUtil.entityToVo(componentVo, Component.class);
        Gson gson = new Gson();

        String inParameters = gson.toJson(componentVo.getInParameters(), LinkedHashMap.class);
        String outParameters = gson.toJson(componentVo.getOutParameters(), LinkedHashMap.class);

        String envVariable = gson.toJson(componentVo.getEnvVirables(), LinkedHashMap.class);
        component.setEnvVirables(envVariable);
        component.setInParameters(inParameters);
        component.setOutParameters(outParameters);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        component.setUpdateBy(loginUser.getUsername());
        component.setUpdateTime(new Date());
        this.componentDao.update(component);
        return this.queryById(component.getId());

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.componentDao.deleteById(id) > 0;
    }

    @Override
    public String removeById(Integer id) throws Exception {
        Component component = this.componentDao.queryById(id);
        //先进行判断 组件是否存在

        if (component == null) {
            throw new Exception("组件不存在");
        }

        //判断权限，只有admin和创建者本身可以删除该组件
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String username = loginUser.getUsername();
        String createdBy = component.getCreateBy();
        if (!(StringUtils.equals(username, "admin") || StringUtils.equals(username, createdBy))) {
            throw new Exception("无权限删除该组件");
        }

        component.setState(0);
        return this.componentDao.update(component) > 0 ? "删除成功" : "删除失败";
    }


}
