package cn.com.ctop.manage.modules.material.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.MaterialInfo;
import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
import cn.com.ctop.common.module.mapper.MaterialInfoMapper;
import cn.com.ctop.common.module.service.IFileInfoService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.manage.modules.material.service.IMaterialUploadService;
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.apache.http.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class MaterialUploadServiceImpl implements IMaterialUploadService {
    static ExecutorService executorService = Executors.newFixedThreadPool(3);


    @Autowired
    private CtopOauthTokenMapper oauthTokenMapper;
    @Autowired
    private MaterialInfoMapper materialInfoMapper;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;
    @Autowired
    private IFileInfoService fileInfoService;


    /**
     * 同步素材到账号下
     *
     * @param mediaId
     * @param materialArray
     * @param accountArray
     */

    @Override
    public void uploadAccount(String mediaId, JSONArray materialArray, JSONArray accountArray) {
        try {
            if ("2".equals(mediaId)) {
                this.kuaiShouUpload(mediaId, materialArray, accountArray);
            } else if ("1".equals(mediaId)) {
                this.touTiaoUpload(mediaId, materialArray, accountArray);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void touTiaoUpload(String mediaId, JSONArray materialArray, JSONArray accountArray) {
        for (int j = 0; j < materialArray.size(); j++) {
            String materialId = materialArray.getString(j);
            MaterialInfo materialInfo = materialInfoMapper.selectById(materialId);
            if (Check.isNull(materialInfo)) {
                continue;
            }
            try {

                for (int i = 0; i < accountArray.size(); i++) {
                    Long accountId = accountArray.getLong(i);
                    QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
                    tokenQueryWrapper.eq("account_id", accountId);
                    tokenQueryWrapper.eq("media_id", mediaId);
                    tokenQueryWrapper.orderByDesc("create_time");
                    tokenQueryWrapper.last("limit 1");
                    CtopOauthToken ctopOauthToken = oauthTokenMapper.selectOne(tokenQueryWrapper);
                    if (Check.isNull(ctopOauthToken)) {
                        continue;
                    }
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                System.err.println(Thread.currentThread().getName());
                                if ("VIDEO".equals(materialInfo.getType())) {
                                    fileInfoService.uploadVideoToBytedance(String.valueOf(accountId), materialInfo.getUrl());

                                } else if ("IMAGE".equals(materialInfo.getType())) {
                                    fileInfoService.uploadImageToBytedance(String.valueOf(accountId), materialInfo.getUrl());
                                }


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


        }


    }


    private void kuaiShouUpload(String mediaId, JSONArray materialArray, JSONArray accountArray) {
        for (int j = 0; j < materialArray.size(); j++) {
            String materialId = materialArray.getString(j);
            MaterialInfo materialInfo = materialInfoMapper.selectById(materialId);
            if (Check.isNull(materialInfo)) {
                continue;
            }
            try {
                String localUrl = LoadFileUtil.downLoadFromUrl(materialInfo.getUrl(), PropertiesUtils.getValue("kuaishou_config", "video_sava_path"));
                FileSystemResource resource = new FileSystemResource(new File(localUrl));
                Map<String, String> headerMap = new HashMap<>();
                headerMap.put("Content-Type", "multipart/form-data");
                JSONObject requestJson = new JSONObject();
                requestJson.put("file", resource);
                requestJson.put("signature", materialInfo.getCode());
                for (int i = 0; i < accountArray.size(); i++) {
                    Long accountId = accountArray.getLong(i);
                    QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
                    tokenQueryWrapper.eq("account_id", accountId);
                    tokenQueryWrapper.eq("media_id", mediaId);
                    tokenQueryWrapper.orderByDesc("create_time");
                    tokenQueryWrapper.last("limit 1");
                    CtopOauthToken ctopOauthToken = oauthTokenMapper.selectOne(tokenQueryWrapper);
                    if (Check.isNull(ctopOauthToken)) {
                        continue;
                    }
                    requestJson.put("advertiser_id", accountId);
                    headerMap.put("Access-Token", ctopOauthToken.getAccessToken());
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                System.err.println(Thread.currentThread().getName());
                                String url = "";
                                if ("VIDEO".equals(materialInfo.getType())) {
                                    url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.VIDEO_UPLOAD;

                                } else if ("IMAGE".equals(materialInfo.getType())) {
                                    url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.IMAGE_UPLOAD;
                                    requestJson.put("type", "2");
                                    requestJson.put("upload_type", "1");
                                }

                                String result = exceptInfoForRestTemplate(url, requestJson, headerMap);
                                JSONObject resultJson = JSONObject.parseObject(result);
                                if (!Check.isNull(resultJson)) {
                                    if (resultJson.getInteger("code") == 0) {
                                        JSONObject dataJson = resultJson.getJSONObject("data");
                                        if (!Check.isNull(dataJson)) {
                                            if ("IMAGE".equals(materialInfo.getType())) {
                                                kuaishouInterfaceService.imageGet(accountId, ctopOauthToken.getAccessToken(), dataJson.getString("image_token"));
                                            } else if ("VIDEO".equals(materialInfo.getType())) {
                                                kuaishouInterfaceService.videoGet(accountId, ctopOauthToken.getAccessToken(), dataJson.getString("photo_id"), dataJson.getString("signature"));
                                            }
                                        }

                                        log.info("素材同步完成，accountId：{}，code：{},返回信息：{}", accountId, materialInfo.getCode(), resultJson);
                                    } else {
                                        log.error("同步素材失败，返回信息：{}，请求参数：{}", resultJson, requestJson);
                                    }
                                }

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

                }
                /*boolean isTrue = LoadFileUtil.delFile(localUrl);
                if (isTrue) {
                    log.info("删除本地缓存素材成功，code：{}", materialInfo.getCode());
                }*/

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


        }


    }


    @Autowired
    private RestTemplate rest;

    private String exceptInfoForRestTemplate(String url, Map<String, Object> paramMap, Map<String, String> headerMap) throws ParseException {
        try {
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            if (!Check.isNullMap(paramMap)) {
                for (String key : paramMap.keySet()) {
                    param.add(key, paramMap.get(key));
                }
                HttpHeaders headers = new HttpHeaders();
                if (!Check.isNullMap(headerMap)) {
                    for (String key : headerMap.keySet()) {
                        headers.add(key, headerMap.get(key));
                    }
                }
                HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param, headers);
                ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
                return responseEntity.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
