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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.constant.ServerCode;
import com.fdkankan.common.constant.TbStatus;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.fyun.oss.UploadToOssUtil;
import com.fdkankan.platform.goods.common.UploadPath;
import com.fdkankan.platform.order.entity.SpaceSdk;
import com.fdkankan.platform.order.mapper.ISpaceSdkMapper;
import com.fdkankan.platform.order.service.ISpaceSdkService;
import com.fdkankan.platform.user.request.RequestSdkVersion;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;
import java.util.Date;

/**
 * <p>
 * space sdk表 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-12-24
 */
@Service
public class SpaceSdkServiceImpl extends ServiceImpl<ISpaceSdkMapper, SpaceSdk> implements ISpaceSdkService {

    public static final Logger log = LoggerFactory.getLogger("programLog");
    private static String DIR_NAME = "new4dkk/v2/images/_/common/data/";

    @Autowired
    private UploadToOssUtil uploadToOssUtil;
    @Value("${upload.type}")
    private String ossType;

    @Value("${oss.prefix.sdk}")
    private String prefixAli;

    @Override
    public Page<SpaceSdk> getPageByParam(RequestSdkVersion param) {
        LambdaQueryWrapper<SpaceSdk> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SpaceSdk::getTbStatus, TbStatus.VALID.code());
        if(param.getStatus()!=null){
            queryWrapper.eq(SpaceSdk::getStatus,param.getStatus());
        }
        if(StringUtils.isNotEmpty(param.getSearchKey()) && !param.getSearchKey().equals("%")){
            queryWrapper.like(SpaceSdk::getVersion,param.getSearchKey());
        }
        if(StringUtils.isNotEmpty(param.getPlatformType())){
            queryWrapper.like(SpaceSdk::getPlatformType,param.getPlatformType());
        }
        queryWrapper.orderByDesc(SpaceSdk::getIsTop,SpaceSdk::getPublishTime);
        Page<SpaceSdk> page = new Page<>(param.getPageNum(),param.getPageSize());
        return this.page(page, queryWrapper);
    }

    @Override
    public String upload(MultipartFile file, String version, String imprintCh, String imprintEn, Integer isTop, String platformType) throws Exception {
        log.info("run upload");

        if (!file.isEmpty()&& file.getSize() <= 0) {
            throw new BusinessException(ErrorCode.FILE_NOT_EXIST);
        }
        String fullFileName = "";
        if(platformType.equals("1")){
            fullFileName = "SpaceTarget_Unity3D";
        }else if(platformType.equals("2")){
            fullFileName = "SpaceTarget_UE4";
        }

        String fileNameAll = "";
        // 文件名全名
        fileNameAll = file.getOriginalFilename();

        // 将文件转字节-> 字符串
        String fileContent = Base64.getEncoder().encodeToString(file.getBytes());

        // 获取类路径
        String resourcePath = FileUtils.getResource();
        log.info("resourcePath: {}", resourcePath);

        // 创建目录
        String dirPath = resourcePath + DIR_NAME;
        FileUtils.createDir(dirPath);

        // 拼接唯一文件名
        String fileName = fullFileName + "_" + version + "_" + UploadPath.dateStr() + fileNameAll;

        // 文件保存路径
        String filePath = dirPath + UploadPath.dateStr() + fileNameAll;

        // 写文件到本地
        FileUtils.base64ToFileWriter(fileContent, filePath);
        log.info("filePath: {}", filePath);

        // 上传到阿里云sso
        uploadToOssUtil.uploadSdk(filePath, DIR_NAME + fileName);
        log.info("upload success");

        String url = prefixAli + DIR_NAME + fileName;

        log.info("upload url: {}" + url);

        this.updatTopFBysdkId(platformType);//取消所有置顶

        SpaceSdk managerSdkEntity = new SpaceSdk();
        managerSdkEntity.setVersion(version);
        managerSdkEntity.setImprintCh(imprintCh);
        managerSdkEntity.setImprintEn(imprintEn);
        managerSdkEntity.setIsTop(1);
        managerSdkEntity.setStatus(0);
        managerSdkEntity.setPlatformType(platformType);
        managerSdkEntity.setFileUrl(url);
        managerSdkEntity.setFileName(fullFileName);

        this.save(managerSdkEntity);

        // 删除本地文件
        FileUtils.deleteFile(filePath);

        return url;
    }

    @Override
    public String updateByEntity(SpaceSdk param) {
        if(param.getId() == null || StringUtils.isEmpty(param.getPlatformType()) || param.getIsTop()==null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        if(param.getIsTop().equals(1)){
            this.updatTopFBysdkId(param.getPlatformType());//取消所有置顶
        }
        if(!this.updateById(param)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String delById(Long id) {
        if(id == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        LambdaUpdateWrapper<SpaceSdk> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SpaceSdk::getTbStatus,TbStatus.DELETE.code())
                .eq(SpaceSdk::getId,id);
        this.update(updateWrapper);
        return ServerCode.SUCCESS.message();
    }


    @Override
    public String online(RequestSdkVersion param) {
        if(param.getId() == null || param.getStatus() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        SpaceSdk managerSdkEntity = this.getById(param.getId());
        if(managerSdkEntity == null || TbStatus.DELETE.code().equals(managerSdkEntity.getTbStatus())){
            throw new BusinessException(-1,"获取记录为空");
        }
        if(managerSdkEntity.getPublishTime()!=null){
            return this.updateBySdkId(param.getId(),param.getStatus());
        }else{
            return this.updateBySdkIdPublish(param.getId(),param.getStatus());
        }
    }

    private String updateBySdkIdPublish(Long id, Integer status) {
        LambdaUpdateWrapper<SpaceSdk> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SpaceSdk::getStatus,status)
                .set(SpaceSdk::getPublishTime,new Date())
                .eq(SpaceSdk::getId,id).eq(SpaceSdk::getTbStatus,TbStatus.VALID.code());
        this.update(updateWrapper);
        return ServerCode.SUCCESS.message();
    }

    private String updateBySdkId(Long id, Integer status) {
        LambdaUpdateWrapper<SpaceSdk> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SpaceSdk::getStatus,status)
                .eq(SpaceSdk::getId,id).eq(SpaceSdk::getTbStatus,TbStatus.VALID.code());
        this.update(updateWrapper);
        return ServerCode.SUCCESS.message();
    }

    private void updatTopFBysdkId(String platformType) {
        LambdaUpdateWrapper<SpaceSdk> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SpaceSdk::getIsTop,0)
                .eq(SpaceSdk::getPlatformType,platformType);
        this.update(updateWrapper);
    }
    private void updatTopFBysdkId(Long Id,Integer isTop) {
        LambdaUpdateWrapper<SpaceSdk> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SpaceSdk::getIsTop,isTop)
                .eq(SpaceSdk::getId,Id).eq(SpaceSdk::getTbStatus,TbStatus.VALID.code());
        this.update(updateWrapper);
    }
}
