package  org.ts.ddcs.dataprocesser.jtDatagram;

import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.main.DataProcessHolder;
import org.ts.ddcs.common.constant.GBConstants;
import org.ts.ddcs.dataprocesser.DataProcesser;
import org.ts.ddcs.dataprocesser.DataProcesserInterface;
import org.ts.ddcs.dataStream.DataStreamAdapter;
import org.ts.ddcs.datatemplate.DataTemplateInterface;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.net.DataChannelHolder;
import org.ts.ddcs.util.BytesUtil;



import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 0x30
 * 测试报
 */

public class DataProcessorJtMultimedia extends DataProcesser implements DataProcesserInterface {

    @Override
    public void packetReadly(byte[] byteBuff, int pos, int length, DataStreamAdapter dataStreamAdapter, DataTemplateInterface template) {
        String logId = LogHelper.createLogId(dataStreamAdapter.getAdapterKey() + " " + this.getClass().getSimpleName());
        try {
            Date dt = new Date();
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            byte[] packetContext = template.datagramContext();
            byte[] rtuCodeBuff = template.rtuCode();
            String rtuCode = BytesUtil.byte2HexStr(rtuCodeBuff);
            LogHelper.info(logId + " " + " JT 808-功能码:0801 多媒体数据上报" + "-RTU:" + rtuCode);
            dataStreamAdapter.setCode(rtuCode);
            //拼装回复报文，先回复再解析入库
            byte[] funCode = new byte[2];
            funCode[0] = (byte) 0x88;
            funCode[1] = (byte) 0x00;
            byte[] respPacket = funCode;
            int len = 4;
            if (template.packageIndex() < template.packageTotal()) {
                len += 1;
            }
            //消息属性
            byte[] lenBuf = BytesUtil.int2Bytes(len);
            String bin = BytesUtil.bytesToBinStr(lenBuf);
            String parameter = "010000" + bin.substring(bin.length() - 10, bin.length());
            lenBuf = BytesUtil.binStrToBytes(parameter);
            respPacket = BytesUtil.arrayApend(respPacket, lenBuf);
            //版本
            byte[] ver = new byte[1];
            ver[0] = (byte) 0x01;
            respPacket = BytesUtil.arrayApend(respPacket, ver);
            //手机号
            respPacket = BytesUtil.arrayApend(respPacket, template.rtuCode());
            //流水号
            byte[] index = new byte[2];
            index[0] = (byte) 0x00;
            index[1] = (byte) 0x01;
            respPacket = BytesUtil.arrayApend(respPacket, index);
            byte[] body = template.body();
            //多媒体ID
            byte[] mid = new byte[4];
            System.arraycopy(body, 0, mid, 0, 4);
            respPacket = BytesUtil.arrayApend(respPacket, mid);
            if (template.packageIndex() < template.packageTotal()) {
                byte[] retryPackageNum = new byte[1];
                retryPackageNum[0] = 0x00;
                respPacket = BytesUtil.arrayApend(respPacket, retryPackageNum);
            }
            int crc = respPacket[0];
            for (int i = 1; i < respPacket.length; i++) {
                crc = crc ^ respPacket[i];
            }
            byte[] crcBuff = new byte[1];
            crcBuff[0] = (byte) crc;
            respPacket = BytesUtil.arrayApend(respPacket, crcBuff);
            byte[] respBuff = BytesUtil.subBytes(packetContext, 0, 1);
            respBuff = BytesUtil.arrayApend(respBuff, respPacket);
            respBuff = BytesUtil.arrayApend(respBuff, BytesUtil.subBytes(packetContext, 0, 1));
            dataStreamAdapter.output(respBuff);
            if (template.packageTotal() > 1) {
                if (template.packageIndex() == 1) {
                    dataStreamAdapter.keyStore.clear();
                    dataStreamAdapter.keyStore.put("" + template.packageIndex(), BytesUtil.byte2HexStr(template.datagramContext()));
                } else {
                    dataStreamAdapter.keyStore.put("" + template.packageIndex(), template.body());
                }
                if (template.packageIndex() == template.packageTotal()) {
                    byte[] mediaType = new byte[1];
                    System.arraycopy(body, 4, mediaType, 0, 1);
                    byte[] mediaTExt = new byte[1];
                    System.arraycopy(body, 5, mediaTExt, 0, 1);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    int fileSize = 0;
                    for (int i = 2; i <= template.packageTotal(); i++) {
                        byte[] buffer = (byte[]) dataStreamAdapter.keyStore.get("" + i);
                        byteArrayOutputStream.write(buffer, 0, buffer.length);
                        fileSize += buffer.length;
                    }
                    byteArrayOutputStream.flush();
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                    String fileName = "";
                    String type = "";
                    String ext = "";
                    if (mediaType[0] == 0) {
                        //图像
                        fileName = rtuCode + "-" + timeFormat.format(dt) + ".jpg";
                        ext = "jpg";
                        type = "image/jpeg";
                    } else if (mediaType[0] == 1) {
                        //音频
                    } else if (mediaType[0] == 2) {
                        //视频
                        if (mediaTExt[0] == 3) {
                            //wav
                            fileName = rtuCode + "-" + timeFormat.format(dt) + ".wav";
                            type = "video/wav";
                            ext = "wav";
                        } else if (mediaTExt[0] == 4) {
                            //wmv
                            fileName = rtuCode + "-" + timeFormat.format(dt) + ".wmv";
                            type = "video/wmv";
                            ext = "wmv";
                        }
                    }
//                    FastImageFile fastImageFile = new FastImageFile(byteArrayInputStream, fileSize, ext, null);
//                    StorePath storePath = DataProcessHolder.newInstance().dataProcess.fastFileStorageClient.uploadImage(fastImageFile);
//                    String photoUrlPath = storePath.getFullPath();
//                    String gram = (String) dataStreamAdapter.keyStore.get("1");
//                    JSONObject data = new JSONObject();
//                    data.put(GBConstants.BASE_KEY_DATAGRAM, gram);
//                    data.put(GBConstants.BASE_KEY_RTU, rtuCode.substring(4, 20));
//                    data.put(GBConstants.BASE_KEY_AGREEMENT, template.agreement());
//                    data.put(GBConstants.BASE_KEY_DATAGRAM_PICK_TM, timeFormat.format(dt));
//                    data.put("photoUrlPath", photoUrlPath);
//                    data.put("fileName", fileName);
//                    data.put("fileType", type);
//                    data.put("fileExt", ext);
//                    data.put("afc", BytesUtil.byte2HexStr(template.funcCode()));
//                    DataChannelHolder.newInstance().dataChannel.online(dataStreamAdapter);
//                    DataProcessHolder.newInstance().dataProcess.submitRelayDatagramTask(data);
                }
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }
}
