package com.ningdatech.carapi.irs.manage;

import static com.ningdatech.carapi.irs.service.AbstractLicenseGetByIrsService.DELAY_MINUTES;

import java.io.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ningdatech.carapi.irs.entity.DriversLicenseRaw;
import com.ningdatech.carapi.irs.service.DriverService;
import com.ningdatech.carapi.irs.service.IDriversLicenseRawService;
import com.ningdatech.carapi.irs.service.PullLicenseByIrsService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdcardUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * IrsLicensePullTask
 * </p>
 *
 * @author WendyYang
 * @since 2023/5/16
 **/
@Component
@Slf4j
public class IrsDriversLicenseManage {


    private final PullLicenseByIrsService driverLicenseGetService;
    private final PullLicenseByIrsService drivingLicenseGetService;
    private final DriverService driverService;
    private final IDriversLicenseRawService driversLicenseRawService;


    public IrsDriversLicenseManage(@Qualifier("drivingLicensePullByIrsService") PullLicenseByIrsService driverLicenseGetService,
                                   @Qualifier("drivingLicensePullByIrsService") PullLicenseByIrsService drivingLicenseGetService,
                                   DriverService driverService, 
                                   IDriversLicenseRawService driversLicenseRawService) {
        this.driverLicenseGetService = driverLicenseGetService;
        this.drivingLicenseGetService = drivingLicenseGetService;
        this.driverService = driverService;
        this.driversLicenseRawService = driversLicenseRawService;
    }

    @PostConstruct
    public void initTask() {
        driverLicenseGetService.initPullLicenseTask();
        drivingLicenseGetService.initPullLicenseTask();
    }

    public void submitDriverLicensePullTask() {
        driverLicenseGetService.startPullLicenseTask(DELAY_MINUTES);
    }

    public void submitDrivingLicensePullTask() {
        drivingLicenseGetService.startPullLicenseTask(DELAY_MINUTES);
    }

