package com.ruoyi.ibs.rules.service.impl;


import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShellCmd;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ibs.rules.domain.dto.RelationRuleDTO;
import com.ruoyi.ibs.rules.mapper.RelationRuleMapper;
import com.ruoyi.ibs.rules.service.IRelationRuleService;
import com.ruoyi.ibs.rules.domain.entity.RelationRule;
import com.ruoyi.ibs.rules.domain.vo.RelationRuleVO;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;


/**
 * 分配引擎规则;Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-20
 */
@Service
@Slf4j
public class RelationRuleServiceImpl implements IRelationRuleService
{
    @Resource
    private RelationRuleMapper relationRuleMapper;

    @Resource
    private SysDeptServiceImpl sysDeptService;



    @Resource
    RedisCache redisCache;

    /**
     * 查询分配引擎规则;列表
     *
     * @param  ;
     * @return 分配引擎规则;
     */
    @Override
    public List<RelationRuleVO> selectRelationRuleList()
    {
        RelationRule relationRule = new RelationRule();
        relationRule.setDeptId(getLoginUser().getDeptId().toString());
        List<RelationRule> relationRules = relationRuleMapper.selectRelationRuleList(relationRule);
        return relationRules.stream().map(RelationRuleVO::new).collect(Collectors.toList());

    }

    /**
     * 新增分配引擎规则;
     *
     * @param relationRules 分配引擎规则;
     * @return 结果
     */
    @Override
    public int insertRelationRule(List<RelationRuleDTO> relationRules)
    {
        RelationRule relationRule = new RelationRule();
        relationRule.setParam(relationRules.get(0).getParam());
        relationRule.setRuleType(relationRules.get(0).getRuleType());
        relationRule.setDeptId(SecurityUtils.getDeptId().toString());
        List<RelationRule> rls =  relationRuleMapper.selectRelationRuleList(relationRule);
        if(StringUtils.isNotEmpty(rls)){
            throw new ServiceException("当前已存在规则，只能修改");
        }
        if(this.hasDuplicates(relationRules)){
            throw new ServiceException("存在重复规则");
        }

        List<RelationRule> collects = relationRules.stream().map(RelationRule::new).collect(Collectors.toList());
        for (RelationRule rr:collects) {
            relationRuleMapper.insertRelationRule(rr);
        }
        return 1;
    }

    /**
     * 修改分配引擎规则;
     *
     * @param relationRules 分配引擎规则;
     * @return 结果
     */
    @Override
    public int updateRelationRule(List<RelationRuleDTO> relationRules)
    {
        List<RelationRule> rules = relationRuleMapper.selectRelationRuleListById(relationRules.get(0).getIdb());

        if(!StringUtils.isNotEmpty(rules) || !rules.get(0).getDeptId().equalsIgnoreCase(relationRules.get(0).getDeptId())){
            throw new ServiceException("被修改規則不存在");
        }
        if(this.hasDuplicates(relationRules)){
            throw new ServiceException("存在重复规则");
        }
        if(!rules.get(0).getDeptId().equalsIgnoreCase(SecurityUtils.getDeptId().toString())  && sysDeptService.Parent2Child(SecurityUtils.getDeptId().toString(),rules.get(0).getDeptId())){
            throw new ServiceException("当前规则不在登录人所在机构管辖范围。不允许修改");
        }
        this.deleteRelationRuleById(relationRules.get(0).getIdb());
        List<RelationRule> collects = relationRules.stream().map(RelationRule::new).collect(Collectors.toList());
        for (RelationRule relationRule:collects) {
            relationRuleMapper.insertRelationRule(relationRule);
        }
        return 1;
    }


    /**
     * 删除分配引擎规则;信息
     *
     * @param id 分配引擎规则;主键
     * @return 结果
     */
    @Override
    public int deleteRelationRuleById(String id)
    {
        return relationRuleMapper.deleteRelationRuleById(id);
    }


    @Override
    public int upadteAllDate(String opType){
        Boolean ans = ShellCmd.runCommand(redisCache.getCacheObject("sys_config:shell.rule.update") + " " + SecurityUtils.getDeptId().toString() +" "+ opType );
        return ans? 1:0;
    }

    /**
     * 获取规则列表
     *
     * @param
     * @return
     */
    @Override
    public Map<String,String> getParamList()
    {

        Map<String,String> params = new HashMap<>();
        ArrayList<SysDictData> sysDictTypeArrayList = new ArrayList<SysDictData>(redisCache.getCacheObject("sys_dict:ral_rules"));
        sysDictTypeArrayList.forEach(sdt -> {
            params.put(sdt.getDictValue(), sdt.getDictLabel());
        });
        return params;
    }

    @Override
    public Map<String, String> getAddressSource() {

        Map<String,String> params = new HashMap<>();
        ArrayList<SysDictData> sysDictTypeArrayList = new ArrayList<SysDictData>(redisCache.getCacheObject("sys_dict:address_source"));
        sysDictTypeArrayList.forEach(sdt -> {
            params.put(sdt.getDictValue(), sdt.getDictLabel());
        });
        return params;
    }


    private Boolean hasDuplicates(List<RelationRuleDTO> dtos){
        Set<String> set = new HashSet<>();
        dtos.forEach(dto -> {
            set.add(dto.getName()+dto.getAddSource()) ;
        } );
        return set.size() < dtos.size();

    }


}
