package cn.com.ctop.toutiao.modules.tool.controller;

import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.toutiao.modules.tool.service.IByteDanceConvertToolService;
import cn.com.ctop.toutiao.modules.tool.service.IByteDanceQueryMaterialInfoService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/ctop/queryTool")
public class ByteDanceQueryToolController {

    @Autowired
    private IByteDanceConvertToolService byteDanceConvertToolService;

    @Autowired
    private IByteDanceQueryMaterialInfoService byteDanceQueryMaterialInfoService;

    @Autowired
    ICtopOauthTokenService ctopOauthTokenService;

    /**
     *  查询转化目标接口
     */
    @PostMapping(value="/queryConvert")
    public Result<Map<String,Object>> queryConvertResult(Long accountId, String landingType, String appType,
                                                         String downloadType,String externalUrl,String toutiaoPackage,
                                                         String downloadUrl){

        Result<Map<String,Object>> result=new Result<>();
        Map<String, Object> convertQueryMap = byteDanceConvertToolService.queryAdConvert(ctopOauthTokenService.getTokenByAccountId(accountId), accountId,
                landingType, appType, downloadType, externalUrl, toutiaoPackage, downloadUrl);
        if(!convertQueryMap.get("code").equals(0)){
            result.error500("查询转化目标结果失败");
        }else{
            result.setSuccess(true);
            result.setResult(ConvertResultHandle((List)((JSONObject)convertQueryMap.get("data")).get("list")));
        }
        return result;
    }

    @PostMapping(value="/queryVideoInfo")
    public Result<JSONArray> queryVideoInfo(@RequestBody JSONObject requestBody){
        Long accountId=requestBody.getLong("accountId");
        JSONArray signatures=requestBody.getJSONArray("signatures");
        Result<JSONArray> result=new Result<>();
        JSONObject jsonObject = byteDanceQueryMaterialInfoService.queryVideoInfo(ctopOauthTokenService.getTokenByAccountId(accountId),accountId,signatures);
        if(jsonObject.getInteger("code")!=0){
            result.error500("视频素材信息查询失败");
        }else{
            result.setSuccess(true);
            result.setResult(jsonObject.getJSONObject("data").getJSONArray("list"));
        }
        return result;
    }
    @PostMapping(value="/queryImageInfo")
    public Result<JSONArray> queryImageInfo(@RequestBody JSONObject requestBody){
        Long accountId=requestBody.getLong("accountId");
        JSONArray signatures=requestBody.getJSONArray("signatures");
        Result<JSONArray> result=new Result<>();
        JSONObject jsonObject = byteDanceQueryMaterialInfoService.queryImageInfo(ctopOauthTokenService.getTokenByAccountId(accountId),accountId,signatures);
        if(jsonObject.getInteger("code")!=0){
            result.error500("图片素材信息查询失败");
        }else{
            result.setSuccess(true);
            result.setResult(jsonObject.getJSONObject("data").getJSONArray("list"));
        }
        return result;
    }

    private Map<String,Object> ConvertResultHandle(List convertResult){
        Map<String,Object> resultMap=new HashMap<>();
        if(convertResult.isEmpty()){
            resultMap.put("data",convertResult);
        }else{
            List resultList=new ArrayList();
            convertResult.forEach(it->{
                if(((JSONObject)it).get("external_actions")!=null){
                    JSONObject jsonObject=(JSONObject)it;
                    Map<String,Object> temp=new HashMap<>();
                    temp.put("convert_type",jsonObject.get("convert_type"));
                    temp.put("name",getName((jsonObject.getString("convert_type"))));
                    if(jsonObject.getJSONArray("external_actions")!=null){
                        List actionList=new ArrayList();
                        jsonObject.getJSONArray("external_actions").forEach(action->{
                            Map<String,Object> actionMap=new HashMap<>();
                            actionMap.put("external_action",((JSONObject)action).getString("external_action"));
                            if(((JSONObject)action).get("convert_id")==null){
                                actionMap.put("convertId",getConvertIdByExternalAction(((JSONObject)action).getString("external_action")));
                            }else {
                                actionMap.put("convertId",(((JSONObject)action).get("convert_id")));
                            }
                            if(((JSONObject)action).get("deep_external_actions")!=null){
                                actionMap.put("deep_external_action",((JSONObject)((JSONObject)action).getJSONArray("deep_external_actions").get(0)).getString("deep_external_action"));
                            }else{
                                actionMap.put("deep_external_action",null);
                            }
                            actionMap.put("external_name",((JSONObject)action).get("external_name"));
                            actionList.add(actionMap);
                        });
                        temp.put("external_actions",actionList);
                    }
                    resultList.add(temp);
                }
                resultMap.put("data",resultList);
            });
        }
        return resultMap;
    }
    private String getName(String convertType){
        String convertName="";
        switch (convertType) {
            case "AD_CONVERT_SOURCE_TYPE_INTERNAL":
                convertName = "线索通";
                break;
            case "AD_CONVERT_SOURCE_TYPE_JS":
                convertName = "代码检测转化";
                break;
            case "AD_CONVERT_SOURCE_TYPE_XPATH":
                convertName = "路径转化";
                break;
            case "AD_CONVERT_SOURCE_TYPE_APP_DOWNLOAD":
                convertName = "应用下载API";
                break;
            case "AD_CONVERT_SOURCE_TYPE_H5_API":
                convertName = "落地页API（H5）";
                break;
            case "AD_CONVERT_SOURCE_TYPE_SDK":
                convertName = "应用下载SDK";
                break;
            case "AD_CONVERT_SOURCE_TYPE_OPEN_URL":
                convertName = "应用直达API（应用直达链接）";
                break;
            case "AD_CONVERT_SOURCE_TYPE_NORMAL_APP_DOWNLOAD":
                convertName = "普通应用下载";
                break;
            case "AD_CONVERT_SOURCE_TYPE_CONFIG":
                convertName = "无转化跟踪";
                break;
            case "AD_CONVERT_SOURCE_TYPE_CPS_GAME":
                convertName = "内部游戏cps应用下载";
                break;
            case "AD_CONVERT_SOURCE_TYPE_APP_API_TEMAI":
                convertName = "落地页API(支持特卖)";
                break;
        }
        return convertName;
    }

    private int getConvertIdByExternalAction(String externalAction){
        int result=0;
        switch (externalAction) {
            case "AD_CONVERT_TYPE_DOWNLOAD_FINISH":
                result = 4;
                break;
            case "AD_CONVERT_TYPE_BUTTON":
                result = 5;
                break;
            case "AD_CONVERT_TYPE_DOWNLOAD_START":
                result = 9;
                break;
            case "AD_CONVERT_TYPE_INSTALL_FINISH":
                result = 15;
                break;
            case "AD_CONVERT_TYPE_REDIRECT":
                result = 95;
                break;
        }
        return result;
    }
}
