package com.tongran.mtragent.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tongran.common.core.constant.SecurityConstants;
import com.tongran.common.core.domain.R;
import com.tongran.common.core.enums.MsgEnum;
import com.tongran.common.core.utils.DateUtils;
import com.tongran.mtragent.domain.DeviceMessage;
import com.tongran.mtragent.domain.RmAgentManagement;
import com.tongran.mtragent.domain.vo.AgentUpdateMsgVo;
import com.tongran.mtragent.domain.vo.PolicyTypeVo;
import com.tongran.mtragent.domain.vo.PolicyVo;
import com.tongran.mtragent.mapper.RmAgentManagementMapper;
import com.tongran.mtragent.model.ProducerMode;
import com.tongran.mtragent.producer.MessageProducer;
import com.tongran.mtragent.service.IRmAgentManagementService;
import com.tongran.system.api.RemoteRevenueConfigService;
import com.tongran.system.api.domain.RmResourceRegistrationRemote;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * Agent管理Service业务层处理
 * 
 * @author tongran
 * @date 2025-09-15
 */
@Service
@Slf4j
public class RmAgentManagementServiceImpl implements IRmAgentManagementService
{
    @Autowired
    private RmAgentManagementMapper rmAgentManagementMapper;
    @Autowired
    private RemoteRevenueConfigService remoteRevenueConfigService;
    @Autowired
    private ProducerMode producerMode;

    /**
     * 查询Agent管理
     * 
     * @param id Agent管理主键
     * @return Agent管理
     */
    @Override
    public RmAgentManagement selectRmAgentManagementById(Long id)
    {
        RmAgentManagement agentManagement = rmAgentManagementMapper.selectRmAgentManagementById(id);
        if(agentManagement != null){
            if(agentManagement.getClientId() != null){
                // 赋其他值
                setPropties(agentManagement);
            }
        }
        return agentManagement;
    }

    /**
     * 查询Agent管理列表
     * 
     * @param rmAgentManagement Agent管理
     * @return Agent管理
     */
    @Override
    public List<RmAgentManagement> selectRmAgentManagementList(RmAgentManagement rmAgentManagement)
    {
        List<RmAgentManagement> managementList = rmAgentManagementMapper.selectRmAgentManagementList(rmAgentManagement);
        for (RmAgentManagement agentManagement : managementList) {
            if(agentManagement.getClientId()!=null){
                // 查询注册表信息赋值
                setPropties(agentManagement);
            }
        }
        return managementList;
    }

    /**
     * 根据注册表赋值
     * @param agentManagement
     */
    public void setPropties(RmAgentManagement agentManagement){
        String clientId = agentManagement.getClientId();
        // 设置其他信息
        RmResourceRegistrationRemote queryRegist = new RmResourceRegistrationRemote();
        queryRegist.setClientId(clientId);
        R<RmResourceRegistrationRemote> registMsgR = remoteRevenueConfigService.getListByHardwareSn(queryRegist, SecurityConstants.INNER);
        if(registMsgR != null && registMsgR.getData() != null){
            RmResourceRegistrationRemote registMsg = registMsgR.getData();
            agentManagement.setStatus(registMsg.getOnlineStatus());
            agentManagement.setHardwareSn(registMsg.getHardwareSn());
        }
    }

    /**
     * 保存最后更新结果
     *
     * @param rmAgentManagement Agent管理
     * @return 结果
     */
    public void updateRmAgentManagementByHardwareSn(RmAgentManagement rmAgentManagement){
        rmAgentManagementMapper.updateRmAgentManagementBySn(rmAgentManagement);
    }

    /**
     * 配置更新策略v1.1
     * @param rmAgentManagement
     * @return
     */
    @Override
    public int addUpdatePolicy(RmAgentManagement rmAgentManagement) {
        processAgentData(rmAgentManagement);
        return 1;
    }

    /**
     * 手动立即更新
     * @param rmAgentManagement 更新信息
     * @return
     */
    @Override
    public int updateAgentNow(RmAgentManagement rmAgentManagement) {
        processAgentData(rmAgentManagement);
        return 1;
    }

    /**
     * 处理agen更新数据
     * @param rmAgentManagement
     */
    public void processAgentData(RmAgentManagement rmAgentManagement){
        String clientIds = rmAgentManagement.getDeployDevice();
        String[] clientIdArr = clientIds.split("\n");
        for (String clientId : clientIdArr) {
            // 创建新的对象，避免污染原始数据
            RmAgentManagement currentAgent = new RmAgentManagement();
            // 复制原始对象的属性
            BeanUtils.copyProperties(rmAgentManagement, currentAgent);
            // 设置当前循环的 clientId
            currentAgent.setClientId(clientId);
            currentAgent.setDeployDevice(clientId);
            // 查询该资源是否已经配置
            RmAgentManagement agentQueryParam = new RmAgentManagement();
            agentQueryParam.setClientId(clientId);
            List<RmAgentManagement> agentManagements = rmAgentManagementMapper.selectRmAgentManagementList(agentQueryParam);
            if(!agentManagements.isEmpty()){
                // 如果存在，修改
                currentAgent.setLastUpdateTime(DateUtils.getNowDate());
                if("0".equals(rmAgentManagement.getMethod())){
                    currentAgent.setScheduledUpdateTime(null);
                }
                rmAgentManagementMapper.updateRmAgentManagement(currentAgent);
            }else{
                // 如果不存在，添加
                currentAgent.setLastUpdateTime(DateUtils.getNowDate());
                if("0".equals(rmAgentManagement.getMethod())){
                    currentAgent.setScheduledUpdateTime(null);
                }
                rmAgentManagementMapper.insertRmAgentManagement(currentAgent);
            }
            // 构建更新策略
            AgentUpdateMsgVo agentUpdateMsgVo = new AgentUpdateMsgVo();
            agentUpdateMsgVo.setFileUrl(rmAgentManagement.getFileUrl());
            agentUpdateMsgVo.setFileMd5(rmAgentManagement.getFileMd5());
            agentUpdateMsgVo.setMethod(rmAgentManagement.getMethod());
            if(rmAgentManagement.getMethod() == 1){
                Date scheduledUpdateTime = rmAgentManagement.getScheduledUpdateTime();
                long scheduledTime = scheduledUpdateTime.toInstant().getEpochSecond();
                agentUpdateMsgVo.setPolicyTime(scheduledTime);
            }
            try {
                PolicyVo<AgentUpdateMsgVo> policyVo = new PolicyVo();
                List<AgentUpdateMsgVo> list = new ArrayList<>();
                list.add(agentUpdateMsgVo);
                policyVo.setContents(list);
                String policyVoStr = JSONObject.toJSONString(policyVo);
                PolicyTypeVo policyTypeVo = new PolicyTypeVo();
                policyTypeVo.setVersions(policyVoStr);
                String configJson = JSONObject.toJSONString(policyTypeVo);
                DeviceMessage deviceMessage = new DeviceMessage();
                deviceMessage.setClientId(clientId);
                deviceMessage.setDataType(MsgEnum.获取最新策略应答.getValue());
                deviceMessage.setData(configJson);
                MessageProducer messageProducer = new MessageProducer();

                messageProducer.sendAsyncProducerMessage(
                        producerMode.getAgentTopic(),
                        "",
                        "",
                        JSONObject.toJSONString(deviceMessage)
                );
            } catch (Exception e) {
                log.error("发送设备配置失败，deviceId: {}", rmAgentManagement.getHardwareSn(), e);
            }
        }
    }
}
