package com.ningdatech.carapi.safe;

import java.io.*;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.ningdatech.basic.util.StrPool;
import com.ningdatech.carapi.AppTests;
import com.ningdatech.carapi.car.vehicle.model.NdVehicleBaseInfo;
import com.ningdatech.carapi.car.vehicle.service.IVehicleBaseInfoService;
import com.ningdatech.carapi.safe.entity.NdInsureInfo;
import com.ningdatech.carapi.safe.entity.NdInsureOutDanger;
import com.ningdatech.carapi.safe.service.INdInsureInfoService;
import com.ningdatech.carapi.safe.service.INdInsureOutDangerService;
import com.ningdatech.carapi.sys.entity.Company;
import com.ningdatech.carapi.sys.entity.Region;
import com.ningdatech.carapi.sys.entity.dto.CompanyDTO;
import com.ningdatech.carapi.sys.helper.CompaniesCacheHelper;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.sys.helper.VehiclesCacheHelper;
import com.ningdatech.carapi.sys.service.CompanyService;
import com.ningdatech.carapi.sys.service.IRegionService;

/**
 * @Classname InsureOutdangerTest
 * @Description
 * @Date 2022/12/22 10:47
 * @Created by PoffyZhang
 */
public class InsureOutdangerTest extends AppTests {

    @Autowired
    private CompaniesCacheHelper companiesCacheHelper;

    @Autowired
    private VehiclesCacheHelper vehiclesCacheHelper;

    @Autowired
    private INdInsureOutDangerService outDangerService;

    @Autowired
    private IVehicleBaseInfoService vehicleBaseInfoService;

    @Autowired
    private INdInsureInfoService insureInfoService;

    @Autowired
    private IRegionService regionService;
    @Autowired
    private RegionsCacheHelper regionCacheHelper;
    @Autowired
    private CompanyService companyService;

