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.sqlserver.domain.TestLineResult;
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.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);
                return;
            }
            //todo:账户, 密码需要变
            String url = "smb://wanteng:wanteng@" + ipAddress + "/AN9637H/testdata@" + dateString + ".mdb";
            SmbFile file = null;
            try {
                file = new SmbFile(url);
                if (file.exists()) {
                    SmbFileUtil.smbGet(url, baseUrl + "testdata@" + dateString + ".mdb");
                }else {
                    log.error("日期: {} 的总装车间新能源检测点共享文件不存在!", dateString);
                    continue;
                }
                Database db;
                List<AssemblyNewEnergy> list = new ArrayList<>();;
                try {
                    db = DatabaseBuilder.open(new File(baseUrl + "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(row.getDouble("ResultValue"));
                            map.setResultUnit(row.getString("ResultUnit"));
                            map.setSystemTime(dateString + row.getString("SystemTime"));
                            map.setIpAddress(ipAddress);
                            map.setCreateTime(new Date());
                            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);
                }}, TestLineResult.class);
                assemblyNewEnergyMapper.insertList(list);
                log.info("更新新能源检测点: {} 数据: {}条", ipAddress, list.size());
            } catch (Exception e) {
                log.error("获取总装车间新能源检测点共享文件失败!ip: {}", ipAddress);
            }
        }
        log.info("--------同步总装车间新能源检测点数据结束--------");
    }
}
