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.WheelAlignment;
import net.vtstar.zhongtong.avi.access.mapper.WheelAlignmentMapper;
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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 底盘车间--四轮定位
 * @Author: xiadongwei
 * @Date: 2019/10/16 18:20
 */
@Slf4j
@Component
@DisallowConcurrentExecution
public class WheelAlignmentJob extends QuartzJobBean {

    @Autowired
    private WheelAlignmentMapper mapper;

    @Value("${zt.ip.wheelalignment1}")
    private String ipAddress1;
    @Value("${zt.ip.wheelalignment2}")
    private String ipAddress2;
    @Value("${zt.ip.wheelalignment3}")
    private String ipAddress3;
    @Value("${zt.ip.pingtimes}")
    private int pingTimes;
    @Value("${zt.ip.timeout}")
    private int timeOut;

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

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        List<String> ipAddressList = Arrays.asList(ipAddress1, ipAddress2, ipAddress3);
        log.info("--------开始同步底盘车间四轮定位数据--------");
        //2019Apr30.mdb 数据文件命名格式
        Date startOfDay = DateUtils.getStartOfDay(0);
        String dateString = DateUtils.parseDateToString(startOfDay, "yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMMdd", Locale.ENGLISH);
        String newDateString = sdf.format(new Date());
        String dataBaseFileName = "BL_Align";
        for (String ipAddress : ipAddressList){
            if (!PingIpUtils.ping(ipAddress, pingTimes, timeOut)) {
                log.error("ping: {}失败, 此次同步底盘四轮定位数据操作结束!", ipAddress);
                continue;
            }
            //todo:账户, 密码, 文件位置需要变 BL_Align(数据库文件)
            String url = "smb://" + ipAddress + "/Database/" + dataBaseFileName + ".mdb";
            SmbFile file = null;
            String dateFile = baseUrl + ipAddress + "/" + newDateString + "/" + "BL_Align.mdb";
            try {
                file = new SmbFile(url);
                if (file.exists()) {
                    SmbFileUtil.smbGet(url, baseUrl + ipAddress + "/" + newDateString);
                }else {
                    log.error("日期: {} 的底盘车间四轮定位共享数据库文件不存在!", url);
                    continue;
                }
                Database db;
                List<WheelAlignment> list = new ArrayList<>();;
                try {
                    db = DatabaseBuilder.open(new File(dateFile));
                    Set<String> tableNames = db.getTableNames();
                    for (String tableName : tableNames) {
                        /*if ("LEGEND-5214E5AF".equals(tableName)){
                            saveData(ipAddress, db, list, tableName);
                        }*/
                        if (newDateString.equals(tableName)){
                            saveData(ipAddress, db, list, tableName);
                        }
                    }
                } catch (IOException e) {
                    log.error("读取日期: {} 的数据库文件失败!ip: {}", dateString, ipAddress);
                    continue;
                }
                if (list.size() == 0){
                    continue;
                }
                mapper.delByFilter(new WhereFilter() {{
                    addFilter("create_time", Operation.GREATER_THAN, dateString);
                    addFilter("ipAddress", Operation.EQUAL, ipAddress);
                }}, WheelAlignment.class);
                mapper.insertList(list);
                log.info("更新四轮定位: {} 数据: {}条", ipAddress, list.size());
            } catch (Exception e) {
                log.error("获取底盘车间四轮定位共享文件失败!ip: {}", ipAddress);
            }
        }
        log.info("--------同步底盘车间四轮定位数据结束--------");
    }

    private void saveData(String ipAddress, Database db, List<WheelAlignment> list, String tableName) throws IOException {
        Table table = db.getTable(tableName);
        for (Row row : table) {
            WheelAlignment map = new WheelAlignment();
            map.setWorkOrderID(row.getString("WorkOrderID"));
            map.setStartDateTime(row.getString("StartDateTime"));
            map.setEndDateTime(row.getString("EndDateTime"));
            map.setMake(row.getString("Make"));
            map.setModel(row.getString("Model"));
            map.setVIN(row.getString("VIN"));
            map.setLFToeI(row.getInt("LFToeI") == 99999 ? "" : new BigDecimal(row.getInt("LFToeI") / 51.2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "mm");
            map.setLFToeF(row.getInt("LFToeF") == 99999 ? "" : new BigDecimal(row.getInt("LFToeF") / 51.2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "mm");
            map.setRFToeI(row.getInt("RFToeI") == 99999 ? "" : new BigDecimal(row.getInt("RFToeI") / 51.2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "mm");
            map.setRFToeF(row.getInt("RFToeF") == 99999 ? "" : new BigDecimal(row.getInt("RFToeF") / 51.2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "mm");
            map.setLFCamI(row.getInt("LFCamI") == 99999 ? "" : (row.getInt("LFCamI") / 1000) + "°" + (Math.round((row.getInt("LFCamI") % 1000 * 60 / 1000f))) + "′");
            map.setLFCamF(row.getInt("LFCamF") == 99999 ? "" : (row.getInt("LFCamF") / 1000) + "°" + (Math.round((row.getInt("LFCamF") % 1000 * 60 / 1000f))) + "′");
            map.setRFCamI(row.getInt("RFCamI") == 99999 ? "" : (row.getInt("RFCamI") / 1000) + "°" + (Math.round((row.getInt("RFCamI") % 1000 * 60 / 1000f))) + "′");
            map.setRFCamF(row.getInt("RFCamF") == 99999 ? "" : (row.getInt("RFCamF") / 1000) + "°" + (Math.round((row.getInt("RFCamF") % 1000 * 60 / 1000f))) + "′");
            map.setLCasI(row.getInt("LCasI") == 99999 ? "" : (row.getInt("LCasI") / 1000) + "°" + (Math.round((row.getInt("LCasI") % 1000 * 60 / 1000f))) + "′");
            map.setLCasF(row.getInt("LCasF") == 99999 ? "" : (row.getInt("LCasF") / 1000) + "°" + (Math.round((row.getInt("LCasF") % 1000 * 60 / 1000f))) + "′");
            map.setRCasI(row.getInt("RCasI") == 99999 ? "" : (row.getInt("RCasI") / 1000) + "°" + (Math.round((row.getInt("RCasI") % 1000 * 60 / 1000f))) + "′");
            map.setRCasF(row.getInt("RCasF") == 99999 ? "" : (row.getInt("RCasF") / 1000) + "°" + (Math.round((row.getInt("RCasF") % 1000 * 60 / 1000f))) + "′");
            //TODO:LKpiI/256*15′
            int lKpiI = Math.round(row.getInt("LKpiI") % 1000 / 250f);
            if (lKpiI == 4){
                map.setLKpiI(row.getInt("LKpiI") == 99999 ? "" : (row.getInt("LKpiI") / 1000 + 1) + "°" + "0′");
            }else{
                map.setLKpiI(row.getInt("LKpiI") == 99999 ? "" : (row.getInt("LKpiI") / 1000 + 1) + "°" + (lKpiI * 15) + "′");
            }
            int lKpiF = Math.round(row.getInt("LKpiF") % 1000 / 250f);
            if (lKpiF == 4){
                map.setLKpiF(row.getInt("LKpiF") == 99999 ? "" : (row.getInt("LKpiF") / 1000 + 1) + "°" + "0′");
            }else{
                map.setLKpiF(row.getInt("LKpiF") == 99999 ? "" : (row.getInt("LKpiF") / 1000) + "°" + (lKpiF * 15) + "′");
            }
            int rKpiI = Math.round(row.getInt("RKpiI") % 1000 / 250f);
            if (rKpiI == 4){
                map.setRKpiI(row.getInt("RKpiI") == 99999 ? "" : (row.getInt("RKpiI") / 1000 + 1) + "°" + "0′");
            }else{
                map.setRKpiI(row.getInt("RKpiI") == 99999 ? "" : (row.getInt("RKpiI") / 1000) + "°" + (rKpiI * 15) + "′");
            }
            int rKpiF = Math.round(row.getInt("RKpiF") % 1000 / 250f);
            if (rKpiF == 4){
                map.setRKpiF(row.getInt("RKpiF") == 99999 ? "" : (row.getInt("RKpiF") / 1000 + 1) + "°" + "0′");
            }else{
                map.setRKpiF(row.getInt("RKpiF") == 99999 ? "" : (row.getInt("RKpiF") / 1000) + "°" + (rKpiF * 15) + "′");
            }

            map.setLAckermanF(row.getDouble("LAckermanF") == 99999.1 ? "" : String.valueOf(new BigDecimal(row.getDouble("LAckermanF")).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "°");
            map.setRAckermanF(row.getDouble("RAckermanF") == 99999.1 ? "" : String.valueOf(new BigDecimal(row.getDouble("RAckermanF")).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "°");
            map.setLMaxTurnF(row.getDouble("LMaxTurnF") == 99999.1 ? "" : String.valueOf(new BigDecimal(row.getDouble("LMaxTurnF")).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "°");
            map.setRMaxTurnF(row.getDouble("RMaxTurnF") == 99999.1 ? "" : String.valueOf(new BigDecimal(row.getDouble("RMaxTurnF")).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "°");
            map.setTandem0I(row.getInt("Tandem0I") == 99999 ? "0" : new BigDecimal((row.getInt("Tandem0I") / 47.5)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "mm");
            map.setTandem0D1I(row.getInt("Tandem0D1I") == 99999 ? "0" :  new BigDecimal((row.getInt("Tandem0D1I") / 115.926)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "mm");
            map.setIpAddress(ipAddress);
            map.setCreateTime(new Date());
            list.add(map);
        }
    }
}