    @Test
    public void test() throws FileNotFoundException {
        File f = new File("C:\\Users\\CMM\\Desktop\\水泥车数据初始化\\出险信息导入\\出险详情\\出险详情\\2023年1-5月出险数据.xlsx");
        Workbook wb = readExcel(new FileInputStream(f),f.getName());
        Row row = null;
        if(wb != null){
            //获取第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            Map<String, NdVehicleBaseInfo> vehicleBaseInfoMap = vehicleBaseInfoService.list()
                    .stream().collect(Collectors.toMap(NdVehicleBaseInfo::getCarPlate, v -> v));

            //Map<String, Long> outDangerMap = outDangerService.list(Wrappers.lambdaQuery(NdInsureOutDanger.class)
            //                .select(NdInsureOutDanger::getCarPlate,NdInsureOutDanger::getAccidentTime,
            //                        NdInsureOutDanger::getAccidentAddress,NdInsureOutDanger::getId)
            //                .gt(NdInsureOutDanger::getAccidentTime,"2023-01-01")
            //                .lt(NdInsureOutDanger::getAccidentTime,"2023-12-31"))
            //        .stream()
            //        .collect(Collectors.toMap(v -> v.getCarPlate() + StrPool.DASH + v.getAccidentAddress() + StrPool.DASH + v.getAccidentTime(), NdInsureOutDanger::getId));

            //获取最大列数
            for (int i = 1; i<rownum; i++) {
                row = sheet.getRow(i);

                String carPlate = Objects.nonNull(row.getCell(0)) ? row.getCell(0).toString() : StringUtils.EMPTY;
                String driverName = Objects.nonNull(row.getCell(1)) ? row.getCell(1).toString() : StringUtils.EMPTY;
                String vehicleTypeName = Objects.nonNull(row.getCell(2)) ? row.getCell(2).toString() : StringUtils.EMPTY;
                String cityName = Objects.nonNull(row.getCell(3)) ? row.getCell(3).toString() : StringUtils.EMPTY;
                //区
                String regionName = Objects.nonNull(row.getCell(4)) ? row.getCell(4).toString() : StringUtils.EMPTY;
                String companyName = Objects.nonNull(row.getCell(5)) ? row.getCell(5).toString() : StringUtils.EMPTY;
                Date outDangerTime = Objects.nonNull(row.getCell(6)) ? row.getCell(6).getDateCellValue() : null;
                String address = Objects.nonNull(row.getCell(7)) ? row.getCell(7).toString() : StringUtils.EMPTY;
                //受伤人数
                String injuies = Objects.nonNull(row.getCell(8)) ? row.getCell(8).toString() : "0";
                //死亡人数
                String deathToll = Objects.nonNull(row.getCell(9)) ? row.getCell(9).toString() : "0";
                //已决赔款
                BigDecimal compensateAmount = BigDecimal.valueOf(0);
                Cell cellAmount = row.getCell(10);
                if(Objects.nonNull(cellAmount)){
                    if(cellAmount.toString().contains("+")){
                        String[] amountArr = cellAmount.toString().split("\\+");
                        compensateAmount = BigDecimal.valueOf(Double.valueOf(amountArr[0])).add(BigDecimal.valueOf(Double.valueOf(amountArr[1])));
                    }else{
                        double numericCellValue = Double.valueOf(cellAmount.toString());
                        compensateAmount = BigDecimal.valueOf(numericCellValue);
                    }
                }
                //保险公司
                String insureCompany = Objects.nonNull(row.getCell(11)) ? row.getCell(11).toString() : StringUtils.EMPTY;

                System.out.println(carPlate + "," + driverName + "," + vehicleTypeName + "," + cityName + "," + regionName +
                        "," + companyName + "," + outDangerTime + "," + address + "," + injuies + "," + deathToll + "," + compensateAmount
                        + "," + compensateAmount + "," + insureCompany);

                NdInsureOutDanger outDanger = new NdInsureOutDanger();
                //Long outDangerId = outDangerMap.get(carPlate + StrPool.DASH + address + StrPool.DASH + outDangerTime);
                //if (Objects.nonNull(outDangerId)){
                //   outDanger.setId(outDangerId);
                //}
                outDanger.setCarPlate(carPlate);
                outDanger.setInsureCompany(insureCompany);
                outDanger.setInsureCompanyFullName(insureCompany);
                outDanger.setAccidentTime(outDangerTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                NdVehicleBaseInfo car = vehicleBaseInfoMap.get(carPlate);
                // 车辆存在于系统中，按照车辆所在企业关联出险企业信息、区域信息
                if (Objects.nonNull(car)) {
                    outDanger.setCompanyId(car.getCompanyId());
                    CompanyDTO company = companiesCacheHelper.getById(car.getCompanyId());
                    outDanger.setCompanyName(Objects.nonNull(company) ? company.getName() : StringUtils.EMPTY);
                    outDanger.setRegionId(car.getRegionId());
                }else {
                    // 车辆不存在于系统中，只关联被保企业名称,不关联区域信息
                    outDanger.setCompanyName(companyName);
                }
                outDanger.setDeathToll(Double.valueOf(deathToll).intValue());
                outDanger.setInjuries(Double.valueOf(injuies).intValue());
                outDanger.setCompensateAmount(compensateAmount);
                outDanger.setAccidentAddress(address);
                outDangerService.saveOrUpdate(outDanger);
                System.out.println("准备插入 " + i  + "条:" + JSON.toJSONString(outDanger));
            }
        }
    }


    @Test
    public void test2() throws FileNotFoundException {
        File f = new File("C:\\Users\\CMM\\Desktop\\水泥车数据初始化\\出险信息导入\\1-4月的出险数据.xlsx");
        Workbook wb = readExcel(new FileInputStream(f),f.getName());
        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 carPlate = Objects.nonNull(row.getCell(0)) ? row.getCell(0).toString() : StringUtils.EMPTY;
                String driverName = Objects.nonNull(row.getCell(1)) ? row.getCell(1).toString() : StringUtils.EMPTY;
                String vehicleTypeName = Objects.nonNull(row.getCell(2)) ? row.getCell(2).toString() : StringUtils.EMPTY;
                String cityName = Objects.nonNull(row.getCell(3)) ? row.getCell(3).toString() : StringUtils.EMPTY;
                //区
                String regionName = Objects.nonNull(row.getCell(4)) ? row.getCell(4).toString() : StringUtils.EMPTY;
                String companyName = Objects.nonNull(row.getCell(5)) ? row.getCell(5).toString() : StringUtils.EMPTY;
                Date outDangerTime = Objects.nonNull(row.getCell(6)) ? row.getCell(6).getDateCellValue() : null;
                String address = Objects.nonNull(row.getCell(7)) ? row.getCell(7).toString() : StringUtils.EMPTY;
                //受伤人数
                String injuies = Objects.nonNull(row.getCell(8)) ? row.getCell(8).toString() : "0";
                //死亡人数
                String deathToll = Objects.nonNull(row.getCell(9)) ? row.getCell(9).toString() : "0";
                //已决赔款
                BigDecimal compensateAmount = BigDecimal.valueOf(0);
                Cell cellAmount = row.getCell(10);
                if(Objects.nonNull(cellAmount)){
                    if(cellAmount.toString().contains("+")){
                        String[] amountArr = cellAmount.toString().split("\\+");
                        compensateAmount = BigDecimal.valueOf(Double.valueOf(amountArr[0])).add(BigDecimal.valueOf(Double.valueOf(amountArr[1])));
                    }else{
                        compensateAmount = BigDecimal.valueOf(cellAmount.getNumericCellValue());
                    }
                }
                //保险公司
                String insureCompany = Objects.nonNull(row.getCell(13)) ? row.getCell(13).toString() : StringUtils.EMPTY;

                System.out.println(carPlate + "," + driverName + "," + vehicleTypeName + "," + cityName + "," + regionName +
                        "," + companyName + "," + outDangerTime + "," + address + "," + injuies + "," + deathToll + "," + compensateAmount
                        + "," + compensateAmount + "," + insureCompany);



                NdInsureOutDanger outDanger = new NdInsureOutDanger();
                outDanger.setCarPlate(carPlate);
                outDanger.setInsureCompany(insureCompany);
                outDanger.setAccidentTime(outDangerTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());

                NdVehicleBaseInfo car = vehiclesCacheHelper.getByCarPlate(carPlate);
                if(Objects.nonNull(car)){
                    outDanger.setCompanyId(car.getCompanyId());
                    CompanyDTO company = companiesCacheHelper.getById(car.getCompanyId());
                    outDanger.setCompanyName(Objects.nonNull(company) ? company.getName() : StringUtils.EMPTY);
                    outDanger.setRegionId(car.getRegionId());
                }else{
                    System.out.println("这辆车不在系统里 " + carPlate);
                }

                outDanger.setDeathToll(Double.valueOf(deathToll).intValue());
                outDanger.setInjuries(Double.valueOf(injuies).intValue());
                outDanger.setCompensateAmount(compensateAmount);
                outDanger.setAccidentAddress(address);
                outDangerService.save(outDanger);
                System.out.println("准备插入 " + i  + "条:" + JSON.toJSONString(outDanger));
            }
        }
    }

    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
    }


    @Test
    public void tes3() throws FileNotFoundException {
        //File f = new File("C:\\Users\\CMM\\Desktop\\水泥车数据初始化\\出险信息导入\\出险详情\\出险详情\\2023出险数据.xlsx");
        //File f = new File("D:\\work\\水泥车出险数据\\2023年1-6月出险数据.xlsx");
        //File f = new File("D:\\work\\水泥车出险数据\\2023年1-7月出险数据.xlsx");
        //File f = new File("D:\\work\\水泥车出险数据\\2023年1-8月出险数据.xlsx");
        //File f = new File("D:\\work\\水泥车出险数据\\2023年1-10月出险数据.xlsx");
        File f = new File("D:\\work\\水泥车出险数据\\2023年1-11月出险数据.xlsx");
        Workbook wb = readExcel(new FileInputStream(f),f.getName());
        Row row = null;
        if(wb != null){
            //获取第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            Map<String, NdVehicleBaseInfo> vehicleBaseInfoMap = vehicleBaseInfoService.list()
                    .stream().collect(Collectors.toMap(NdVehicleBaseInfo::getCarPlate, v -> v));

            HashSet<String> countySet = new HashSet<>();
            // 根据区县名称获取区域ID
            Map<String, Region> regionMap = regionService.list().stream()
                    .filter(v -> !StrPool.EMPTY.equals(v.getName()) &&
                            !"市本级".equals(v.getName()) &&
                            countySet.add(v.getName()))
                    .collect(Collectors.toMap(Region::getName, v -> v));

            //获取最大列数
            for (int i = 1; i<rownum; i++) {
                row = sheet.getRow(i);

                String carPlate = Objects.nonNull(row.getCell(0)) ? row.getCell(0).toString() : StringUtils.EMPTY;
                String driverName = Objects.nonNull(row.getCell(1)) ? row.getCell(1).toString() : StringUtils.EMPTY;
                String vehicleTypeName = Objects.nonNull(row.getCell(2)) ? row.getCell(2).toString() : StringUtils.EMPTY;
                String cityName = Objects.nonNull(row.getCell(3)) ? row.getCell(3).toString() : StringUtils.EMPTY;
                //区
                String regionName = Objects.nonNull(row.getCell(4)) ? row.getCell(4).toString() : StringUtils.EMPTY;
                String companyName = Objects.nonNull(row.getCell(5)) ? row.getCell(5).toString() : StringUtils.EMPTY;
                Date outDangerTime = Objects.nonNull(row.getCell(6)) ? row.getCell(6).getDateCellValue() : null;
                String address = Objects.nonNull(row.getCell(7)) ? row.getCell(7).toString() : StringUtils.EMPTY;
                //受伤人数
                String injuies = Objects.nonNull(row.getCell(8)) ? row.getCell(8).toString() : "0";
                //死亡人数
                String deathToll = Objects.nonNull(row.getCell(9)) ? row.getCell(9).toString() : "0";
                //已决赔款
                BigDecimal compensateAmount = BigDecimal.valueOf(0);
                Cell cellAmount = row.getCell(10);
                if(Objects.nonNull(cellAmount)){
                    if(cellAmount.toString().contains("+")){
                        String[] amountArr = cellAmount.toString().split("\\+");
                        compensateAmount = BigDecimal.valueOf(Double.valueOf(amountArr[0])).add(BigDecimal.valueOf(Double.valueOf(amountArr[1])));
                    }else{
                        double numericCellValue = Double.valueOf(cellAmount.toString());
                        compensateAmount = BigDecimal.valueOf(numericCellValue);
                    }
                }
                //保险公司
                String insureCompany = Objects.nonNull(row.getCell(11)) ? row.getCell(11).toString() : StringUtils.EMPTY;
                //保险公司全称
                String insureCompanyFullName = Objects.nonNull(row.getCell(12)) ? row.getCell(12).toString() : StringUtils.EMPTY;
                System.out.println(carPlate + "," + driverName + "," + vehicleTypeName + "," + cityName + "," + regionName +
                        "," + companyName + "," + outDangerTime + "," + address + "," + injuies + "," + deathToll + "," + compensateAmount
                        + "," + compensateAmount + "," + insureCompany);



                NdInsureOutDanger outDanger = new NdInsureOutDanger();
                outDanger.setCarPlate(carPlate);
                outDanger.setInsureCompany(insureCompany);
                outDanger.setInsureCompanyFullName(insureCompanyFullName);
                outDanger.setAccidentTime(outDangerTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                NdVehicleBaseInfo car = vehicleBaseInfoMap.get(carPlate);
                // 车辆存在于系统中，按照车辆所在企业关联出险企业信息、区域信息
                if (Objects.nonNull(car)) {
                    Long companyId = car.getCompanyId();
                    if (Objects.nonNull(companyId)) {
                        outDanger.setCompanyId(companyId);
                        CompanyDTO company = companiesCacheHelper.getById(car.getCompanyId());
                        outDanger.setCompanyName(Objects.nonNull(company) ? company.getName() : StringUtils.EMPTY);
                    }
                }else {
                    // 车辆不存在于系统中，只关联被保企业名称,不关联区域信息
                    outDanger.setCompanyName(companyName);
                }
                Region region = regionMap.get(regionName);
                if (Objects.nonNull(region)) {
                    Long regionId = region.getId();
                    outDanger.setRegionId(regionId);
                    outDanger.setRegionName("浙江省" + "-" + cityName + "-" + region.getName());
                }else {
                    // 如果行政区划不存在，按所属市级区域保存，并拼接区域名称
                    Region cityRegion = regionMap.get(cityName);
                    Long cityRegionId = cityRegion.getId();
                    outDanger.setRegionId(cityRegionId);
                    outDanger.setRegionName("浙江省" + "-" + cityName);
                }
                outDanger.setDeathToll(Double.valueOf(deathToll).intValue());
                outDanger.setInjuries(Double.valueOf(injuies).intValue());
                outDanger.setCompensateAmount(compensateAmount);
                outDanger.setAccidentAddress(address);
                outDangerService.save(outDanger);
                System.out.println("准备插入 " + i  + "条:" + JSON.toJSONString(outDanger));
            }
        }
    }


    @Test
    public void test4() throws FileNotFoundException {
        //File f = new File("C:\\Users\\CMM\\Desktop\\水泥车数据初始化\\出险信息导入\\出险详情\\出险详情\\2023年1-5月出险数据.xlsx");
        //File f = new File("D:\\work\\水泥车出险数据\\2023年1-6月出险数据.xlsx");
        //File f = new File("D:\\work\\水泥车出险数据\\2023年1-7月出险数据.xlsx");
        //File f = new File("D:\\work\\水泥车出险数据\\2023年1-8月出险数据.xlsx");
        //File f = new File("D:\\work\\水泥车出险数据\\2023年1-10月出险数据.xlsx");
        File f = new File("D:\\work\\水泥车出险数据\\2023年1-11月出险数据.xlsx");
        Workbook wb = readExcel(new FileInputStream(f),f.getName());
        Row row = null;
        if(wb != null){
            //获取第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);

            // 根据区县名称获取区域ID
            HashSet<String> countySet = new HashSet<>();
            Map<String, Region> regionMap = regionService.list().stream()
                    .filter(v -> !StrPool.EMPTY.equals(v.getName()) &&
                            !"市本级".equals(v.getName()) &&
                            countySet.add(v.getName()))
                    .collect(Collectors.toMap(Region::getName, v -> v));

            // 根据企业名查询企业信息
            HashSet<String> companySet = new HashSet<>();
            Map<String, Company> companyNameMap = companyService.list().stream()
                    .filter(v -> !StrPool.EMPTY.equals(v.getName()) &&
                            companySet.add(v.getName()))
                    .collect(Collectors.toMap(Company::getName, v -> v));

            for (int i = 1; i<rownum; i++) {
                row = sheet.getRow(i);

                String carPlate = Objects.nonNull(row.getCell(0)) ? row.getCell(0).toString() : StringUtils.EMPTY;

                String cityName = Objects.nonNull(row.getCell(3)) ? row.getCell(3).toString() : StringUtils.EMPTY;
                //区
                String regionName = Objects.nonNull(row.getCell(4)) ? row.getCell(4).toString() : StringUtils.EMPTY;
                Region region = regionMap.get(regionName);
                Long regionId = null;
                if (Objects.nonNull(region)) {
                    regionId = region.getId();
                }else {
                    Region cityRegion = regionMap.get(cityName);
                    regionId = cityRegion.getId();
                }
                String displayName = regionCacheHelper.getDisplayName(regionId);
                String companyName = Objects.nonNull(row.getCell(5)) ? row.getCell(5).toString() : StringUtils.EMPTY;
                Company companyInfo = companyNameMap.get(companyName);
                Long companyId = null;
                if (Objects.nonNull(companyInfo)){
                    companyId = companyInfo.getId();
                }
                //保险公司
                String insureCompany = Objects.nonNull(row.getCell(11)) ? row.getCell(11).toString() : StringUtils.EMPTY;
                //保险公司全称
                String insureCompanyFullName = Objects.nonNull(row.getCell(12)) ? row.getCell(12).toString() : StringUtils.EMPTY;
                NdInsureInfo insureInfo = new NdInsureInfo();
                insureInfo.setCarPlate(carPlate);
                insureInfo.setRegionId(regionId);
                insureInfo.setRegionName(displayName);
                insureInfo.setCompanyId(companyId);
                insureInfo.setCompanyName(companyName);
                insureInfo.setInsureCompany(insureCompany);
                insureInfo.setInsureCompanyFullName(insureCompanyFullName);
                insureInfoService.save(insureInfo);
                System.out.println("准备插入 " + i  + "条:" + JSON.toJSONString(insureInfo));
            }
        }
    }

    //这个下面是单独函数
    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;
    }

}
