package net.vtstar.zhongtong.avi.access.job;

import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;
import com.healthmarketscience.jackcess.Row;
import com.healthmarketscience.jackcess.Table;
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.DateUtils;
import net.vtstar.zhongtong.avi.access.domain.AssemblyNewEnergy;
import net.vtstar.zhongtong.avi.access.mapper.AssemblyNewEnergyMapper;
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 java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 总装车间--新能源检测点
 *
 * @Author: xiadongwei
 * @Date: 2019/10/16 18:20
 */
@Slf4j
@Component
@DisallowConcurrentExecution
public class AssemblyNewEnergyJob extends QuartzJobBean {

    @Autowired
    private AssemblyNewEnergyMapper assemblyNewEnergyMapper;

    @Value("${zt.ip.assemblynewenergy1}")
    private String ipAddress1;
    @Value("${zt.ip.assemblynewenergy2}")
    private String ipAddress2;
    @Value("${zt.ip.assemblynewenergy3}")
    private String ipAddress3;
    @Value("${zt.ip.assemblynewenergy4}")
    private String ipAddress4;
    @Value("${zt.ip.pingtimes}")
    private int pingTimes;
    @Value("${zt.ip.timeout}")
    private int timeOut;

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

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        List<String> ipAddressList = Arrays.asList(ipAddress1, ipAddress2, ipAddress3, ipAddress4);
        log.info("--------开始同步总装车间新能源检测点数据--------");
        //testdata@2018-05-05 数据文件命名格式
        Date startOfDay = DateUtils.getStartOfDay(0);
        String dateString = DateUtils.parseDateToString(startOfDay, "yyyy-MM-dd");
        for (String ipAddress : ipAddressList){
            if (!PingIpUtils.ping(ipAddress, pingTimes, timeOut)) {
                log.error("ping: {}失败, 此次同步总装新能源检测点数据操作结束!", ipAddress);
                continue;
            }
            //todo:账户, 密码需要变
            String url = "smb://admin:123456@" + ipAddress + "/AN9637H/testdata@" + dateString + ".mdb";
//            String url = "smb://admin:123456@10.1.25.128/an9637h/test/data@2018-05-04.mdb";
            SmbFile file = null;
            try {
                file = new SmbFile(url);
                if (file.exists()) {
                    SmbFileUtil.smbGet(url, baseUrl + ipAddress);
                }else {
                    log.error("日期: {} 的总装车间新能源检测点共享文件不存在!", dateString);
                    continue;
                }
                Database db;
                List<AssemblyNewEnergy> list = new ArrayList<>();
                try {
                    db = DatabaseBuilder.open(new File(baseUrl + ipAddress + "/" + "testdata@" + dateString + ".mdb"));
                    Set<String> tableNames = db.getTableNames();
                    for (String tableName : tableNames) {
                        if (!"TestConditionResult".equals(tableName)){
                            continue;
                        }
                        Table table = db.getTable(tableName);
                        for (Row row : table) {
                            AssemblyNewEnergy map = new AssemblyNewEnergy();
                            map.setSerialNo(row.getString("SerialNo"));
                            map.setTIName(row.getString("TIName"));
                            map.setResultValue(new BigDecimal(row.getDouble("ResultValue")).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue());
                            map.setResultUnit(row.getString("ResultUnit"));
                            map.setSystemTime(dateString + " " + row.getString("SystemTime"));
                            map.setIpAddress(ipAddress);
                            map.setCreateTime(DateUtils.parse(dateString + " " + row.getString("SystemTime"), "yyyy-MM-dd HH:mm:ss"));
                            list.add(map);
                        }
                    }
                } catch (IOException e) {
                    log.error("读取日期: {} 的数据库文件失败!ip: {}", dateString, ipAddress);
                    continue;
                }
                assemblyNewEnergyMapper.delByFilter(new WhereFilter() {{
                    addFilter("SystemTime", Operation.LIKE, dateString);
                    addFilter("ipAddress", Operation.EQUAL, ipAddress);
                }}, AssemblyNewEnergy.class);
                assemblyNewEnergyMapper.insertList(list);
                log.info("更新新能源检测点: {} 数据: {}条", ipAddress, list.size());
            } catch (Exception e) {
                log.error("获取总装车间新能源检测点共享文件失败!ip: {}", ipAddress);
            }
        }
        log.info("--------同步总装车间新能源检测点数据结束--------");
    }
}
