package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteRocketMqService;
import com.ruoyi.system.api.domain.RmDeployScriptRemote;
import com.ruoyi.system.api.domain.RmNetworkInterfaceRemote;
import com.ruoyi.system.domain.EpsBusinessDeploy;
import com.ruoyi.system.domain.EpsMethodChangeRecord;
import com.ruoyi.system.domain.RmResourceRegistration;
import com.ruoyi.system.enums.ReviewEnum;
import com.ruoyi.system.mapper.EpsBusinessDeployMapper;
import com.ruoyi.system.mapper.EpsMethodChangeRecordMapper;
import com.ruoyi.system.mapper.RmResourceRegistrationMapper;
import com.ruoyi.system.service.IEpsBusinessDeployService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 业务下发管理Service业务层处理
 * 
 * @author gyt
 * @date 2025-10-13
 */
@Service
public class EpsBusinessDeployServiceImpl implements IEpsBusinessDeployService 
{
    @Autowired
    private EpsBusinessDeployMapper epsBusinessDeployMapper;
    @Autowired
    private RmResourceRegistrationMapper rmResourceRegistrationMapper;
    @Autowired
    private RemoteRocketMqService remoteRocketMqService;
    @Autowired
    private EpsMethodChangeRecordMapper epsMethodChangeRecordMapper;

    /**
     * 查询业务下发管理
     * 
     * @param id 业务下发管理主键
     * @return 业务下发管理
     */
    @Override
    public EpsBusinessDeploy selectEpsBusinessDeployById(Long id)
    {
        EpsBusinessDeploy detailMsg = epsBusinessDeployMapper.selectEpsBusinessDeployById(id);
        String[] clientIds = detailMsg.getDeployDevice().split("\n");

        // 创建一个列表来存储处理后的clientId信息
        List<String> processedClientIds = new ArrayList<>();

        // 根据clientId获取服务器公网ip
        for (String clientId : clientIds) {
            if (StringUtils.isNotBlank(clientId)) {
                RmResourceRegistration rmResourceRegistration = new RmResourceRegistration();
                rmResourceRegistration.setClientId(clientId.trim()); // 使用clientId字段查询

                // 根据clientId查询注册信息
                RmResourceRegistration publicIpVo = rmResourceRegistrationMapper.selectRegistMsgByClientId(rmResourceRegistration);

                String processedClientId;
                if (publicIpVo != null && StringUtils.isNotBlank(publicIpVo.getIp1PublicIp())) {
                    // 如果有公网IP，格式为：公网IP + 空格 + 原clientId
                    processedClientId = publicIpVo.getIp1PublicIp() + "   " + clientId.trim();
                } else {
                    // 如果没有公网IP，保持原样
                    processedClientId = clientId.trim();
                }
                processedClientIds.add(processedClientId);
            }
        }

        // 将处理后的结果重新设置回detailMsg
        if (detailMsg != null) {
            // 如果需要修改原对象的deployDevice字段
            String processedDeployDevice = String.join("\n", processedClientIds);
            detailMsg.setDeployDevice(processedDeployDevice);
        }

        return detailMsg;
    }

    /**
     * 查询业务下发管理列表
     * 
     * @param epsBusinessDeploy 业务下发管理
     * @return 业务下发管理
     */
    @Override
    public List<EpsBusinessDeploy> selectEpsBusinessDeployList(EpsBusinessDeploy epsBusinessDeploy)
    {
        return epsBusinessDeployMapper.selectEpsBusinessDeployList(epsBusinessDeploy);
    }

    /**
     * 新增业务下发管理
     * 
     * @param epsBusinessDeploy 业务下发管理
     * @return 结果
     */
    @Override
    public int insertEpsBusinessDeploy(EpsBusinessDeploy epsBusinessDeploy)
    {
        epsBusinessDeploy.setCreateTime(DateUtils.getNowDate());
        epsBusinessDeploy.setSubmitBy(SecurityUtils.getUsername());
        return epsBusinessDeployMapper.insertEpsBusinessDeploy(epsBusinessDeploy);
    }

    /**
     * 修改业务下发管理
     * 
     * @param epsBusinessDeploy 业务下发管理
     * @return 结果
     */
    @Override
    public int updateEpsBusinessDeploy(EpsBusinessDeploy epsBusinessDeploy)
    {
        epsBusinessDeploy.setUpdateTime(DateUtils.getNowDate());
        return epsBusinessDeployMapper.updateEpsBusinessDeploy(epsBusinessDeploy);
    }

