package cn.com.ctop.kuaishou.modules.batch.controller;

import cn.com.ctop.common.module.constant.CosConstant;
import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CosUtils;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouVideoGet;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouMaterialUploadService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouVideoGetService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/kusiShouUpload")
public class KuaiShouMaterialUploadController {

    @Autowired
    private IKuaiShouMaterialUploadService uploadService;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private IKuaiShouImageGetService iKuaiShouImageGetService;
    @Autowired
    private IKuaiShouVideoGetService videoGetService;

    @PostMapping(value = "/video")
    public Result<JSONObject> video(@RequestBody JSONObject requestJson) throws Exception {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            if (Check.isNull(accountId)) {
                throw new Exception("请传入账户id");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            String url = requestJson.getString("url");
            if (Check.isNull(url)) {
                throw new Exception("请传入视频");
            }
            String videoUrl;
            if (!url.contains("https:")) {
                videoUrl = KuaishouInterfaceConstant.HTTPS_PREFIX + url;
            } else {
                videoUrl = url;
            }
            Integer type = requestJson.getInteger("type");
            if (Check.isNull(type)) {
                throw new Exception("请传入视频类型");
            }
            String signature = requestJson.getString("signature");
            if (Check.isNull(type)) {
                throw new Exception("视频标识错误");
            }
            JSONObject videoJson = uploadService.video(videoUrl, type, accountId, oauthToken.getAccessToken(), signature);
            JSONObject returnJson = new JSONObject();
            if (videoJson.getBoolean("success")) {
                result.setSuccess(true);
                returnJson.put("photoId", videoJson.getString("photoId"));
                returnJson.put("signature", videoJson.getString("signature"));
                returnJson.put("videoUrl", videoUrl);
                result.setResult(returnJson);
                result.setMessage(videoJson.getString("message"));
            } else {
                result.setSuccess(false);
                result.setMessage(videoJson.getString("message"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }


        return result;
    }


    @GetMapping(value = "/checkVideo")
    public Result<JSONObject> video(String signature, Long accountId) {
        Result<JSONObject> result = new Result();
        try {
            JSONObject returnJson = new JSONObject();
            QueryWrapper<KuaiShouVideoGet> videoGetQueryWrapper = new QueryWrapper<>();
            videoGetQueryWrapper.eq("signature", signature);
            videoGetQueryWrapper.eq("account_id", accountId);
            videoGetQueryWrapper.last("limit 1");
            KuaiShouVideoGet videoGet = videoGetService.getOne(videoGetQueryWrapper);
            if (Check.isNull(videoGet)) {
                returnJson.put("isExistence", false); // 未存在
            } else {
                returnJson.put("isExistence", true);
                returnJson.put("videoUrl", videoGet.getUrl());
                returnJson.put("photoId", videoGet.getPhotoId());
                returnJson.put("signature", signature);
            }
            result.setSuccess(true);
            result.setResult(returnJson);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }

        return result;
    }


    @PostMapping(value = "/image")
    public Result<JSONArray> image(@RequestBody JSONObject requestJson) throws Exception {
        Result<JSONArray> result = new Result<>();

        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            JSONArray returnArr = new JSONArray();
            JSONArray imageArr = requestJson.getJSONArray("uploadImageArr");
            if (!Check.isNull(imageArr)) {
                for (int i = 0; i < imageArr.size(); i++) {
                    JSONObject imageJson = imageArr.getJSONObject(i);
                    String url = imageJson.getString("url");
                    String imageUrl;
                    if (!url.contains("https:")) {
                        imageUrl = KuaishouInterfaceConstant.HTTPS_PREFIX + url;
                    } else {
                        imageUrl = url;
                    }
                    String signature = imageJson.getString("signature");
                    QueryWrapper<KuaiShouImageGet> imageGetQueryWrapper = new QueryWrapper<>();
                    imageGetQueryWrapper.eq("signature", signature);
                    imageGetQueryWrapper.eq("account_id", accountId);
                    imageGetQueryWrapper.last("limit 1");
                    KuaiShouImageGet imageGet = iKuaiShouImageGetService.getOne(imageGetQueryWrapper);
                    if (Check.isNull(imageGet)) {
                        String imageToken = uploadService.kuauiShouImageUpload(imageUrl, signature, accountId, oauthToken.getAccessToken());
                        if (!Check.isNull(imageToken)) {
                            JSONObject returnJson = new JSONObject();
                            returnJson.put("url", imageUrl);
                            returnJson.put("signature", signature);
                            returnJson.put("imageToken", imageToken);
                            returnArr.add(returnJson);
                        }
                    } else {
                        JSONObject returnJson = new JSONObject();
                        returnJson.put("url", imageUrl);
                        returnJson.put("signature", signature);
                        returnJson.put("imageToken", imageGet.getImageToken());
                        returnArr.add(returnJson);
                    }
                }

            }
            result.setSuccess(true);
            result.setResult(returnArr);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }

        return result;
    }


    @PostMapping(value = "/uploadImage")
    public Result<Object> uploadImage(@RequestParam("file") MultipartFile file, Long accountId, String signature) throws Exception {
        try {
            QueryWrapper<KuaiShouImageGet> imageGetQueryWrapper = new QueryWrapper<>();
            imageGetQueryWrapper.eq("signature", signature);
            imageGetQueryWrapper.eq("account_id", accountId);
            imageGetQueryWrapper.last("limit 1");
            KuaiShouImageGet imageGet = iKuaiShouImageGetService.getOne(imageGetQueryWrapper);
            if (Check.isNull(imageGet)) {
                CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
                if (Check.isNull(oauthToken)) {
                    return Result.error("未获取到账户信息");
                }
                String[] split = file.getOriginalFilename().split("\\.");
                String fileName = accountId + System.currentTimeMillis() + UUID.randomUUID().toString().replace("-", "").substring(0, 5) + "." + split[1];
                InputStream inputStream = null;
                try {
                    inputStream = file.getInputStream();
                } catch (IOException e) {
                    log.error("图片上传异常");
                }
                String splashPath = "splash/image/" + DateUtils.date2Str() + "/";
                String md5 = CosUtils.uploadFileByInputStream(inputStream, splashPath, fileName);
                Thread.sleep(200);
                String imageUrl = CosConstant.URL_COS_ADDRESS + splashPath + fileName;
                String imageToken = uploadService.kuauiShouImageUpload(imageUrl, md5, accountId, oauthToken.getAccessToken());
                if (!Check.isNull(imageToken)) {
                    imageGetQueryWrapper = new QueryWrapper<>();
                    imageGetQueryWrapper.eq("image_token", imageToken);
                    imageGetQueryWrapper.eq("account_id", accountId);
                    imageGetQueryWrapper.last("limit 1");
                    KuaiShouImageGet one = iKuaiShouImageGetService.getOne(imageGetQueryWrapper);
                    return Result.ok(one);
                }
            } else {
                return Result.ok(imageGet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }


}
