package com.izouma.jmrh.service;

import com.alibaba.excel.EasyExcel;
import com.izouma.jmrh.domain.OrgInfo;
import com.izouma.jmrh.enums.AuditStatus;
import com.izouma.jmrh.enums.OrgStatus;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.*;
import com.izouma.jmrh.service.storage.StorageService;
import com.izouma.jmrh.utils.FileUtils;
import com.izouma.jmrh.utils.excel.UploadDataListener;
import lombok.AllArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.TempFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@AllArgsConstructor
public class OrgInfoService {

    private OrgInfoRepo    orgInfoRepo;
    private StorageService storageService;

    public Map<String, Object> getAllCount(Long id) {
        HashMap<String, Object> map = new HashMap<>();
        OrgInfo orgInfo = orgInfoRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        map.put("orgInfo", orgInfo);
        return map;
    }

    public void upload(MultipartFile file) throws IOException {
        File destDir = TempFile.createTempDirectory("import");
        FileUtils.unzip(file.getInputStream(), destDir);
        File xlsxFile = FileUtils.findExcel(destDir);
        if (xlsxFile == null) return;
        UploadDataListener<OrgInfo> listener = new UploadDataListener<>();
        EasyExcel.read(new FileInputStream(xlsxFile), OrgInfo.class, listener).sheet().doReadSync();
        for (OrgInfo data : listener.getData()) {
            data.setStatus(AuditStatus.PASS);
            if (StringUtils.isBlank(data.getOrgName())) {
                throw new BusinessException("企业名称不能为空");
            }
            if (data.getLogo() != null) {
                File uploadFile = new File(destDir, data.getLogo());
                if (uploadFile.exists()) {
                    try {
                        String path = "image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
                                + RandomStringUtils.randomAlphabetic(8)
                                + "." + FilenameUtils.getExtension(uploadFile.getName());
                        String url = storageService.uploadFromInputStream(new FileInputStream(uploadFile), path);
                        data.setLogo(url);
                    } catch (Exception ignored) {
                    }
                }
            }
        }
        orgInfoRepo.saveAll(listener.getData());
    }
}
