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

import cn.com.ctop.common.module.enums.MaterialEnum;
import cn.com.ctop.common.module.service.IMaterialImageInfoService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouAdvertiserBaseInfoService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
import cn.com.ctop.manage.modules.material.service.IMaterialUploadImageService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.ParseException;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class MaterialUploadImageServiceImpl implements IMaterialUploadImageService {
    static ExecutorService executorService = Executors.newFixedThreadPool(15);

    @Value("${oss.replace.download}")
    private String downloadUrl;

    @Autowired
    private IMaterialImageInfoService materialImageInfoService;
    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IKuaiShouAdvertiserBaseInfoService baseInfoService;

    /**
     * 同步素材到账号下
     */
    @Override
    public synchronized void uploadImage(String videoId, Long accountId, String accessToken) {
        try {
            List<JSONObject> imageList = materialImageInfoService.getUrlList(videoId);
            if (!Check.isNull(imageList)) {
                for (int i = 0; i < imageList.size(); i++) {
                    JSONObject imageInfo = imageList.get(i);
                    if (Check.isNull(imageInfo)) {
                        continue;
                    }

                    List<Long> accountList = baseInfoService.getAccountListByAccountId(accountId);
                    if (Check.isNull(accountList)) {
                        return;
                    }

                    for (int j = 0; j < accountList.size(); j++) {
                        Long imageAccountId = accountList.get(j);
                        if (Check.isNull(imageAccountId)) {
                            continue;
                        }
                        executorService.submit(new Runnable() {
                            @SneakyThrows
                            @Override
                            public void run() {
                                synchronized (this) {
                                    QueryWrapper<KuaiShouImageGet> imageQueryWrapper = new QueryWrapper<>();
                                    imageQueryWrapper.eq("account_id", imageAccountId);
                                    imageQueryWrapper.eq("signature", imageInfo.getString("signature"));
                                    List<KuaiShouImageGet> imageGetList = imageGetService.list(imageQueryWrapper);
                                    if (Check.isNull(imageGetList)) {
                                        Map<String, String> headerMap = new HashMap<>();
                                        JSONObject requestJson = new JSONObject();
                                        requestJson.put("advertiser_id", imageAccountId);
                                        headerMap.put("Access-Token", accessToken);
                                        headerMap.put("Content-Type", "multipart/form-data");

                                        requestJson.put("url", imageInfo.getString("imageUrl"));
                                        requestJson.put("signature", imageInfo.getString("signature"));
                                        requestJson.put("type", "2");
                                        requestJson.put("upload_type", "2");
                                        String requestUrl = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.IMAGE_UPLOAD;
                                        String result = exceptInfoForRestTemplate(requestUrl, 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)) {
                                                    String signature = dataJson.getString("signature");
                                                    String image_token = dataJson.getString("image_token");
                                                    KuaiShouImageGet imageGet = new KuaiShouImageGet();
                                                    imageGet.setId(imageAccountId + image_token);
                                                    imageGet.setAccountId(imageAccountId);
                                                    imageGet.setUrl(dataJson.getString("url"));
                                                    imageGet.setWidth(dataJson.getInteger("width"));
                                                    imageGet.setHeight(dataJson.getInteger("height"));
                                                    imageGet.setSize(dataJson.getInteger("size"));
                                                    imageGet.setFormat(dataJson.getString("format"));
                                                    Integer type = MaterialEnum.getTypeBySize(dataJson.getInteger("width"), dataJson.getInteger("height"));
                                                    if (!Check.isNull(type)) {
                                                        imageGet.setMaterialType(type);
                                                    }
                                                    String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
                                                    imageGet.setStatDate(DateUtils.parseDate(nowDate, "yyyy-MM-dd"));
                                                    imageGet.setSignature(signature);
                                                    imageGet.setImageToken(image_token);
                                                    imageGetService.saveOrUpdate(imageGet);
                                                }
                                                log.info("快手封面素材素材同步完成，accountId：{}，code：{},返回信息：{}", imageAccountId, imageInfo.getString("signature"), resultJson);
                                            } else {
                                                log.error("快手同步封面素材失败，返回信息：{}，请求参数：{}", resultJson, requestJson);
                                            }
                                        }
                                    }

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


    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));
                    }
                }
                SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
                requestFactory.setConnectTimeout(1000 * 500);// 设置超时
                requestFactory.setReadTimeout(1000 * 500);
                RestTemplate rest = new RestTemplate(requestFactory);
                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;
    }


}