    public void vehicleLicenseSingleSave() {
        List<String> list = new ArrayList<>();
        Set<String> set = new HashSet<>();

        File directory = new File("");
        //临时文件存储路径
        String filePath = directory.getAbsolutePath() + File.separator + "irs";
        File f = new File( filePath +  File.separator +  "行驶证身份证号.xlsx");
        Workbook wb = null;
        try {
            wb = readExcel(new FileInputStream(f), f.getName());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Row row = null;
        if (wb != null) {
            //获取第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);

            //获取最大列数
            for (int i = 1; i < rownum; i++) {
                row = sheet.getRow(i);
                // 身份证号
                String idCard = Objects.nonNull(row.getCell(0)) ? row.getCell(0).toString() : StringUtils.EMPTY;
                list.add(idCard);
            }
        }

        // 去重并校验身份证号
        List<String> idCardList = list.stream()
                .filter(set::add)
                .filter(IdcardUtil::isValidCard)
                .collect(Collectors.toList());

        // 调用IRS接口,返回数据
        // 访问计数
        int count = 0;
        for (String idCard : idCardList) {
            String dataJsonStr = driverService.vehicleLicenseQuery(idCard);
            count++;
            log.info("已访问行驶证查询IRS接口 {} 次", count);
            log.info("此次访问的行驶证身份证号为 {}",idCard);
            JSONObject object = JSON.parseObject(dataJsonStr, JSONObject.class);
            String data = object.getString("datas");
            List<JSONObject> array = JSON.parseArray(data, JSONObject.class);
            if (CollUtil.isEmpty(array)) {
                log.info("该身份证号没有行驶证信息!");
                continue;
            }
            // 获取身份证号的所有行驶证信息
            Map<String, List<DriversLicenseRaw>> drivingLicenseMap = driversLicenseRawService.list().stream()
                    .collect(Collectors.groupingBy(DriversLicenseRaw::getIdcard));
            
            for (JSONObject jsonObject : array) {
                if (Objects.nonNull(jsonObject)) {
                    // 获取发证日期，判断是否重复
                    Timestamp fZRQ = jsonObject.getTimestamp("fZRQ");

                    List<DriversLicenseRaw> driversLicenseRaws = drivingLicenseMap.get(idCard);

                    List<DriversLicenseRaw> licenseRaws = Lists.newArrayList();
                    if (CollUtil.isNotEmpty(driversLicenseRaws)) {
                        licenseRaws = driversLicenseRaws.stream().filter(d -> {
                            String detail = d.getDrivingLicenseDetail();
                            JSONObject json = JSON.parseObject(detail, JSONObject.class);
                            Timestamp timestamp = json.getTimestamp("fZRQ");
                            if (timestamp.equals(fZRQ)) {
                                return true;
                            } else {
                                return false;
                            }
                        }).collect(Collectors.toList());
                    }
                    // 保存新增的行驶证信息
                    if (CollUtil.isNotEmpty(licenseRaws)) {
                        DriversLicenseRaw driversLicenseRaw = new DriversLicenseRaw();
                        driversLicenseRaw.setIdcard(idCard);
                        String jsonString = jsonObject.toJSONString();
                        driversLicenseRaw.setDrivingLicenseDetail(jsonString);
                        driversLicenseRaw.setCreateOn(LocalDateTime.now());
                        driversLicenseRaw.setUpdateOn(LocalDateTime.now());
                        driversLicenseRawService.save(driversLicenseRaw);
                    }
                    
                }
            }
        }
    }

    public void drivingLicenseSingleSave() {
        List<String> list = new ArrayList<>();
        Set<String> set = new HashSet<>();

        File directory = new File("");
        //临时文件存储路径
        String filePath = directory.getAbsolutePath() + File.separator + "irs";
        File f = new File( filePath +  File.separator +  "驾驶证身份证号.xlsx");
        Workbook wb = null;
        try {
            wb = readExcel(new FileInputStream(f), f.getName());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Row row = null;
        if (wb != null) {
            //获取第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);

            //获取最大列数
            for (int i = 1; i < rownum; i++) {
                row = sheet.getRow(i);
                // 身份证号
                String idCard = Objects.nonNull(row.getCell(0)) ? row.getCell(0).toString() : StringUtils.EMPTY;
                list.add(idCard);
            }
        }

        // 去重并校验身份证号
        List<String> idCardList = list.stream()
                .filter(set::add)
                .filter(IdcardUtil::isValidCard)
                .collect(Collectors.toList());

        // 调用IRS接口,返回数据
        // 访问计数
        int count = 0;
        for (String idCard : idCardList) {
            String dataJsonStr = driverService.vehicleLicenseQuery(idCard);
            count++;
            log.info("已访问驾驶证查询IRS接口 {} 次", count);
            log.info("此次访问的驾驶证身份证号为 {}",idCard);
            JSONObject object = JSON.parseObject(dataJsonStr, JSONObject.class);
            String data = object.getString("datas");
            List<JSONObject> array = JSON.parseArray(data, JSONObject.class);
            if (CollUtil.isEmpty(array)) {
                log.info("该身份证号没有驾驶证信息!");
                continue;
            }
            // 获取身份证号的所有驾驶证信息
            Map<String, List<DriversLicenseRaw>> drivingLicenseMap = driversLicenseRawService.list().stream()
                    .collect(Collectors.groupingBy(DriversLicenseRaw::getIdcard));

            for (JSONObject jsonObject : array) {
                if (Objects.nonNull(jsonObject)) {
                    // 获取发证日期，判断是否重复
                    Timestamp fZRQ = jsonObject.getTimestamp("fZRQ");

                    List<DriversLicenseRaw> driversLicenseRaws = drivingLicenseMap.get(idCard);
                    List<DriversLicenseRaw> licenseRaws = Lists.newArrayList();
                    if (CollUtil.isNotEmpty(driversLicenseRaws)) {
                        licenseRaws = driversLicenseRaws.stream().filter(d -> {
                            String detail = d.getDriverLicenseDetail();
                            JSONObject json = JSON.parseObject(detail, JSONObject.class);
                            Timestamp timestamp = json.getTimestamp("fZRQ");
                            if (timestamp.equals(fZRQ)) {
                                return true;
                            } else {
                                return false;
                            }
                        }).collect(Collectors.toList());
                    }
                    // 保存新增的驾驶证信息
                    if (CollUtil.isNotEmpty(licenseRaws)) {
                        DriversLicenseRaw driversLicenseRaw = new DriversLicenseRaw();
                        driversLicenseRaw.setIdcard(idCard);
                        String jsonString = jsonObject.toJSONString();
                        driversLicenseRaw.setDriverLicenseDetail(jsonString);
                        driversLicenseRaw.setCreateOn(LocalDateTime.now());
                        driversLicenseRaw.setUpdateOn(LocalDateTime.now());
                        driversLicenseRawService.save(driversLicenseRaw);
                    }
                }
            }
        }
    }

    //这个下面是单独函数
    public static Workbook readExcel(InputStream is, String extString) {
        Workbook wb = null;
        extString = extString.substring(extString.lastIndexOf("."));
        try {
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    public List<String> vehicleLicenseTest() {
        return driverService.vehicleLicenseTest();
    }
}
