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.ICrossAccountBatchService;
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;
    @Autowired
    private ICrossAccountBatchService crossAccountBatchService;

    /**
     * 批量创建广告计划
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchCampaignCreate")
    public Result<JSONArray> campaignCreate(@RequestBody JSONObject requestJson) {
        Result<JSONArray> result = new Result<>();
        try {
            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 = "/crossAccountUnitCreate")
    public Result<JSONArray> batchUnitCreate(@RequestBody JSONObject requestJson) {
        System.err.println(requestJson);
        Result<JSONArray> result = new Result<>();
        try {

            if (Check.isNull(requestJson)) {
                throw new Exception("参数不能为空");
            }
            JSONArray accountArr = requestJson.getJSONArray("accountArr");
            if (Check.isNull(accountArr)) {
                throw new Exception("accountArr节点不能为空");
            }

            JSONArray createUnitArr = new JSONArray();
            for (int i = 0; i < accountArr.size(); i++) {
                JSONObject accountJson = accountArr.getJSONObject(i);
                if (Check.isNull(accountJson)) {
                    continue;
                }
                Long accountId = accountJson.getLong("accountId");
                if (Check.isNull(accountId)) {
                    log.error("账户id不能为空");
                    continue;
                }
                CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
                if (Check.isNull(oauthToken)) {
                    log.error("未获取到授权信息");
                    continue;
                }
                Integer campaignAgreement = accountJson.getInteger("campaignAgreement");  //判断是否计划相同   0为相同取值campaignOne   1不同取值campaignList
                if (campaignAgreement == 0) { // 计划下组相同
                    JSONObject campaignOne = accountJson.getJSONObject("campaignOne");
                    if (Check.isNull(campaignOne)) {
                        continue;
                    }
                    createUnitArr = crossAccountBatchService.assembleUnitJson(oauthToken, createUnitArr, campaignOne);

                } else if (campaignAgreement == 1) { // 计划下组不同
                    JSONArray campaignList = accountJson.getJSONArray("campaignList");
                    if (Check.isNull(campaignList)) {
                        continue;
                    }
                    createUnitArr = crossAccountBatchService.assembleUnitArray(oauthToken, createUnitArr, campaignList);
                }
            }
            System.err.println("组装数据：" + createUnitArr);
            JSONArray returnArray = crossAccountBatchService.createUnit(createUnitArr);
            System.err.println(returnArray);
            result.setSuccess(true);
            result.setResult(returnArray);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(true);
            result.setMessage(e.getMessage());
        }
        return result;

    }


    @PostMapping(value = "/crossAccountCreativeCreate")
    public Result<JSONArray> crossAccountCreativeCreate(@RequestBody JSONObject requestJson) {
        Result<JSONArray> result = new Result<>();
        try {
            System.err.println(requestJson);

            if (Check.isNull(requestJson)) {
                throw new Exception("参数不能为空");
            }
            JSONArray accountArr = requestJson.getJSONArray("accountArr");
            if (Check.isNull(accountArr)) {
                throw new Exception("accountArr节点不能为空");
            }
            JSONArray creativeArray = new JSONArray();
            for (int i = 0; i < accountArr.size(); i++) {
                JSONObject accountJson = accountArr.getJSONObject(i);
                creativeArray = crossAccountBatchService.assembleCreativeJson(creativeArray, accountJson);
            }
            System.err.println("组装数据：" + creativeArray);
            JSONArray returnArray = crossAccountBatchService.createCreative(creativeArray);
            System.err.println(returnArray);
            result.setSuccess(true);
            result.setResult(returnArray);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(true);
            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
     */


}
