package com.pqs9900.serviceImpl.DataInfo;

import com.njcn.utils.AppConfig;
import com.pqs9900.mapper.DataInfo.DownEventMapper;
import com.pqs9900.service.DataInfo.DownEventService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * system
 * 暂态事件业务
 *
 * @author cdf
 * @date 2021/9/29
 */
@Service
public class DownEventServiceImpl implements DownEventService {

    @Autowired
    private DownEventMapper downEventMapper;
    @Autowired
    private AppConfig appConfig;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addEventAndWave(MultipartFile[] multfile, Integer lineIndex, Date time, Integer ms, String describe, Integer waveType, Integer persistime, Float eventValue,String eventReason,String eventType,String ip) {
        Integer count = downEventMapper.isRight(time,lineIndex,ms);
        if(count>0){
            return "已存在相同暂态事件";
        }
        String guid = UUID.randomUUID().toString();
        Integer res = downEventMapper.addEventAndWave(guid, lineIndex, time, ms, describe, waveType, persistime,eventValue,eventReason,eventType);
        if (res == 1) {
            //开始保存文件

            for (MultipartFile multipartFile : multfile) {
                String filePath = appConfig.getWavePath() + File.separator + ip + File.separator + multipartFile.getOriginalFilename();
                File file = new File(filePath);
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                if(!file.exists()){
                        try {
                            file.createNewFile();
                            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
                        } catch (IOException e) {
                            e.printStackTrace();
                            throw new RuntimeException("9900暂态波形上传出错");
                        }
                }else {
                    throw new RuntimeException("已存在相同波形请勿重复上传！");
                }
            }

        }
        return "新增成功";
    }

    @Override
    public Integer updateWaveFlag(String evenDetailIndex) {
       return downEventMapper.updateWaveFlag(evenDetailIndex);
    }
}
