package com.ningdatech.carapi.open.manage;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.util.StrPool;
import com.ningdatech.carapi.safe.entity.NdSecurityAdvisory;
import com.ningdatech.carapi.safe.service.INdSecurityAdvisoryService;
import com.ningdatech.carapi.sys.entity.Region;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.sys.service.IRegionService;
import com.ningdatech.file.entity.vo.result.FileResultVO;
import com.ningdatech.file.service.FileService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author CMM
 * @since 2023/01/06 16:40
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OpenSecurityAdvisoryManage {

    private final INdSecurityAdvisoryService ndSecurityAdvisoryService;
    private final RegionsCacheHelper regionsCacheHelper;
    private final FileService fileService;
    private final IRegionService regionService;

    public String batchUpload() {
        List<String> folderList = Lists.newArrayList();
        folderList.add("3301_杭州市");
        folderList.add("3302_宁波市");
        folderList.add("3303_温州市");
        folderList.add("3304_嘉兴市");
        folderList.add("3305_湖州市");
        folderList.add("3306_绍兴市");
        folderList.add("3307_金华市");
        folderList.add("3308_衢州市");
        folderList.add("3309_舟山市");
        folderList.add("3310_台州市");
        folderList.add("3311_丽水市");
        for (String folderName : folderList) {
            File directory = new File("");
            // 临时文件存储路径
            String filePath = directory.getAbsolutePath() + File.separator + "advisory" + File.separator + folderName;
            log.info(filePath);
            File folder = new File(filePath);
            if (folder.isDirectory()) {
                readFiles(folder);
            } else {
                log.info("指定路径不是一个文件夹！");
            }
        }
        return "上传成功";
    }

    private void readFiles(File folder) {
        File[] files = folder.listFiles();
        if (files != null) {
            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 (File file : files) {
                if (file.isDirectory()) {
                    // 递归调用，读取子文件夹中的文件
                    readFiles(file);
                } else {
                    // 输出文件名
                    log.info(file.getName());
                    // 上传文件到OSS
                    MultipartFile multipartFile;
                    try {
                        InputStream inputStream = new FileInputStream(file);
                        String fileName = file.getName();
                        multipartFile = new MockMultipartFile("file", fileName,
                                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                                inputStream);
                        FileResultVO fileResultVo = fileService.upload(multipartFile, "default");
                        // 保存到安全通报表中
                        NdSecurityAdvisory ndSecurityAdvisory = new NdSecurityAdvisory();
                        ndSecurityAdvisory.setCreateBy(2L);
                        ndSecurityAdvisory.setCreateOn(LocalDateTime.now());
                        int startIndex = fileName.indexOf("月");
                        String regionName = fileName.substring(startIndex + 1, startIndex + 4);
                        if ("景宁县".equals(regionName)){
                            regionName = "景宁畲族自治县";
                        }
                        Region region = regionMap.get(regionName);
                        Long regionId;
                        if (Objects.isNull(region)){
                            String folderName = folder.getName();
                            int start = folderName.indexOf(StrPool.UNDERSCORE);
                            String cityName = folderName.substring(start + 1, start + 4);
                            Region cityRegion = regionMap.get(cityName);
                            regionId = cityRegion.getId();

                        }else {
                            regionId = region.getId();
                        }
                        ndSecurityAdvisory.setRegionId(regionId);
                        ndSecurityAdvisory.setRegionName(regionsCacheHelper.getDisplayName(regionId));
                        // 获取当前日期
                        LocalDate currentDate = LocalDate.now();
                        // 获取当前日期所在月份的第一天
                        LocalDate firstDayOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
                        // 获取第一天的开始时间
                        LocalTime startTime = LocalTime.of(0, 0,0);
                        // 将日期和时间合并为完整的日期时间对象
                        LocalDateTime time = LocalDateTime.of(firstDayOfMonth, startTime);
                        //String dateString = "2023-06-01 00:00:00";
                        //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        //LocalDateTime time = LocalDateTime.parse(dateString, formatter);
                        ndSecurityAdvisory.setAdvisoryDate(time);
                        ndSecurityAdvisory.setFileId(fileResultVo.getId());
                        ndSecurityAdvisory.setAdvisoryFileName(fileName);
                        ndSecurityAdvisory.setCompanyId(32104L);
                        ndSecurityAdvisoryService.save(ndSecurityAdvisory);
                    } catch (IOException e) {
                        throw new BizException("上传文件失败:" + e.getMessage());
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前日期所在月份的第一天
        LocalDate firstDayOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
        // 获取第一天的开始时间
        LocalTime startTime = LocalTime.of(0, 0,0);
        // 将日期和时间合并为完整的日期时间对象
        LocalDateTime firstDayOfMonthWithStartTime = LocalDateTime.of(firstDayOfMonth, startTime);

        System.out.println(firstDayOfMonthWithStartTime);
    }
}