    /**
     * 批量删除业务下发管理
     * 
     * @param ids 需要删除的业务下发管理主键
     * @return 结果
     */
    @Override
    public int deleteEpsBusinessDeployByIds(Long[] ids)
    {
        return epsBusinessDeployMapper.deleteEpsBusinessDeployByIds(ids);
    }

    /**
     * 删除业务下发管理信息
     * 
     * @param id 业务下发管理主键
     * @return 结果
     */
    @Override
    public int deleteEpsBusinessDeployById(Long id)
    {
        return epsBusinessDeployMapper.deleteEpsBusinessDeployById(id);
    }

    /**
     * 审核
     * @param epsBusinessDeploy
     * @return
     */
    @Override
    public int reviewBusiness(EpsBusinessDeploy epsBusinessDeploy) {
        // 设置审核信息
        epsBusinessDeploy.setReviewBy(SecurityUtils.getUsername());
        epsBusinessDeploy.setReviewTime(DateUtils.getNowDate());
        int rows = epsBusinessDeployMapper.updateEpsBusinessDeploy(epsBusinessDeploy);
        if(StringUtils.equals(ReviewEnum.通过.getCode(), epsBusinessDeploy.getReviewStatus())){
            // 根据id查询业务信息
            EpsBusinessDeploy businessMsg = epsBusinessDeployMapper.selectEpsBusinessDeployById(epsBusinessDeploy.getId());
            String businessCode = businessMsg.getBusinessCode();
            String businessName = businessMsg.getBusinessName();
            String clientIdStr = businessMsg.getDeployDevice();
            // 添加服务器脚本执行策略
            RmDeployScriptRemote addData = new RmDeployScriptRemote();
            addData.setDeployDevice(clientIdStr);
            addData.setExecutionMethod(0);
            addData.setPolicyStatus("0");
            addData.setTaskName(businessMsg.getTaskName());
            addData.setScriptName(businessMsg.getScriptName());
            addData.setScriptPath(businessMsg.getScriptPath());
            addData.setDefaultParams(businessMsg.getScriptParams());
            addData.setPolicyName("策略"+ DateUtils.dateTimeNow());
            remoteRocketMqService.addDeployScript(addData, SecurityConstants.INNER);
            String[] clientIds = clientIdStr.split("\n");
            // 保存业务修改记录
            for (String clientId : clientIds) {
                // 根据clientId查询网卡接口名称
                RmNetworkInterfaceRemote queryParam = new RmNetworkInterfaceRemote();
                queryParam.setClientId(clientId);
                List<RmNetworkInterfaceRemote> interfaceList =  remoteRocketMqService.getNetworkInterfaceList(queryParam, SecurityConstants.INNER).getData();
                String interfaceName = "";
                if (interfaceList != null && !interfaceList.isEmpty()) {
                    interfaceName = interfaceList.stream()
                            .filter(interfaceRemote -> "1".equals(interfaceRemote.getBindIp()))
                            .map(RmNetworkInterfaceRemote::getInterfaceName)
                            .filter(name -> name != null && !name.trim().isEmpty())
                            .collect(Collectors.joining(","));
                }
                EpsMethodChangeRecord changeRecord = new EpsMethodChangeRecord();
                // 设置基本信息
                changeRecord.setClientId(clientId);
                changeRecord.setTrafficPort(interfaceName);
                changeRecord.setBusinessCode(businessCode);
                changeRecord.setBusinessName(businessName);
                changeRecord.setCreateTime(DateUtils.getNowDate());
                changeRecord.setUpdateTime(DateUtils.getNowDate());
                changeRecord.setCreatBy(SecurityUtils.getUsername());
                changeRecord.setUpdateBy(SecurityUtils.getUsername());
                // 修改内容
                String content = "流量网口设置为" + interfaceName + ",业务为" + businessName;
                changeRecord.setChangeContent(content);
                // 保存数据
                epsMethodChangeRecordMapper.insertEpsMethodChangeRecord(changeRecord);
                // 绑定业务名称
                RmResourceRegistration updateData = new RmResourceRegistration();
                updateData.setBusinessName(businessName);
                updateData.setClientId(clientId);
                rmResourceRegistrationMapper.updateStatusByResource(updateData);
            }
        }
        return 1;
    }
}
