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


import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IProjectService;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.Enums.CampaignTypeEnum;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Api(tags = "快手-批量工具")
@RestController
@RequestMapping("/kuaishou/crossAccount")
public class CrossAccountBatchController {
    @Autowired
    private IProjectService projectService;

    @Autowired
    private ICtopOauthTokenService oauthTokenService;

    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;
    @Autowired
    private IUserAllocationService userAllocationService;


    /**
     * 批量创建广告计划
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchCampaignCreate")
    public Result<JSONArray> campaignCreate(@RequestBody JSONObject requestJson) {
        Result<JSONArray> result = new Result<>();
        try {
            System.err.println(requestJson);
            JSONArray accountArr = requestJson.getJSONArray("accountArr");
            if (Check.isNull(accountArr)) {
                throw new Exception("请选择需要创建的账户");
            }
            JSONArray returnArr = new JSONArray();

            for (int i = 0; i < accountArr.size(); i++) {
                Long accountId = accountArr.getLong(i);
                CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
                if (Check.isNull(oauthToken)) {
                    throw new Exception("未获取到账户信息");
                }

                JSONObject returnJson = new JSONObject();
                returnJson.put("accountId", accountId);
                JSONObject campaignJson = new JSONObject();
                campaignJson.put("day_budget", requestJson.getLong("dayBudget"));
                Integer nameType = requestJson.getInteger("nameType");
                Integer type = requestJson.getInteger("type");
                campaignJson.put("type", type);
                if (!Check.isNull(requestJson.getLong("dayBudget"))) {
                    campaignJson.put("day_budget", requestJson.getLong("dayBudget"));
                }

                if (!Check.isNull(requestJson.getJSONArray("dayBudgetSchedule"))) {
                    campaignJson.put("day_budget_schedule", requestJson.getJSONArray("dayBudgetSchedule"));
                }

                JSONArray campaignNames = new JSONArray();
                if (nameType == 0) { // 0 为统一命名  1 为分别命名
                    //    Integer startNum = requestJson.getInteger("startNum");
                    Integer createTotal = requestJson.getInteger("createTotal");
                    String campaignName = requestJson.getString("campaignName");
                    for (int j = 0; j < createTotal; j++) {
                        if (campaignName.contains("{{数值}}")) {
                            String name = getName(campaignName, accountId, j, type);
                            campaignNames.add(name);
                        } else {
                            String name = null;
                            if (createTotal == 1) {
                                name = getName(campaignName, accountId, null, type);
                            } else {
                                name = getName(campaignName + "_" + j, accountId, null, type);
                            }
                            campaignNames.add(name);
                        }
                    }
                } else if (nameType == 1) { // "分别命名"
                    JSONArray nameArr = requestJson.getJSONArray("nameArr");
                    for (int j = 0; j < nameArr.size(); j++) {
                        JSONObject nameJson = nameArr.getJSONObject(j);
                        if (nameJson.getLong("accountId").equals(accountId)) {
                            campaignNames = nameJson.getJSONArray("campaignNames");
                        }
                    }
                }
                if (!Check.isNull(campaignNames)) {
                    JSONArray returnCampaigns = new JSONArray();
                    for (int j = 0; j < campaignNames.size(); j++) {
                        JSONObject returnCampaignJson = new JSONObject();
                        String campaignName = (String) campaignNames.get(j);
                        campaignJson.put("campaign_name", campaignName);
                        Map<String, Object> campaignMap = kuaishouInterfaceService.campaignCreate(oauthToken.getAccessToken(), accountId, campaignJson);
                        if ((Integer) campaignMap.get("code") == 0) {
                            returnCampaignJson.put("code", 0);
                            returnCampaignJson.put("campaignId", campaignMap.get("campaignId"));
                            returnCampaignJson.put("campaignName", campaignName);
                            returnCampaignJson.put("type", type);
                            returnCampaignJson.put("message", campaignMap.get("message"));
                        } else {
                            returnCampaignJson.put("code", -1);
                            returnCampaignJson.put("campaignName", campaignName);
                            returnCampaignJson.put("message", campaignMap.get("message"));
                        }
                        returnCampaigns.add(returnCampaignJson);

                    }
                    returnJson.put("createDetail", returnCampaigns);

                }
                returnArr.add(returnJson);
            }
            result.setSuccess(true);
            System.err.println(returnArr);
            result.setResult(returnArr);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());

        }
        return result;

    }


    /**
     * 获取账户授权名称
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/getAuthName")
    public Result<JSONArray> getAuthName(@RequestBody JSONObject requestJson) {
        Result<JSONArray> result = new Result<>();
        try {
            JSONArray accountArr = requestJson.getJSONArray("accountArr");
            if (Check.isNull(accountArr)) {
                throw new Exception("请传入账户id");
            }
            JSONArray returnArr = new JSONArray();
            for (int i = 0; i < accountArr.size(); i++) {
                Long accountId = accountArr.getLong(i);
                UserAllocation userAllocation = userAllocationService.getByAccountId(accountId);
                if (!Check.isNull(userAllocation)) {
                    JSONObject returnJson = new JSONObject();
                    returnJson.put("accountId", accountId);
                    returnJson.put("authName", userAllocation.getAuthName());
                    returnArr.add(returnJson);
                }
            }
            result.setSuccess(true);
            result.setResult(returnArr);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());

        }
        return result;

    }





    /**
     * 批量创建广告组
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUnitCreate")
    public Result<JSONArray> batchUnitCreate(@RequestBody JSONObject requestJson) {
        Result<JSONArray> result = new Result<>();
        try {
            System.err.println(requestJson);
            JSONArray accountArr = requestJson.getJSONArray("accountArr");
            if (Check.isNull(accountArr)) {
                throw new Exception("请选择需要创建的账户");
            }
            JSONArray returnArr = new JSONArray();

            for (int i = 0; i < accountArr.size(); i++) {
                Long accountId = accountArr.getLong(i);
                CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
                if (Check.isNull(oauthToken)) {
                    throw new Exception("未获取到账户信息");
                }

                JSONObject returnJson = new JSONObject();
                returnJson.put("accountId", accountId);
                JSONObject campaignJson = new JSONObject();
                campaignJson.put("day_budget", requestJson.getLong("dayBudget"));
                Integer nameType = requestJson.getInteger("nameType");
                Integer type = requestJson.getInteger("type");
                campaignJson.put("type", type);
                if (!Check.isNull(requestJson.getLong("dayBudget"))) {
                    campaignJson.put("day_budget", requestJson.getLong("dayBudget"));
                }

                if (!Check.isNull(requestJson.getJSONArray("dayBudgetSchedule"))) {
                    campaignJson.put("day_budget_schedule", requestJson.getJSONArray("dayBudgetSchedule"));
                }

                JSONArray campaignNames = new JSONArray();
                if (nameType == 0) { // 0 为统一命名  1 为分别命名
                    //    Integer startNum = requestJson.getInteger("startNum");
                    Integer createTotal = requestJson.getInteger("createTotal");
                    String campaignName = requestJson.getString("campaignName");
                    for (int j = 0; j < createTotal; j++) {
                        if (campaignName.contains("{{数值}}")) {
                            String name = getName(campaignName, accountId, j, type);
                            campaignNames.add(name);
                        } else {
                            String name = null;
                            if (createTotal == 1) {
                                name = getName(campaignName, accountId, null, type);
                            } else {
                                name = getName(campaignName + "_" + j, accountId, null, type);
                            }
                            campaignNames.add(name);
                        }
                    }
                } else if (nameType == 1) { // "分别命名"
                    JSONArray nameArr = requestJson.getJSONArray("nameArr");
                    for (int j = 0; j < nameArr.size(); j++) {
                        JSONObject nameJson = nameArr.getJSONObject(j);
                        if (nameJson.getLong("accountId").equals(accountId)) {
                            campaignNames = nameJson.getJSONArray("campaignNames");
                        }
                    }
                }
                if (!Check.isNull(campaignNames)) {
                    JSONArray returnCampaigns = new JSONArray();
                    for (int j = 0; j < campaignNames.size(); j++) {
                        JSONObject returnCampaignJson = new JSONObject();
                        String campaignName = (String) campaignNames.get(j);
                        campaignJson.put("campaign_name", campaignName);
                        Map<String, Object> campaignMap = kuaishouInterfaceService.campaignCreate(oauthToken.getAccessToken(), accountId, campaignJson);
                        if ((Integer) campaignMap.get("code") == 0) {
                            returnCampaignJson.put("code", 0);
                            returnCampaignJson.put("campaignId", campaignMap.get("campaignId"));
                            returnCampaignJson.put("campaignName", campaignName);
                            returnCampaignJson.put("type", type);
                            returnCampaignJson.put("message", campaignMap.get("message"));
                        } else {
                            returnCampaignJson.put("code", -1);
                            returnCampaignJson.put("campaignName", campaignName);
                            returnCampaignJson.put("message", campaignMap.get("message"));
                        }
                        returnCampaigns.add(returnCampaignJson);

                    }
                    returnJson.put("createDetail", returnCampaigns);

                }
                returnArr.add(returnJson);
            }
            result.setSuccess(true);
            System.err.println(returnArr);
            result.setResult(returnArr);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());

        }
        return result;

    }










    /**
     * @param content   计划名称
     * @param accountId 账户id
     * @param num       数值数
     * @param type      计划类型
     * @return
     */
    private String getName(String content, Long accountId, Integer num, Integer type) {
        String reg = "\\{\\{(.+?)\\}\\}";
        List<String> params = getParams(reg, content);
        if (Check.isNull(params)) {
            return content;
        }


        Map<String, String> data = new HashMap<>();
        for (int i = 0; i < params.size(); i++) {
            String regName = params.get(i);
            if ("项目名称".equals(regName)) {
                String projectName = projectService.getNameByAccountId(accountId);
                data.put(regName, projectName);
            }

            if ("日期".equals(regName)) {
                data.put(regName, DateUtils.getNowDate("yyyy-MM-dd"));
            }

            if ("计划类型".equals(regName)) {
                data.put(regName, CampaignTypeEnum.getNameByType(type));
            }

            if ("数值".equals(regName)) {
                data.put(regName, String.valueOf(num));
            }

        }
        String text = parse(reg, content, data);
        return text;
    }


    public static String parse(String pattern, String content, Map<String, String> data) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(content);

        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String key = m.group(1);
            String value = data.get(key);
            m.appendReplacement(sb, value == null ? "" : value);
        }
        m.appendTail(sb);
        return sb.toString();
    }

    /**
     * 根据正则表达式获取文本中的变量名列表
     *
     * @param pattern
     * @param content
     * @return
     */
    public static List<String> getParams(String pattern, String content) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(content);

        List<String> result = new ArrayList<String>();
        while (m.find()) {
            result.add(m.group(1));
        }
        return result;
    }

    /**
     * 根据正则表达式将文本中的变量使用实际的数据替换成无变量的文本
     *
     * @param pattern
     * @param content
     * @param data
     * @return
     */


}
