package com.xiaoniu.subsystem.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoniu.common.core.constant.Constants;
import com.xiaoniu.common.core.exception.ServiceException;
import com.xiaoniu.common.core.utils.BeanUtil;
import com.xiaoniu.common.core.utils.DateUtils;
import com.xiaoniu.common.core.utils.StringUtils;
import com.xiaoniu.common.core.utils.uuid.IdUtils;
import com.xiaoniu.subsystem.business.domain.ManageFile;
import com.xiaoniu.subsystem.business.domain.ProfileManage;
import com.xiaoniu.subsystem.business.domain.StudentInfo;
import com.xiaoniu.subsystem.business.domain.dto.ProfileSaveDTO;
import com.xiaoniu.subsystem.business.domain.vo.ProfileManageVO;
import com.xiaoniu.subsystem.business.mapper.ManageFileMapper;
import com.xiaoniu.subsystem.business.mapper.ProfileManageMapper;
import com.xiaoniu.subsystem.business.service.IProfileManageService;
import com.xiaoniu.subsystem.file.service.ISysFileService;
import com.xiaoniu.subsystem.strategy.FileUtil;
import com.xiaoniu.subsystem.strategy.UnZipStrategy;
import com.xiaoniu.subsystem.strategy.bean.FileObj;
import com.xiaoniu.subsystem.strategy.factory.UnZipStrategyFactory;
import com.xiaoniu.subsystem.system.utils.MysqlDataBackupUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ProfileManageServiceImpl extends ServiceImpl<ProfileManageMapper, ProfileManage> implements IProfileManageService {
    @Resource
    private ISysFileService fileService;
    @Resource
    private ManageFileMapper manageFileMapper;

    @Override
    public IPage<ProfileManageVO> selectProfilePage(IPage<ProfileManageVO> page, ProfileManageVO profile) {
        return page.setRecords(baseMapper.selectProfileManagePage(page, profile));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importProFile(MultipartFile multipartFile, ProfileSaveDTO dto) {
        if(StringUtils.isBlank(dto.getType())) {
            throw new ServiceException("请选择导入类型");
        }
        if(ObjectUtils.isEmpty(multipartFile)) {
            throw new ServiceException("文件不能为空");
        }
        File file = new File(multipartFile.getOriginalFilename());
        List<String> zipTypeList = new ArrayList<>();
        zipTypeList.add("zip");
        zipTypeList.add("tar");
        zipTypeList.add("rar");
        zipTypeList.add("7z");
        String fileType = FileUtil.getFileType(multipartFile.getOriginalFilename());
        if (!zipTypeList.contains(fileType)) {
            throw new ServiceException("上传的文件格式不对，请检查");
        }
        String url = "";
        try {
            //上传
            url = fileService.uploadFile(multipartFile);
            try (FileOutputStream fos = new FileOutputStream(file)) {
                FileCopyUtils.copy(multipartFile.getInputStream(), fos);
            }
        } catch (Exception e) {
            log.error("文件处理失败");
        }
        String fileName = file.getName();
        int index = fileName.lastIndexOf(".");
        //获取文件大小
        String fileSize = FileUtil.formatFileSize(file.length());
        ProfileManage profileManage = new ProfileManage();
        BeanUtil.copy(dto,profileManage);
        profileManage.setProfileName(fileName.substring(0, index));
        profileManage.setFileSize(fileSize);
        profileManage.setYear(DateUtils.getDate("YYYY"));
        profileManage.setType(dto.getType());
        profileManage.setUrl(url);
        profileManage.setCreateTime(new Date());
        profileManage.setUpdateTime(new Date());
        profileManage.setStatus(Constants.ONE);
        profileManage.setIsDeleted(Constants.ZERO);
        baseMapper.insert(profileManage);

        String suffix = fileName.substring(index + 1);
        UnZipStrategy unZipStrategy = UnZipStrategyFactory.generate(suffix);
        try {
            List<FileObj> analysis = unZipStrategy.analysis(new FileInputStream(fileName));
            log.info("文件数量为{}", analysis.size());
            //处理资料
            processingData(analysis, profileManage.getProfileId(), dto.getType());
            MysqlDataBackupUtil.deleteFiles(file.getName());
        } catch (FileNotFoundException e) {
            log.error("压缩包格式不正确！！！");
        }
    }

    @Override
    public boolean updateByIds(List<String> list) {
        for (String id : list) {
            baseMapper.update(new LambdaUpdateWrapper<ProfileManage>()
                    .set(ProfileManage::getUrl,"")
                    .set(ProfileManage::getProfileCode,"")
                    .set(ProfileManage::getRemark,"")
                    .set(ProfileManage::getUpdateTime,null)
                    .eq(ProfileManage::getProfileId,id));
        }
        return true;
    }

    /**
     * 处理资料
     *
     * @param analysis  文件
     * @param profileId 资料管理信息
     * @param type      类型
     */
    public void processingData(List<FileObj> analysis, Long profileId, String type) {
        List<ManageFile> tbManageFiles = new ArrayList<>();
        for (FileObj fileObj : analysis) {
            String url = "";
            if (StringUtils.isNotNull(fileObj.getBytes())) {
                try {
                    // 将字节数组转换为 InputStream
                    InputStream inputStream = new ByteArrayInputStream(fileObj.getBytes());
                    MultipartFile multipartFile = FileUtil.inputStreamConvertMultipartFile(inputStream, IdUtils.fastSimpleUUID() + "." + fileObj.getSuffix());
                    url = fileService.uploadFile(multipartFile);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            String fileName = fileObj.getDocName();
            String[] split = fileName.split("\\.");
            // int index = fileName.lastIndexOf(".");
            ManageFile tbManageFile = new ManageFile();
            tbManageFile.setProfileId(profileId);
            tbManageFile.setFileName(split[0]);
            tbManageFile.setType(split[1]);
            tbManageFile.setUrl(url);
            tbManageFiles.add(tbManageFile);
        }
        if (!CollectionUtils.isEmpty(tbManageFiles)) {
            manageFileMapper.insertBatch(tbManageFiles);
        }
    }

}
