package com.ningdatech.carapi.dataview;

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 org.springframework.security.crypto.password.PasswordEncoder;

import com.alibaba.fastjson.JSON;
import com.ningdatech.carapi.AppTests;
import com.ningdatech.carapi.analysis.entity.WarnAnalysisCompany;
import com.ningdatech.carapi.analysis.service.IWarnAnalysisCompanyService;
import com.ningdatech.carapi.car.vehicle.model.NdVehicleBaseInfo;
import com.ningdatech.carapi.car.vehicle.service.IVehicleBaseInfoService;
import com.ningdatech.carapi.common.constant.UserRoleTypeEnum;
import com.ningdatech.carapi.company.enumeration.CompanyTypeEnum;
import com.ningdatech.carapi.driver.constant.UserCanLoginEnum;
import com.ningdatech.carapi.safe.entity.NdInsureInfo;
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.CompanyTypeRelated;
import com.ningdatech.carapi.sys.entity.Region;
import com.ningdatech.carapi.sys.entity.UserRole;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.sys.service.*;
import com.ningdatech.carapi.user.entity.NdUserAuth;
import com.ningdatech.carapi.user.entity.NdUserInfo;
import com.ningdatech.carapi.user.security.auth.constant.AuthTypeEnum;
import com.ningdatech.carapi.user.service.INdUserAuthService;
import com.ningdatech.carapi.user.service.INdUserInfoService;

import lombok.RequiredArgsConstructor;

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

    @Autowired
    private  CompanyService companyService;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IWarnAnalysisCompanyService analysisCompanyService;
    @Autowired
    private IVehicleBaseInfoService vehicleBaseInfoService;
    @Autowired
    private CompanyTypeRelatedService companyTypeRelatedService;
    @Autowired
    private INdInsureInfoService insureInfoService;
    @Autowired
    private RegionsCacheHelper regionsCacheHelper;
    @Autowired
    private INdUserInfoService userInfoService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private  INdUserAuthService ndUserAuthService;
    @Autowired
    private  UserRoleService userRoleService;

    @Autowired
    private OperatorService operatorService;

    private final INdInsureOutDangerService inInsureOutDangerService;

    @Test
    public void test() throws FileNotFoundException {
        // 更新预警评估-预警企业表中的企业ID
        Map<String, Company> companyMap = companyService.list().stream().collect(Collectors.toMap(Company::getName, c -> c));
        List<NdInsureInfo> insureInfoList = insureInfoService.list();
        List<WarnAnalysisCompany> warnAnalysisCompanyList = analysisCompanyService.list();
        for (WarnAnalysisCompany warnAnalysisCompany : warnAnalysisCompanyList) {
            String companyName = warnAnalysisCompany.getCompanyName();
            if (companyMap.containsKey(companyName)){
                Company company = companyMap.get(companyName);
                warnAnalysisCompany.setCompanyId(company.getId());
                warnAnalysisCompany.setRegionId(company.getRegionId());
                analysisCompanyService.updateById(warnAnalysisCompany);
            }
        }
    }

    @Test
    public void test3() {
        // 更新预警评估-保险机构信息中的企业和区域信息
        Map<String, NdVehicleBaseInfo> vehicleBaseInfoMap = vehicleBaseInfoService.list().stream()
                .collect(Collectors.toMap(NdVehicleBaseInfo::getCarPlate, v -> v));
        Map<Long, Company> companyMap = companyService.list().stream().collect(Collectors.toMap(Company::getId, c -> c));
        List<NdInsureInfo> insureInfos = insureInfoService.list();
        for (NdInsureInfo insureInfo : insureInfos) {
            String carPlate = insureInfo.getCarPlate();
            NdVehicleBaseInfo baseInfo = vehicleBaseInfoMap.get(carPlate);
            Long companyId = baseInfo.getCompanyId();
            Long regionId = baseInfo.getRegionId();
            String regionName = baseInfo.getRegionName();
            Company company = companyMap.get(companyId);
            insureInfo.setCompanyId(companyId);
            insureInfo.setRegionId(regionId);
            insureInfo.setRegionName(regionName);
            insureInfo.setCompanyName(company.getName());
            insureInfoService.updateById(insureInfo);
        }
    }

    @Test
    public void test4() {
        // 创建各市、区县散装中心管理企业
        List<Region> cityList = regionService.list()
                .stream().filter(c -> (2 == c.getLevel() || 3 == c.getLevel())
                        && !"市本级".equals(c.getName()))
                .collect(Collectors.toList());
        for (Region region : cityList) {
            Company company = new Company();
            String regionName = region.getName();
            Long regionId = region.getId();
            String companyName = regionName + "散装中心";
            company.setName(companyName);
            company.setRegionId(regionId);
            String displayName = regionsCacheHelper.getDisplayName(regionId);
            company.setRegionName(displayName);
            company.setCompanyType(CompanyTypeEnum.MANAGE_BU.getCode());
            company.setCreateOn(LocalDateTime.now());
            company.setUpdateOn(LocalDateTime.now());
            companyService.save(company);
        }
    }

    @Test
    public void test5() {
        // 创建各企业企业信息员账号
        Map<Long, Company> companyMap = companyService.list().stream().collect(Collectors.toMap(Company::getId, c -> c));
        List<Company> companyList = companyService.list().stream().filter(c -> c.getCompanyType().equals(CompanyTypeEnum.PRODUCT_BU.getCode())
                || c.getCompanyType().equals(CompanyTypeEnum.LOGISTICS_BU.getCode())
                || c.getCompanyType().equals(CompanyTypeEnum.OTHER.getCode())).collect(Collectors.toList());
        for (Company company : companyList) {
            Long companyId = company.getId();
            Company companyInfo = companyMap.get(companyId);
            NdUserInfo userInfo = new NdUserInfo();
            userInfo.setCanLogin(UserCanLoginEnum.CAN_LOGIN.getCode());
            userInfo.setUsername(companyInfo.getName());
            userInfo.setCompanyId(companyId);
            userInfo.setCreateOn(LocalDateTime.now());
            userInfo.setUpdateOn(LocalDateTime.now());
            userInfoService.save(userInfo);

            Long userId = userInfo.getId();
            NdUserAuth userAuth = new NdUserAuth();
            userAuth.setUserId(userId);
            userAuth.setIdentifier(companyInfo.getName());
            userAuth.setCredential(passwordEncoder.encode("123456Aa"));
            userAuth.setAuthType(AuthTypeEnum.ACCOUNT_PASSWORD.getKey());
            userAuth.setIsAvailable(true);
            ndUserAuthService.save(userAuth);

            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(UserRoleTypeEnum.COMPANY_INFO_OFFICER_ROLE_ID.getId());
            userRoleService.save(userRole);
        }
    }

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

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