package com.fdkankan.platform.agent.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.fyun.oss.UploadToOssUtil;
import com.fdkankan.platform.agent.entity.AppFile;
import com.fdkankan.platform.agent.mapper.IAppFileMapper;
import com.fdkankan.platform.agent.request.RequestAppFile;
import com.fdkankan.platform.agent.service.IAppFileService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Base64;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2022-04-27
 */
@Service
public class AppFileServiceImpl extends ServiceImpl<IAppFileMapper, AppFile> implements IAppFileService {

    @Resource
    private IAppFileMapper appFileMapper;
    @Autowired
    private UploadToOssUtil uploadToOssUtil;
    @Value("${upload.type}")
    private String ossType;
    @Value("${oss.prefix.sdk}")
    private String prefixAli;

    @Override
    public String upload(MultipartFile file)  {
        if (ObjectUtils.isEmpty(file) || file.isEmpty() || file.getSize() <= 0) {
            throw new BusinessException(ErrorCode.FAILURE_CODE_3017);
        }
        try {
            String fileContent = Base64.getEncoder().encodeToString(file.getBytes());
            String filePath = FileUtils.getResource().concat("uploadAppTmp");
            FileUtils.createDir(filePath);
            filePath = filePath.concat("/").concat(file.getOriginalFilename());
            // 删除旧文件
            FileUtils.deleteFile(filePath);
            // 写文件到本地
            FileUtils.base64ToFileWriter(fileContent, filePath);
            return filePath;
        }catch (Exception e){
            throw new BusinessException(-1,"上传失败");
        }
    }

    @Override
    public Page<AppFile> getPageByParam(RequestAppFile param) {
        LambdaQueryWrapper<AppFile> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtil.isNotBlank(param.getKeyword())){
            queryWrapper.like(AppFile::getAgent,param.getKeyword());
        }
        queryWrapper.orderByDesc(AppFile::getCreateTime);
        Page<AppFile> page = new Page<>(param.getPageNum(),param.getPageSize());
        return this.page(page,queryWrapper);
    }

    @Override
    public List<String> agenetList(String name) {
        return appFileMapper.agentList(name);
    }

    @Override
    public void saveByParam(RequestAppFile param) {
        if(ObjectUtils.isEmpty(param.getName())){
            throw new BusinessException(-1,"文件名称为空，请输入文件名称！");
        }
        AppFile managerAPPEntity = new AppFile();
        BeanUtils.copyProperties(param, managerAPPEntity);
        String basePath = FileUtils.getResource().concat("uploadAppTmp/");

        String filePath = basePath.concat(param.getName());
        File file = new File(filePath);
        if (!file.exists()) {
            throw new BusinessException(-1,"应用包文件未上传，请先上传文件！");
        }

        String versionFilePath = basePath.concat("version.json");
        if (!new File(versionFilePath).exists()) {
            throw new BusinessException(-1,"version.json 文件未上传，请先上传文件！");
        }

        String fileType = param.getName().substring(param.getName().lastIndexOf(".")+1);

        String ossPathPrefix = "apps/customApp/" + param.getAgent() + "/"+param.getAppType()+"/";

        uploadToOssUtil.upload(filePath, ossPathPrefix+"4dkankan."+fileType);
        // 上传到 历史记录文件夹目录
        uploadToOssUtil.upload(filePath, ossPathPrefix+"oldapps/" + file.getName());

        // 上传到 version.json 文件
        uploadToOssUtil.upload(versionFilePath, ossPathPrefix+"version/version.json");

        // 删除旧文件
        FileUtils.deleteFile(filePath);
        FileUtils.deleteFile(versionFilePath);

        managerAPPEntity.setUrl(prefixAli.concat(ossPathPrefix+"4dkankan."+fileType));
        managerAPPEntity.setFileServerType(ossType);
        this.save(managerAPPEntity);
    }

}
