package com.yfd.platform.modules.basedata.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
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.yfd.platform.component.nettyclient.*;
import com.yfd.platform.config.HttpServerConfig;
import com.yfd.platform.constant.Constant;
import com.yfd.platform.constant.SystemCode;
import com.yfd.platform.modules.basedata.domain.AlgorithmModel;
import com.yfd.platform.modules.basedata.mapper.AlgorithmModelMapper;
import com.yfd.platform.modules.basedata.service.IAlgorithmModelService;
import com.yfd.platform.modules.robotapi.domain.PlatformParentSystem;
import com.yfd.platform.modules.robotapi.service.IPlatformParentSystemService;
import com.yfd.platform.utils.FileUtil;
import io.netty.util.CharsetUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 算法模型表 服务实现类
 * </p>
 *
 *
 * @since 2023-08-25
 */
@Service
public class AlgorithmModelServiceImpl extends ServiceImpl<AlgorithmModelMapper, AlgorithmModel> implements IAlgorithmModelService {

    @Resource
    private HttpServerConfig httpServerConfig;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Resource
    private IPlatformParentSystemService platformParentSystemService;

    /**********************************
     * 用途说明: 上传文件
     * 参数说明 file 文件域
     * 返回值说明: java.lang.String
     ***********************************/
    @Override
    public void uploadModelFile(MultipartFile file, String modelId) {
        // 文件存储地址
        String fileName =
                IdUtil.fastSimpleUUID() + "." + FileUtil.getExtensionName(file.getOriginalFilename());
        // 上传文件
        String name =
                Objects.requireNonNull(FileUtil.upload(file, httpServerConfig.getDocumentPath(), fileName)).getName();
        LambdaUpdateWrapper<AlgorithmModel> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AlgorithmModel::getId, modelId).set(AlgorithmModel::getCustom1, name);
        this.update(updateWrapper);
    }

    /**********************************
     * 用途说明: 预览模型文件
     * 参数说明 fileName 文件名称
     * 参数说明 response
     * 返回值说明: void
     ***********************************/
    @Override
    public void viewModelFile(String fileName, HttpServletResponse response) throws IOException {
        boolean exist = FileUtil.exist(httpServerConfig.getDocumentPath() + fileName);
        if (!exist) {
            throw new RuntimeException("文件不存在");
        }
        FileUtil.viewPDF(httpServerConfig.getDocumentPath() + fileName, response);
    }

    /**********************************
     * 用途说明: 删除模型文件
     * 参数说明 id 模型id
     * 参数说明 fileName 文件名称
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean deleteModelFile(String id, String fileName) {
        boolean exist = FileUtil.exist(httpServerConfig.getDocumentPath() + fileName);
        if (!exist) {
            throw new RuntimeException("删除失败");
        }
        FileUtil.del(httpServerConfig.getDocumentPath() + fileName);
        LambdaUpdateWrapper<AlgorithmModel> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AlgorithmModel::getId, id).set(AlgorithmModel::getCustom1, "");
        return this.update(updateWrapper);

    }

    @Override
    public void getRecogParams(String sectionId, String stationId, String type) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOnce("section_id", sectionId);
        jsonObject.putOnce("station_id", stationId);
        jsonObject.putOnce("type", type);
        this.sendAlgorithmData(SystemCode.TYPE_ALGORITHM_PARAM_CODE.getCode(), "", "", jsonObject.toString());
    }

    @Override
    public void getHistoryVersion(String sectionId, String stationId, String type, String algorithmManufacturer) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOnce("section_id", sectionId);
        jsonObject.putOnce("station_id", stationId);
        jsonObject.putOnce("type", type);
        jsonObject.putOnce("algorithm_manufacturer", algorithmManufacturer);
        this.sendAlgorithmData(SystemCode.TYPE_ALGORITHM_VERSION_CODE.getCode(), "", "", jsonObject.toString());
    }

    @Override
    public void updateAlgorithmVersion(String sectionId, String stationId, String type, String version) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOnce("section_id", sectionId);
        jsonObject.putOnce("station_id", stationId);
        jsonObject.putOnce("type", type);
        jsonObject.putOnce("version", version);
        this.sendAlgorithmData(SystemCode.TYPE_ALGORITHM_UPDATE_CODE.getCode(), "", "", jsonObject.toString());
    }

    public void sendAlgorithmData(String Type, String Command, String Code, String Items) {
        List<PlatformParentSystem> list =
                platformParentSystemService.list(new LambdaQueryWrapper<PlatformParentSystem>().eq(PlatformParentSystem::getIsEnable, "1"));
        if (list.size() <= 0) {
            return;
        }
        PlatformParentSystem platformParentSystem = list.get(0);
        String xml = MyXmlUtil.getXml(httpServerConfig.getPatrolServerid(), platformParentSystem.getParentCode(), Type
                , Command, Code, Items);
        MyMessageProtocol messageProtocol = new MyMessageProtocol();
        long requestSessionID = BootSessionCache.getRequestSessionID();
        messageProtocol.setSenderSerialNo(requestSessionID);
        redisTemplate.opsForValue().set(Constant.CLOUD_SEND_CODE + requestSessionID, xml);
        messageProtocol.setReceiverSerialNo(0L);
        messageProtocol.setSessionflag(0);
        messageProtocol.setXmllen(xml.getBytes(CharsetUtil.UTF_8).length);
        messageProtocol.setXmlcontent(xml.getBytes(CharsetUtil.UTF_8));
        if (BootNettyClientChannelCache.channelMapCache.size() > 0) {
            for (Map.Entry<String, BootNettyClientChannel> entry :
                    BootNettyClientChannelCache.channelMapCache.entrySet()) {
                BootNettyClientChannel bootNettyChannel = entry.getValue();
                if (bootNettyChannel != null && bootNettyChannel.getChannel().isOpen()) {
                    bootNettyChannel.getChannel().writeAndFlush(messageProtocol);
                }
            }
        }
    }

}
