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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.FileMd5Util;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.common.validation.ValidationUtils;
import com.fdkankan.fyun.oss.UploadToOssUtil;
import com.fdkankan.platform.agent.request.RequestSearch;
import com.fdkankan.platform.goods.common.UploadPath;
import com.fdkankan.platform.goods.entity.CameraVersion;
import com.fdkankan.platform.goods.mapper.ICameraVersionMapper;
import com.fdkankan.platform.goods.service.ICameraVersionService;
import com.fdkankan.scene.api.feign.SceneUserSceneClient;
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 javax.annotation.Resource;
import java.io.File;
import java.util.Base64;
import java.util.List;

/**
 * <p>
 * 相机版本表 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-12-24
 */
@Service
public class CameraVersionServiceImpl extends ServiceImpl<ICameraVersionMapper, CameraVersion> implements ICameraVersionService {

    private static Logger log = LoggerFactory.getLogger("programLog");

    @Value("${upload.type}")
    private String ossType;
    @Value("${prefix.ali}")
    private String prefixAli;
    @Resource
    private UploadToOssUtil uploadToOssUtil;
    @Autowired
    private SceneUserSceneClient sceneUserSceneClient;

    private LambdaQueryWrapper<CameraVersion> getQueryByType(String type){
        LambdaQueryWrapper<CameraVersion> queryWrapper = new LambdaQueryWrapper<>();
        String cameraType = StringUtils.isNotBlank(type) ? type : "1";
        queryWrapper.eq(CameraVersion::getTbStatus, TbStatus.VALID.code());
        queryWrapper.eq(CameraVersion::getCameraType,cameraType)
                .orderByDesc(CameraVersion::getCreateTime);
        return queryWrapper;
    }

    @Override
    public Page<CameraVersion> getPageByType(Integer pageNum, Integer pageSize, String type) {
        return this.page(new Page<>(pageNum, pageSize), getQueryByType(type));
    }

    @Override
    public String updateStatus(Long id, String status, String type) {
        CameraVersion cameraVersion = this.getById(id);
        if(cameraVersion == null){
            throw new BusinessException(ErrorCode.NOT_RECORD);
        }
        if (!ValidationUtils.validateRecStatus(status)) {
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        // 仅有有一台相机是活动状态
        // 查找所以活动状态相机
        String cameraType = StringUtils.isNotBlank(type) ? type : "1";
        LambdaUpdateWrapper<CameraVersion> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CameraVersion::getAcStatus,"I")
                .eq(CameraVersion::getAcStatus,"A")
                .eq(CameraVersion::getCameraType,cameraType);
        this.update(updateWrapper);

        cameraVersion.setAcStatus(status);
        if(!this.updateById(cameraVersion)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        return ServerCode.SUCCESS.message();
    }

    @Override
    public Page<CameraVersion> searchLike(RequestSearch param) {
        String cameraType = StringUtils.isNotBlank(param.getType()) ? param.getType() : "1";
        LambdaQueryWrapper<CameraVersion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CameraVersion::getTbStatus,TbStatus.VALID.code());
        queryWrapper.eq(CameraVersion::getCameraType,cameraType);
        if(param.getStartDate()!=null){
            queryWrapper.ge(CameraVersion::getCreateTime,param.getStartDate());
        }
        if(param.getStartDate()!=null){
            queryWrapper.le(CameraVersion::getCreateTime,param.getEndDate());
        }
        if (StringUtils.isNotBlank(param.getItemName())) {
            queryWrapper.and(wrapper -> wrapper
                    .like(CameraVersion::getFileName,param.getItemName())
                    .or()
                    .like(CameraVersion::getVersion,param.getItemName()));
        }
        queryWrapper.orderByDesc(CameraVersion::getCreateTime);

        return this.page(new Page<>(param.getPageNum(), param.getPageSize()), queryWrapper);
    }

    @Override
    public String upload(MultipartFile file, String version, String description, String minVersion, String type)throws Exception {
        String cameraType = StringUtils.isNotBlank(type) ? type : "1";
        log.info("run upload");
        if (!file.isEmpty()&& file.getSize() <= 0) {
            throw new BusinessException(ErrorCode.FILE_NOT_EXIST);
        }
        // 文件名全名
        String fullFileName = file.getOriginalFilename();
        // 将文件转字节-> 字符串
        String fileContent = Base64.getEncoder().encodeToString(file.getBytes());
        // 获取类路径
        String resourcePath = FileUtils.getResource();
        log.info("resourcePath: {}", resourcePath);
        // 创建目录
        String dirPath = resourcePath + UploadPath.DIR_NAME;
        FileUtils.createDir(dirPath);
        // 拼接唯一文件名
        String fileName = UploadPath.dateStr() + fullFileName;
        // 文件保存路径
        String filePath = dirPath + UploadPath.dateStr() + fullFileName;
        // 写文件到本地
        FileUtils.base64ToFileWriter(fileContent, filePath);
        log.info("filePath: {}", filePath);
        // 上传到阿里云sso
        uploadToOssUtil.upload(filePath, UploadPath.DIR_NAME + fileName);
        log.info("upload success");
        String url = prefixAli + UploadPath.ALIYUN_SSO_PATH + fileName;
        if("aws".equals(ossType)){
            url = UploadPath.YAMAXUN_S3_PATH + fileName;
        }
        log.info("upload url: {}" + url);
        // 添加对象信息
        CameraVersion versionEntity = new CameraVersion();
        versionEntity.setFileName(fileName);
        versionEntity.setFileUrl(url);
        versionEntity.setVersion(version);
        versionEntity.setDescription(description);
        versionEntity.setCameraType(Integer.parseInt(cameraType));
        versionEntity.setMinVersion(minVersion);
        versionEntity.setAcStatus("I");
        versionEntity.setFileMd5(FileMd5Util.getFileMD5(new File(filePath)));
        this.save(versionEntity);
        // 删除本地文件
        FileUtils.deleteFile(filePath);
        return ServerCode.SUCCESS.message();
    }

    @Override
    public CameraVersion getByType(String type) {
        List<CameraVersion> list = this.list(getQueryByType(type).eq(CameraVersion::getTbStatus, TbStatus.VALID.code()));
        if(list == null || list.size() <= 0){
            return null;
        }
        return list.get(0);
    }

    @Override
    public int updateImageVersion(String num) {
        sceneUserSceneClient.updateImageVersionFromSceneProEdit(num);
        return 1;
    }
}
