package com.ningdatech.carapi.company;

import java.io.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

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.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.company.entity.NdCompanyCreditLevel;
import com.ningdatech.carapi.company.service.INdCompanyCreditLevelService;
import com.ningdatech.carapi.sys.entity.Company;
import com.ningdatech.carapi.sys.entity.CompanyTypeRelated;
import com.ningdatech.carapi.sys.entity.Region;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.sys.service.CompanyService;
import com.ningdatech.carapi.sys.service.CompanyTypeRelatedService;
import com.ningdatech.carapi.sys.service.IRegionService;

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

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

    @Autowired
    private RegionsCacheHelper regionsCacheHelper;

    @Autowired
    private CompanyTypeRelatedService companyTypeRelatedService;
    @Autowired
    private INdCompanyCreditLevelService companyCreditLevelService;

    @Test
    public void test() throws FileNotFoundException {
        File f = new File("C:\\Users\\CMM\\Desktop\\水泥车数据初始化\\最新企业.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();

            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));

            Map<String, Company> companyMap = companyService.list().stream()
                    .collect(Collectors.toMap(Company::getName, v -> v));

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

                // 企业名称
                String name = Objects.nonNull(row.getCell(0)) ? row.getCell(0).toString() : StringUtils.EMPTY;
                //// 企业地址
                //String address = Objects.nonNull(row.getCell(1)) ? row.getCell(1).toString() : StringUtils.EMPTY;
                //// 企业法人姓名
                //String legalPerson = Objects.nonNull(row.getCell(2)) ? row.getCell(2).toString() : StringUtils.EMPTY;
                //// 区域名称
                //String regionName = Objects.nonNull(row.getCell(3)) ? row.getCell(3).toString() : StringUtils.EMPTY;
                //Region region = regionMap.get(regionName);
                //Long regionId = null;
                //if (Objects.nonNull(region)) {
                //    regionId = region.getId();
                //}
                //
                //// 企业类型
                //String companyTypeName = Objects.nonNull(row.getCell(4)) ? row.getCell(4).toString() : StringUtils.EMPTY;
                //Integer comType = CompanyTypeEnum.getCodeByDesc(companyTypeName);
                //
                //// 营业执照编号
                //String businessLicense = Objects.nonNull(row.getCell(5)) ? row.getCell(5).toString() : StringUtils.EMPTY;

                // 经度
                String longitude = Objects.nonNull(row.getCell(7)) ? row.getCell(7).toString() : StringUtils.EMPTY;
                // 纬度
                String latitude = Objects.nonNull(row.getCell(8)) ? row.getCell(8).toString() : StringUtils.EMPTY;


                Company company = companyMap.get(name);
                if (Objects.nonNull(company)) {
                    company.setName(name);
                    company.setLongitude(longitude);
                    company.setLatitude(latitude);
                    company.setCreateOn(LocalDateTime.now());
                    company.setUpdateOn(LocalDateTime.now());
                    companyService.updateById(company);
                    System.out.println("准备插入 " + i + "条:" + JSON.toJSONString(company));
                }
            }
        }
    }

    @Test
    public void test2() throws FileNotFoundException {
        File f = new File("C:\\Users\\CMM\\Desktop\\水泥车数据初始化\\水泥车企业类型细分.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();

            HashSet<String> countySet = new HashSet<>();
            // 根据公司名称获取公司ID
            Map<String, Company> companyMap = companyService.list().stream()
                    .collect(Collectors.toMap(Company::getName, c -> c));


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

                // 企业名称
                String name = Objects.nonNull(row.getCell(0)) ? row.getCell(0).toString() : StringUtils.EMPTY;
                Company company = companyMap.get(name);
                // 具体企业类型
                String companyTypeName = Objects.nonNull(row.getCell(1)) ? row.getCell(1).toString() : StringUtils.EMPTY;
                CompanyTypeRelated related = new CompanyTypeRelated();
                related.setCompanyId(company.getId());
                if (companyTypeName.equals("预拌砂浆生产企业")){
                    related.setCompanyTypeId(2L);
                }else if (companyTypeName.equals("预拌混凝土生产企业")){
                    related.setCompanyTypeId(3L);
                }else if (companyTypeName.equals("水泥生产企业")){
                    related.setCompanyTypeId(4L);
                }else if (companyTypeName.equals("物流企业")){
                    related.setCompanyTypeId(5L);
                }else if (companyTypeName.equals("其他")){
                    related.setCompanyTypeId(6L);
                }
                companyTypeRelatedService.save(related);
                System.out.println("准备插入 " + i  + "条:" + JSON.toJSONString(company));
            }
        }
    }

    @Test
    public void test3(){
        // 获取所有非管理企业信息
        List<Company> companyList = companyService.list().stream().filter(c -> c.getCompanyType() != 0).collect(Collectors.toList());
        // 初始化所有企业2023年的的企业信用等级
        for (Company company : companyList) {
            NdCompanyCreditLevel creditLevel = new NdCompanyCreditLevel();
            creditLevel.setCompanyId(company.getId());
            creditLevel.setCompanyName(company.getName());
            creditLevel.setRegionId(company.getRegionId());
            String regionName = regionsCacheHelper.getDisplayName(company.getRegionId());
            creditLevel.setRegionName(regionName);
            creditLevel.setYear("2023");
            creditLevel.setScore(1000);
            creditLevel.setLevel("A");
            creditLevel.setBasicCreditScore(120);
            creditLevel.setCommonCreditScore(300);
            creditLevel.setSafeProductCreditScore(240);
            creditLevel.setIndustryRegulateCreditScore(240);
            creditLevel.setIndustryHonorBonus(100);
            creditLevel.setGovernmentAwardScore(50);
            creditLevel.setIndustryBenchMarkScore(50);
            companyCreditLevelService.save(creditLevel);
        }

    }

    @Test
    public void test4() throws FileNotFoundException {
        File f = new File("D:\\work\\水泥车车辆数据\\丽水莲都区物流企业.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 name = Objects.nonNull(row.getCell(0)) ? row.getCell(0).toString() : StringUtils.EMPTY;
                // 区域ID
                String regionId = Objects.nonNull(row.getCell(1)) ? row.getCell(1).toString() : StringUtils.EMPTY;
                // 区域名称
                String regionName = Objects.nonNull(row.getCell(2)) ? row.getCell(2).toString() : StringUtils.EMPTY;
                // 营业执照编号
                String businessLicense = Objects.nonNull(row.getCell(3)) ? row.getCell(3).toString() : StringUtils.EMPTY;
                // 地址
                String address = Objects.nonNull(row.getCell(4)) ? row.getCell(4).toString() : StringUtils.EMPTY;
                // 法人
                String legalPerson = Objects.nonNull(row.getCell(5)) ? row.getCell(5).toString() : StringUtils.EMPTY;
                // 法人联系电话
                String legalPersonPhone = Objects.nonNull(row.getCell(6)) ? row.getCell(6).toString() : StringUtils.EMPTY;
                // 企业类型
                String companyType = Objects.nonNull(row.getCell(7)) ? row.getCell(7).toString() : StringUtils.EMPTY;
                Company company = new Company();
                company.setName(name);
                company.setRegionId(Double.valueOf(regionId).longValue());
                company.setRegionName(regionName);
                company.setBusinessLicense(businessLicense);
                company.setAddress(address);
                company.setLegalPerson(legalPerson);
                company.setLegalPersonPhone(legalPersonPhone);
                company.setCompanyType(Double.valueOf(companyType).intValue());
                company.setCreateOn(LocalDateTime.now());
                company.setUpdateOn(LocalDateTime.now());
                companyService.save(company);
                System.out.println("准备插入 " + i + "条:" + JSON.toJSONString(company));
            }
        }
    }

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

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