package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.MaterialImageInfo;
import cn.com.ctop.common.module.mapper.MaterialImageInfoMapper;
import cn.com.ctop.common.module.service.IMaterialImageInfoService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 素材
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-03-16
 */
@Slf4j
@Service
public class MaterialImageInfoServiceImpl extends ServiceImpl<MaterialImageInfoMapper, MaterialImageInfo> implements IMaterialImageInfoService {

    @Value("${oss.replace.download}")
    private String downloadUrl;
    @Value("${oss.replace.replace-value}")
    private String replaceValue;
    @Value("${oss.replace.replace-old-value}")
    private String replaceOldValue;


    @Autowired
    private MaterialImageInfoMapper materialImageInfoMapper;


    @Override
    public void insertImage(JSONObject imageJson) {
        try {

            String videoId = imageJson.getString("videoId");
            if (Check.isNull(videoId)) {
                log.error("视频id不能为空");

            }
            String userId = imageJson.getString("userId");
            JSONArray imageArr = imageJson.getJSONArray("imageArr");
            for (int i = 0; i < imageArr.size(); i++) {
                JSONObject json = imageArr.getJSONObject(i);
                if (!Check.isNull(json)) {
                    MaterialImageInfo materialImageInfo = new MaterialImageInfo();
                    materialImageInfo.setVideoId(videoId);
                    materialImageInfo.setCode(json.getString("code"));
                    materialImageInfo.setMaterialDescribe(json.getString("materialDescribe"));
                    materialImageInfo.setType("IMAGE");
                    String url = "https:" + json.getString("url");
                    materialImageInfo.setUrl(url);
                    materialImageInfo.setMaterialName(json.getString("materialName"));
                    materialImageInfo.setStatus(0);
                    materialImageInfo.setUserId(userId);
                    String replaceUrl = url.replace(replaceOldValue, replaceValue);
                    log.info("图片replaceUrl:{}", url);
                    String localUrl = LoadFileUtil.downLoadFromUrl(replaceUrl, downloadUrl);
                    File picture = new File(localUrl);
                    BufferedImage sourceImg = null;
                    try {
                        sourceImg = ImageIO.read(new FileInputStream(picture));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String size = String.format("%.1f", picture.length() / 1024.0);
                    Integer width = sourceImg.getWidth();
                    Integer height = sourceImg.getHeight();
                    materialImageInfo.setSize(size);
                    materialImageInfo.setHeight(String.valueOf(height));
                    materialImageInfo.setWidth(String.valueOf(width));
                    materialImageInfoMapper.insertSelective(materialImageInfo);
                    LoadFileUtil.delFile(localUrl);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public Map<String, Object> checkMaterialInfo(String code, String videoId) {


        Map<String, Object> result = new HashMap<>();
        QueryWrapper<MaterialImageInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        queryWrapper.eq("video_id", videoId);
        queryWrapper.last("limit 1");
        MaterialImageInfo info = this.getOne(queryWrapper);
        if (null != info) {
            //文件已存在
            ResultMapUtils.setResultMap(result, StatusCode.FILE_HAS_UPLOAD.getCode());
            result.put("url", info.getUrl());
            return result;
        } else {
            //文件尚未上传
            ResultMapUtils.setResultMap(result, StatusCode.FILE_HAS_NOT_UPLOAD.getCode());
            return result;
        }

    }


    @Override
    public List<String> getCodeList() {
        return materialImageInfoMapper.getCodeList();
    }

}
