package cn.com.ctop.kuaishou.modules.batch.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.AesEncryptUtil;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImage;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouImageMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
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.stereotype.Service;

import java.util.List;

/**
 * @Description: 快手-本地图片保存
 * @Author: jeecg-boot
 * @Date: 2019-08-14
 * @Version: V1.0
 */
@Slf4j
@Service
public class KuaiShouImageServiceImpl extends ServiceImpl<KuaiShouImageMapper, KuaiShouImage> implements IKuaiShouImageService {

    @Autowired
    private KuaiShouImageMapper imageMapper;

    @Autowired
    private IKuaishouInterfaceService interfaceService;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;

    @Override
    public void insert(JSONObject requestJson) throws Exception {
        JSONArray imageArr = requestJson.getJSONArray("localImageUrl");
        Long accountId = requestJson.getLong("accountId");
        CtopOauthToken cTopOauthToken = oauthTokenService.getOauthTokenByAccountId(String.valueOf(accountId));
        if (Check.isNull(cTopOauthToken)) {
            throw new Exception("未获取到token信息");
        }
        String accessToken = cTopOauthToken.getAccessToken();
        if (!Check.isNull(imageArr)) {
            for (int i = 0; i < imageArr.size(); i++) {
                KuaiShouImage image = new KuaiShouImage();
                String imageUrl = imageArr.get(i).toString();
                String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
                String fileNameStr = null;
                if (!Check.isNull(fileName)) {
                    String[] split = fileName.split("-");
                    fileNameStr = split[0];
                }
                image.setImageName(AesEncryptUtil.getUrlDecoderString(fileNameStr));
                image.setLoginId(requestJson.getString("loginId"));
                image.setMaterialType(requestJson.getString("materialType"));
                image.setPositionType(requestJson.getString("positionType"));
                image.setAccountId(accountId);
                String imageUrlStr;
                if (!imageUrl.contains(KuaishouInterfaceConstant.HTTPS_PREFIX)) {
                    imageUrlStr = KuaishouInterfaceConstant.HTTPS_PREFIX + imageUrl;
                } else {
                    imageUrlStr = imageUrl;
                }
                image.setLocalUrl(imageUrlStr);
                imageMapper.insert(image);

                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        log.info("快手开始上传图片，accountId：{}", accountId);
                        interfaceService.imageUpload(accountId, accessToken, imageUrlStr, 0);
                    }
                };
                thread.start();
            }
        }

    }

    @Override
    public String localInsert(JSONObject imageJson) {
        String url = imageJson.getString("url");
        String positionType = imageJson.getString("positionType");
        String videoUploadType = imageJson.getString("videoUploadType");
        String loginId = imageJson.getString("loginId");
        Long accountId = imageJson.getLong("accountId");

        QueryWrapper<KuaiShouImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("local_url", url);
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("position_type", positionType);
        queryWrapper.eq("material_type", videoUploadType);
        queryWrapper.eq("login_id", loginId);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 1");
        KuaiShouImage imageLocal = imageMapper.selectOne(queryWrapper);
        if (Check.isNull(imageLocal)) {
            KuaiShouImage image = new KuaiShouImage();
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            String fileNameStr = null;
            if (!Check.isNull(fileName)) {
                String[] split = fileName.split("-");
                fileNameStr = split[0];
            }
            image.setLoginId(loginId);
            image.setImageName(AesEncryptUtil.getUrlDecoderString(fileNameStr));
            image.setMaterialType(videoUploadType);
            image.setPositionType(positionType);
            if (!url.contains("https:")) {
                String imageUrl = KuaishouInterfaceConstant.HTTPS_PREFIX + url;
                image.setLocalUrl(imageUrl);
            } else {
                image.setLocalUrl(url);
            }
            image.setAccountId(accountId);

            imageMapper.insert(image);
            return image.getLocalUrl().toString();
        }

        return url;
    }

    @Override
    public JSONArray selectImageList(QueryWrapper<KuaiShouImage> queryWrapper) {
        List<KuaiShouImage> kuaiShouImages = imageMapper.selectList(queryWrapper);
        JSONArray jsonArray = new JSONArray();
        if (!Check.isNull(kuaiShouImages)) {
            for (KuaiShouImage image : kuaiShouImages) {
                if (!Check.isNull(image)) {
                    JSONObject json = new JSONObject();
                    json.put("id", image.getId());
                    json.put("src", image.getLocalUrl());
                    json.put("msrc", image.getLocalUrl());
                    json.put("w", 600);
                    json.put("h", 400);
                    json.put("name", image.getImageName());
                    jsonArray.add(json);
                }
            }
        }

        return jsonArray;
    }
}
