package org.jeecg.modules.bytedance.common.service.impl;

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.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.bytedance.advertise.entity.AiBytedanceAdvertiserStrategy;
import org.jeecg.modules.bytedance.common.constant.BytedanceConstant;
import org.jeecg.modules.bytedance.common.entity.MaterialImageInfo;
import org.jeecg.modules.bytedance.common.mapper.MaterialImageInfoMapper;
import org.jeecg.modules.bytedance.common.service.IMaterialImageInfoService;
import org.jeecg.modules.bytedance.common.utils.*;
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.Date;
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;

    @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.setMaterialDescribe(json.getString("materialDescribe"));
                    materialImageInfo.setType("ICON");
                    String url = "https:" + json.getString("url");
                    materialImageInfo.setUrl(url);
                    materialImageInfo.setMaterialName(json.getString("materialName"));
                    materialImageInfo.setStatus(0);
                    materialImageInfo.setUserId(userId);
                    String localUrl = LoadFileUtil.downLoadFromUrl(url, downloadUrl);
                    String md5Code = MD5Util.getFileMd5(localUrl);
                    materialImageInfo.setCode(md5Code);
                    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();
        }

    }

    /**
     * 检查自己数据库 ctop_material_image_info 是否有图片素材
     * @param code
     * @param videoId
     * @return
     */
    @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("type", BytedanceConstant.IMAGE_TYPE_ICON);
        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();
    }

    @Override
    public List<JSONObject> getUrlList(String videoId) {
        return materialImageInfoMapper.getUrlList(videoId);
    }

    @Override
    public void initImageCode(MaterialImageInfo image) {
        //String localUrl = LoadFileUtil.downLoadFromUrl(image.getUrl(), downloadUrl);
        //String md5Code = null;
        try {
            /*md5Code = MD5Util.getFileMd5(localUrl);
            image.setCode(md5Code);
            image.setUpdateTime(new Date());
            this.saveOrUpdate(image);*/

            image.setType("ICON");
            String url = "https:" + image.getUrl();
            image.setUrl(url);
            image.setStatus(0);

            String imaUrl = LoadFileUtil.downLoadFromUrl(url, downloadUrl);
            String urlMd5 = MD5Util.getFileMd5(imaUrl);
            image.setCode(urlMd5);
            File picture = new File(imaUrl);
            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();
            image.setSize(size);
            image.setHeight(String.valueOf(height));
            image.setWidth(String.valueOf(width));
            QueryWrapper<MaterialImageInfo> queryWrapper = new QueryWrapper<>();
            MaterialImageInfo info = this.getOne(queryWrapper.eq("code", image.getCode()));
            if (Check.isNull(info)){
                this.saveOrUpdate(image);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public MaterialImageInfo getByCode(String signature) {
        QueryWrapper<MaterialImageInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",signature);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }


    @Override
    public List<MaterialImageInfo> getListByVideoSignature(String signature) {
        QueryWrapper<MaterialImageInfo>queryWrapper =new QueryWrapper<>();
        if(null!=signature&&!"".equals(signature.trim())){
            queryWrapper.eq("video_id",signature);
        }
        return this.list(queryWrapper);
    }


}
