package com.inspect.metadata.montdatamqhandle.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspect.base.core.constant.Color;
import com.inspect.metadata.alg.mapper.BasedataAlgSubtypeMapper;
import com.inspect.metadata.area.mapper.BaseDataAreaMapper;
import com.inspect.metadata.bdconfig.domain.BasedataBdConfigMainSystem;
import com.inspect.metadata.bdconfig.mapper.BasedataBdConfigAlgConvertMapper;
import com.inspect.metadata.bdconfig.mapper.BasedataBdConfigDeviceConvertMapper;
import com.inspect.metadata.bdconfig.mapper.BasedataBdConfigMainSystemMapper;
import com.inspect.metadata.eqpbook.mapper.BasedataEqpBookMapper;
import com.inspect.metadata.montdatamqhandle.service.IBasedataMontDataHandleService;
import com.inspect.metadata.montdatamqhandle.service.component.BasedataMontPatrolPointHandleComponent;
import com.inspect.metadata.montdatamqhandle.vo.ModelFileItem;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataPatrolPointMapper;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataPatrolPointPresetMapper;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataStdPatrolPointMapper;
import com.inspect.metadata.patrolpointmnt.service.IBasedataPatrolPointService;
import com.inspect.metadata.prodevmnt.mapper.BasedataDeviceMapper;
import com.inspect.metadata.prodevmnt.mapper.BasedataDeviceTypeMapper;
import com.inspect.base.core.sftp.SftpClient;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component("basedataMont-modelup-1024")
public class BasedataMontPatrolPointConsumerHandle implements IBasedataMontDataHandleService {

    @Value("${test-mode:false}")
    private boolean testMode;
    @Resource
    private IBasedataPatrolPointService basedataPatrolPointService;
    @Resource
    private BasedataDeviceTypeMapper basedataDevicetypeMapper;
    @Resource
    private BasedataDeviceMapper basedataDeviceMapper;
    @Resource
    BasedataStdPatrolPointMapper basedataStdpatrolPointMapper;
    @Resource
    BasedataPatrolPointPresetMapper basedataPatrolpointPresetMapper;
    @Resource
    BasedataEqpBookMapper basedataEqpbookMapper;
    @Resource
    BasedataBdConfigMainSystemMapper basedataBdconfigMainsystemMapper;
    @Resource
    BasedataBdConfigDeviceConvertMapper basedataBdconfigDeviceConvertMapper;
    @Resource
    BasedataBdConfigAlgConvertMapper basedataBdconfigAlgConvertMapper;
    @Resource
    BasedataAlgSubtypeMapper basedataAlgSubtypeMapper;
    @Resource
    BasedataMontPatrolPointHandleComponent basedataMontPatrolPointHandleComponent;
    @Resource
    private SftpClient sftpClient;
    @Resource
    private BaseDataAreaMapper baseDataAreaMapper;
    @Resource
    private BasedataPatrolPointPresetMapper basedataPatrolPointPresetMapper;
    @Resource
    private BasedataPatrolPointMapper basedataPatrolpointMapper;

