package net.vtstar.zhongtong.avi.gateway.trial.job;

import jcifs.smb.SmbFile;
import lombok.extern.slf4j.Slf4j;
import net.vtstar.user.mybatis.provider.Operation;
import net.vtstar.user.mybatis.provider.WhereFilter;
import net.vtstar.utils.CollecUtils;
import net.vtstar.utils.DateUtils;
import net.vtstar.zhongtong.avi.sqlserver.domain.TestSpeedResult;
import net.vtstar.zhongtong.avi.sqlserver.mapper.TestSpeedMapper;
import net.vtstar.zhongtong.avi.utils.PingIpUtils;
import net.vtstar.zhongtong.avi.utils.SmbFileUtil;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.*;

/**
 * 试交车间--错误帧
 *
 * @Author: xiadongwei
 * @Date: 2019/10/16 18:20
 */
@Slf4j
@Component
@DisallowConcurrentExecution
public class ErrorFrameJob extends QuartzJobBean {

    @Autowired
    private TestSpeedMapper mapper;

    @Value("${zt.ip.errorframe}")
    private String ipAddress;
    @Value("${zt.ip.pingtimes}")
    private int pingTimes;
    @Value("${zt.ip.timeout}")
    private int timeOut;

    private String baseUrl = "D:/scada/errorframe/";

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("--------开始同步试交车间错误帧数据--------");
        //ZTLOG_2019-10-26_11-35-46
        String dateString = DateUtils.parseDateToString(new Date(), "yyyy-MM-dd");
        if (!PingIpUtils.ping(ipAddress, pingTimes, timeOut)) {
            log.error("ping: {}失败, 此次同步试交车间错误帧数据操作结束!", ipAddress);
            return;
        }
        //todo:账户, 密码需要变
        String url = "smb://" + ipAddress + "/ztlog/";
        SmbFile file = null;
        InputStream in = null;
        List<String> fileName = new ArrayList<>();
        try {
            file = new SmbFile(url);
            if (file.exists()) {
                SmbFile[] files = file.listFiles();
                for (SmbFile f : files) {
                    String name = f.getName();
                    String[] split = name.split("_");
                    if (split.length != 3 || !dateString.equals(split[1])) {
                        continue;
                    }
                    fileName.add(name);
                }
            } else {
                log.error("试交车间错误帧共享文件夹: {}不存在!", url);
                return;
            }
            if (CollecUtils.isEmpty(fileName)) {
                log.error("试交车间错误帧共享文件夹中不存在当天日期的文件!", dateString);
                return;
            }
            for (String name : fileName){
                String urlName = url + name;
                SmbFile remoteFile = new SmbFile(urlName);
                if (!remoteFile.exists()) {
                    log.error("远程共享文件: {}不存在", urlName);
                    continue;
                }
                SmbFileUtil.smbGet(url, baseUrl + ipAddress);
            }
            List<TestSpeedResult> results = new ArrayList<>();
            for (String name : fileName) {
                String urlName = baseUrl + ipAddress + "/" + name;
                File remoteFile = new File(urlName);
                if (!remoteFile.exists()) {
                    log.error("本地共享文件: {}不存在", urlName);
                    continue;
                }
                List<TestSpeedResult> item = new ArrayList<>();
                in = new BufferedInputStream(new FileInputStream(urlName));
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                String lineString = "";
                String err = "";
                Map<Integer, String> vinMap = new HashMap<>();
                while ((lineString = bufferedReader.readLine()) != null) {
                    if (lineString.contains("cfeec21")) {
                        String[] split = lineString.split(",");
                        if (split.length == 3) {
                            if (split[1].trim().startsWith("01")) {
                                vinMap.put(1, split[1].trim());
                            }
                            if (split[1].trim().startsWith("02")) {
                                vinMap.put(2, split[1].trim());
                            }
                            if (split[1].trim().startsWith("03")) {
                                vinMap.put(3, split[1].trim());
                            }
                        }
                    }
                    if (lineString.contains("err=")) {
                        if (vinMap.size() == 3) {
                            StringBuilder vin = new StringBuilder();
                            for (int i = 1; i <= 3; i++) {
                                String[] ascString = vinMap.get(i).split(" ");
                                for (int j = 1; j < ascString.length; j++) {
                                    if ("ff".equals(ascString[j])){
                                        continue;
                                    }
                                    vin.append((char) Integer.parseInt(ascString[j], 16));
                                }
                            }
                            lineString.replace(" ", "");
                            err = lineString.substring(lineString.indexOf("err=") + 4, lineString.indexOf("rec=")).trim();
                            if (StringUtils.isEmpty(vin.toString()) || StringUtils.isEmpty(err)) {
                                continue;
                            }
                            TestSpeedResult result = new TestSpeedResult();
                            result.setVin(vin.toString());
                            result.setErrorFrame(Integer.valueOf(err));
                            item.add(result);
                            vinMap.clear();
                        }else{
                            vinMap.clear();
                        }
                    }
                }

                int errItem = 0;
                String vinItem = "";
                for (TestSpeedResult itemResult : item){
                    vinItem = itemResult.getVin();
                    if (itemResult.getErrorFrame() > errItem){
                        errItem = itemResult.getErrorFrame();
                    }
                }
                TestSpeedResult result = new TestSpeedResult();
                result.setVin(vinItem);
                result.setErrorFrame(errItem);
                result.setMODEL_ID("错误帧");
                String[] split = name.split("_");
                Date date = DateUtils.parse(split[1] + " " + split[2], "yyyy-MM-dd HH-mm-ss");
                result.setTestDate(date);
                results.add(result);
            }

            //当天零点
            Date startOfDay = DateUtils.getStartOfDay(0);
            String startString = DateUtils.parseDateToString(startOfDay, "yyyy-MM-dd HH-mm-ss");
            mapper.delByFilter(new WhereFilter() {{
                addFilter("test_date", Operation.GREATER_THAN, startString);
                addFilter("MODEL_ID", Operation.EQUAL, "错误帧");
            }}, TestSpeedResult.class);
            mapper.insertList(results);
            log.info("更新试交车间错误帧: {} 数据: {}条", ipAddress, results.size());
        } catch (Exception e) {
            log.error("获取试交车间错误帧共享文件失败!ip: {}", ipAddress);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("--------同步试交车间错误帧数据结束--------");
    }
}
