package org.ts.ddcs.DataSaveProcesser;


import org.ts.ddcs.DataItemTemplate.DataItemTemplateImg;
import org.ts.ddcs.DataItemTemplate.DataItemTemplateInterface;
import org.ts.ddcs.DataTemplate.DataTemplateInterface;
import org.ts.ddcs.Entity.RtuImageEntity;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.Service.SwService;
import org.ts.ddcs.Tool.BytesHelp;
import org.ts.ddcs.Worker.DataProcessHolder;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.upload.FastImageFile;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * RTU上传图片
 * 0x36
 */
@SuppressWarnings("all")
public class DataSaveProcesserC36 extends DataSaveProcesser {

    @Override
    public void Save(DataTemplateInterface dataTemplateInterface) {
        super.Save(dataTemplateInterface);
        try {
            LogHelper.info("SAVE:" + dataTemplateInterface.GetFeture() + " " + BytesHelp.byte2HexStr(dataTemplateInterface.RtuCode()));
            String rtuCode = BytesHelp.byte2HexStr(dataTemplateInterface.RtuCode());
            HashMap<String, DataItemTemplateInterface> items = dataTemplateInterface.DataItem();
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (null != items) {
                if (items.containsKey("photo")) {
                    DataItemTemplateImg img = (DataItemTemplateImg) items.get("photo");
                    if (img.getPackageCount() == 1) {
                        String path = DataProcessHolder.newInstance().dataProcess.config.getRtuUploadPhotoPath() + File.separator + rtuCode;
                        File dir = new File(path);
                        if (!dir.exists()) {
                            dir.mkdir();
                        }
                        StringBuffer dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.CollectTime()));
                        String tm = "20" + dataStr.toString() + "00";
                        path += File.separator + tm.substring(0, 8);
                        dir = new File(path);
                        if (!dir.exists()) {
                            dir.mkdir();
                        }
                        String photoName = tm + ".jpg";
                        File file = new File(path + File.separator + photoName);
                        if (file.exists()) {
                            file.delete();
                        }
                        opsHash.put(rtuCode, "upload_photo", tm);
                        opsHash.put(rtuCode, "upload_photo_index", "" + img.getPackageCount());
                        //创建输入流
                        FileOutputStream outputStream = new FileOutputStream(file);
                        outputStream.write(img.getBuff());
                        outputStream.close();
                    } else if (img.getPackageSize() == img.getPackageCount()) {
                        String tm = opsHash.get(rtuCode, "upload_photo");
                        String saveIndex = opsHash.get(rtuCode, "upload_photo_index");
                        if (!saveIndex.equals("" + img.getPackageCount())) {
                            String path = DataProcessHolder.newInstance().dataProcess.config.getRtuUploadPhotoPath() + File.separator + rtuCode;
                            File dir = new File(path);
                            if (!dir.exists()) {
                                dir.mkdir();
                            }
                            path += File.separator + tm.substring(0, 8);
                            dir = new File(path);
                            if (!dir.exists()) {
                                dir.mkdir();
                            }
                            String photoName = tm + ".jpg";
                            File file = new File(path + File.separator + photoName);
                            if (file.exists()) {
                                FileOutputStream fos = new FileOutputStream(file, true);//追加写入
                                fos.write(img.getBuff());
                                fos.close();
                            }
                            opsHash.put(rtuCode, "upload_photo_index", "" + img.getPackageCount());

                            FileInputStream fileInputStream = new FileInputStream(file);
                            FastImageFile fastImageFile = new FastImageFile(fileInputStream, file.length(), "jpg", null);
                            StorePath storePath = DataProcessHolder.newInstance().dataProcess.fastFileStorageClient.uploadImage(fastImageFile);
                            String photoUrlPath = storePath.getFullPath();

                            SwService swService = DataProcessHolder.newInstance().dataProcess.swService;
                            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                            RtuImageEntity entity = new RtuImageEntity();
                            entity.setGroupId(rtuCode + tm);
                            entity.setRtuCode(rtuCode);
                            entity.setFileName(photoName);
                            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                            Date dt = timeFormat.parse(tm);
                            entity.setTm(new Timestamp(dt.getTime()));

                            // String savePath = "rtu" + File.separator + "img" + File.separator + DataProcessHolder.newInstance().dataProcess.config.getImageServerPath() + File.separator + photoName;
                            swService.SaveSwImage(uuid, photoUrlPath, entity);
                        }
                    } else {
                        String tm = opsHash.get(rtuCode, "upload_photo");
                        String saveIndex = opsHash.get(rtuCode, "upload_photo_index");
                        if (!saveIndex.equals("" + img.getPackageCount())) {
                            String path = DataProcessHolder.newInstance().dataProcess.config.getRtuUploadPhotoPath() + File.separator + rtuCode;
                            File dir = new File(path);
                            if (!dir.exists()) {
                                dir.mkdir();
                            }
                            path += File.separator + tm.substring(0, 8);
                            dir = new File(path);
                            if (!dir.exists()) {
                                dir.mkdir();
                            }
                            String photoName = tm + ".jpg";
                            File file = new File(path + File.separator + photoName);
                            if (file.exists()) {
                                FileOutputStream fos = new FileOutputStream(file, true);//追加写入
                                fos.write(img.getBuff());
                                fos.close();
                            }
                            opsHash.put(rtuCode, "upload_photo_index", "" + img.getPackageCount());
                        }
                    }
                }
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }
}