    public void handleMontData(JSONObject jsonObject) {
        log.info(Color.CYAN + "handleMontData-modelup-1024: {}" + Color.END, jsonObject.toString());
        String Type = jsonObject.getString("Type");
        String convertFlag = "0";
        String SendCode = jsonObject.getString("SendCode");
//        if(testMode) {
//            log.info(Color.BLUE + "HANDLE_MONT_DATA MODEL SYNC SendCode: {}, delete old data Start" + Color.END, SendCode);
//            deletePatrolPointPresetBySendCode(SendCode);
//            log.info(Color.BLUE + "HANDLE_MONT_DATA MODEL SYNC SendCode: {}, delete old data End" + Color.END, SendCode);
//        }
        BasedataBdConfigMainSystem mainSystem = basedataBdconfigMainsystemMapper.selectBasedataBdConfigMainSystemByMainSystemCode(SendCode);
        if (null != mainSystem) {
            String flag = mainSystem.getConvertFlag();
            if (null != flag && flag.equals("1")) {
                convertFlag = "1";
            }
        }

        JSONArray jsonObjectItems = jsonObject.getJSONArray("Items");
        List<ModelFileItem> list = jsonObjectItems.toJavaList(ModelFileItem.class);
        log.info("MODEL_SYNC list: {}, jsonObject: {}", list, jsonObject);
        if (list != null && !list.isEmpty()) {
            String modelString;
            for (Iterator<ModelFileItem> iterator = list.iterator(); iterator.hasNext(); basedataMontPatrolPointHandleComponent.handPointModelData(SendCode, modelString)) {
                ModelFileItem item = iterator.next();
                String deviceFilePath = item.getDevice_file_path();
                log.info("MODEL_SYNC filePath: {}", deviceFilePath);
                ByteBuf byteBuf = Unpooled.buffer();
                try {
                    sftpClient.downLoad(deviceFilePath, (inputStream) -> {
                        byte[] bytes = new byte[1024];
                        int index;
                        while ((index = inputStream.read(bytes)) > -1) {
                            byteBuf.writeBytes(Arrays.copyOfRange(bytes, 0, index));
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(bytes);
                modelString = "";

                try {
                    modelString = new String(bytes, "UTF-8");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            log.info("MODEL_SYNC modelFile: {}, jsonObject: {}", list, jsonObject);
        }
    }

    public void handleMontDataEx(JSONObject jsonObject) {
        log.info(Color.CYAN + "MODEL_SYNC_EX model_up_1024: {}" + Color.END, jsonObject.toString());
        String SendCode = jsonObject.getString(("SendCode"));
        JSONArray jsonObjectItems = jsonObject.getJSONArray(("Items"));
        List<ModelFileItem> list = jsonObjectItems.toJavaList(ModelFileItem.class);
        log.info("MODEL_SYNC_EX list: {}, jsonObject: {}", list, jsonObject);
        if (list != null && !list.isEmpty()) {
            String modelString;
            for (Iterator<ModelFileItem> iterator = list.iterator(); iterator.hasNext(); basedataMontPatrolPointHandleComponent.handPointModelData(SendCode, modelString)) {
                ModelFileItem item = iterator.next();
                String deviceFilePath = item.getDevice_file_path();
                log.info("MODEL_SYNC_EX filePath: {}", deviceFilePath);
                ByteBuf byteBuf = Unpooled.buffer();
                try {
                    sftpClient.downLoad(deviceFilePath, (inputStream) -> {
                        byte[] bytes = new byte[1024];
                        int index;
                        while ((index = inputStream.read(bytes)) > -1) {
                            byteBuf.writeBytes(Arrays.copyOfRange(bytes, 0, index));
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(bytes);

                modelString = new String(bytes, StandardCharsets.UTF_8);
            }

            log.info("MODEL_SYNC_EX modelFile: {}, jsonObject: {}", list, jsonObject);
        }
    }

    public void delMontData(JSONObject jsonObject) {
        log.info(Color.CYAN + "delMontData-modelup-1024: {}" + Color.END, jsonObject.toString());
        String SendCode = jsonObject.getString("SendCode");
        if (testMode) {
            log.info(Color.BLUE + "DEL_MONT_DATA MODEL SYNC SendCode: {}, delete old data Start" + Color.END, SendCode);
            deletePatrolPointPresetBySendCode(SendCode);
            log.info(Color.BLUE + "DEL_MONT_DATA MODEL SYNC SendCode: {}, delete old data End" + Color.END, SendCode);
        }
    }

    private void deletePatrolPointPresetBySendCode(String sendCode) {
        // basedata_area 区域删除
        int areaNum = baseDataAreaMapper.deleteAreaBySendCode(sendCode);
        // basedata_device 删除
        int deviceNum = basedataDeviceMapper.deleteBySendCode(sendCode);
        // basedata_patrolpoint_preset  删除
        int patrolPointPresetNum = basedataPatrolPointPresetMapper.deleteBySendCode(sendCode);
        // basedata_patrolpoint 删除
        int patrolPointNum = basedataPatrolpointMapper.deleteBySendCode(sendCode);
        log.info(Color.BLUE + "[METADATA] 模型同步删除数据：区域{}条，设备{}条，巡检点预设{}条，巡检点{}条" + Color.END, areaNum, deviceNum, patrolPointPresetNum, patrolPointNum);
    }
}
