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


import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.MaterialInfo;
import cn.com.ctop.common.module.mapper.MaterialInfoMapper;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.BigDecimalUtil;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.RandomUtil;
import cn.com.ctop.kuaishou.modules.batch.entity.*;
import cn.com.ctop.kuaishou.modules.batch.entity.vo.ConvertVo;
import cn.com.ctop.kuaishou.modules.batch.entity.vo.SpendVo;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouCampaignMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouGroupMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouTargetingTagsMapper;
import cn.com.ctop.kuaishou.modules.batch.service.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "快手-批量工具")
@RestController
@RequestMapping("/kuaishou/batch")
public class BatchController {
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private IKuaishouInterfaceService iKuaishouInterfaceService;
    @Autowired
    private IBatchService batchService;
    @Autowired
    private IKuaiShouCampaignService kuaiShouCampaignService;
    @Autowired
    private IKuaiShouUpdateService updateService;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaiShouGroupService kuaiShouGroupService;
    @Autowired
    private IKuaiShouAppListService kuaiShouAppListService;
    @Autowired
    private KuaiShouTargetingTagsMapper targetingTagsMapper;
    @Autowired
    private IKuaiShouImageGetService kuaiShouImageGetService;
    @Autowired
    private IKuaiShouVideoGetService kuaiShouVideoGetService;
    @Autowired
    private MaterialInfoMapper materialInfoMapper;
    @Autowired
    private KuaiShouCampaignMapper campaignMapper;
    @Autowired
    private IKuaiShouActionBarTextService actionBarTextService;
    @Autowired
    private IKuaiShouDirectionalTemplateService kuaiShouDirectionalTemplateService;
    @Autowired
    private IKuaiShouCreativeService kuaiShouCreativeService;
    @Autowired
    private IKuaiShouAppInfoService appInfoService;
    @Autowired
    private IKuaiShouGroupTargetService targetService;
    @Autowired
    private IKuaiShouRegionListParentService regionListParentService;
    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IKuaiShouVideoGetService videoGetService;
    @Autowired
    private IKuaishouPopulationService populationService;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private ISyncPullMaterialService syncPullMaterialService;
    @Autowired
    private IKuaiShouAdvertiserBaseInfoService KuaiShouAdvertiserBaseInfoService;


    /**
     * 获取花费信息
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/spend")
    public Result<SpendVo> spend(Long accountId) {
        Result<SpendVo> result = new Result<>();
        try {

            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            SpendVo spendVo = new SpendVo();
            JSONObject fundJson = iKuaishouInterfaceService.fundGet(oauthToken);


            if (!Check.isNull(fundJson)) {
                spendVo.setBalance(fundJson.getBigDecimal("balance")); // 余额
            }
            BigDecimal cost = batchService.getCost(accountId);
            spendVo.setCost(cost);

            BigDecimal budget = batchService.getBudget(accountId);
            spendVo.setBudget(budget);
            result.setSuccess(true);
            result.setResult(spendVo);

            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
            String startDate = DateUtils.getAnotherDay("yyyy-MM-dd", nowDate, -1);
            String endDate = DateUtils.getAnotherDay("yyyy-MM-dd", nowDate, 1);


            iKuaishouInterfaceService.getCampaignList(oauthToken, new java.util.Date(), new java.util.Date());


            Thread thread = new Thread() {
                @Override
                public void run() {
                    iKuaishouInterfaceService.getAppList(oauthToken.getAccountId(), oauthToken.getAccessToken());
                }
            };
            thread.start();

            Thread thread1 = new Thread() {
                @Override
                public void run() {
                    iKuaishouInterfaceService.getPopulationList(accountId, oauthToken.getAccessToken());
                }
            };
            thread1.start();


            Thread thread2 = new Thread() {
                @Override
                public void run() {
                    // syncPullMaterialService.getSyncVideoList(accountId, nowDate, nowDate);
                    iKuaishouInterfaceService.getVideoList(oauthToken, nowDate, nowDate);

                }
            };
            thread2.start();

          /*  Thread thread3 = new Thread() {
                @Override
                public void run() {
                    iKuaishouInterfaceService.getSuZaoList(oauthToken.getAccessToken(), accountId, 1, nowDate, endDate);
                }
            };
            thread3.start();*/

            Thread thread4 = new Thread() {
                @Override
                public void run() {
                    kuaiShouGroupService.getGroupList(oauthToken.getAccessToken(), oauthToken.getAccountId());

                }
            };
            thread4.start();

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }

        return result;
    }


    /**
     * 获取广告计划列表
     *
     * @param kuaiShouCampaign
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/getCampaignList")
    public Result<IPage<KuaiShouCampaign>> getCampaignList(KuaiShouCampaign kuaiShouCampaign,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<KuaiShouCampaign>> result = new Result<>();
        String campaignName = kuaiShouCampaign.getCampaignName();
        kuaiShouCampaign.setCampaignName(null);
        if (!Check.isNull(kuaiShouCampaign.getCampaignId())) {
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(kuaiShouCampaign.getAccountId());
            iKuaishouInterfaceService.getCampaign(oauthToken.getAccessToken(), kuaiShouCampaign.getAccountId(), kuaiShouCampaign.getCampaignId());
        }
        QueryWrapper<KuaiShouCampaign> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouCampaign, req.getParameterMap());
        if (!Check.isNull(campaignName)) {
            queryWrapper.like("campaign_name", campaignName);
        }
        queryWrapper.orderByDesc("put_create_time");
        Page<KuaiShouCampaign> page = new Page<KuaiShouCampaign>(pageNo, pageSize);
        IPage<KuaiShouCampaign> pageList = kuaiShouCampaignService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 批量修改广告计划状态
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateStatus")
    public Result<JSONObject> batchUpdateStatus(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }
            Integer putStatus = requestJson.getInteger("putStatus");
            if (putStatus == null) {
                throw new Exception("请选择状态");
            }
            String userId = requestJson.getString("userId");
            JSONArray campaignIds = requestJson.getJSONArray("campaignIds");
            JSONArray failArr = new JSONArray();
            if (!Check.isNull(campaignIds)) {
                for (int i = 0; i < campaignIds.size(); i++) {
                    Long campaignId = campaignIds.getLong(i);
                    if (!Check.isNull(campaignId)) {
                        Map<String, Object> updateMap = updateService.updateCampaignStatus(token.getAccessToken(), accountId, campaignId, putStatus, userId);
                        if (!Check.isNull(updateMap)) {
                            Integer code = (Integer) updateMap.get("code");
                            if (code != 0) {
                                JSONObject failJson = new JSONObject();
                                failJson.put("message", updateMap.get("message"));
                                KuaiShouCampaign campaign = batchService.getCampaignInfo(accountId, campaignId);
                                if (!Check.isNull(campaign)) {
                                    failJson.put("campaignName", campaign.getCampaignName());
                                }
                                failArr.add(failJson);
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            json.put("totalCount", campaignIds.size());
            json.put("failCount", failArr.size());
            json.put("failInfo", failArr);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 批量修改广告计划预算
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateDayBudget")
    public Result<JSONObject> batchUpdateDayBudget(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }
            Long dayBudget = requestJson.getLong("dayBudget");
            if (Check.isNull(dayBudget)) {
                throw new Exception("预算信息为空");
            }
            String userId = requestJson.getString("userId");
            JSONArray campaignIds = requestJson.getJSONArray("campaignIds");
            JSONArray failArr = new JSONArray();
            if (!Check.isNull(campaignIds)) {
                for (int i = 0; i < campaignIds.size(); i++) {
                    Long campaignId = campaignIds.getLong(i);
                    if (!Check.isNull(campaignId)) {
                        Map<String, Object> updateMap = updateService.updateCampaign(token.getAccessToken(), accountId, campaignId, dayBudget, userId);
                        if (!Check.isNull(updateMap)) {
                            Integer code = (Integer) updateMap.get("code");
                            if (code != 0) {
                                JSONObject failJson = new JSONObject();
                                failJson.put("message", updateMap.get("message"));
                                KuaiShouCampaign campaign = batchService.getCampaignInfo(accountId, campaignId);
                                if (!Check.isNull(campaign)) {
                                    failJson.put("campaignName", campaign.getCampaignName());
                                }
                                failArr.add(failJson);
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            json.put("totalCount", campaignIds.size());
            json.put("failCount", failArr.size());
            json.put("failInfo", failArr);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 根据比例批量修改广告计划预算
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateDayBudgetByProportion")
    public Result<JSONObject> batchUpdateDayBudgetByProportion(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }
            BigDecimal proportion = requestJson.getBigDecimal("proportion");
            if (proportion.compareTo(new BigDecimal(0)) == 0) {
                throw new Exception("比例不能为0");
            }
            String userId = requestJson.getString("userId");
            JSONArray campaignIds = requestJson.getJSONArray("campaignIds");
            JSONArray failArr = new JSONArray();
            if (!Check.isNull(campaignIds)) {
                for (int i = 0; i < campaignIds.size(); i++) {
                    Long campaignId = campaignIds.getLong(i);
                    if (!Check.isNull(campaignId)) {
                        KuaiShouCampaign campaign = batchService.getCampaignInfo(accountId, campaignId);
                        if (!Check.isNull(campaign)) {
                            Long dayBudget = campaign.getDayBudget();
                            if (Check.isNull(dayBudget)) {
                                continue;
                            }
                            BigDecimal totalFee = new BigDecimal(dayBudget);
                            Long multiply = 0L;
                            if (proportion.compareTo(new BigDecimal(0)) == -1) {
                                BigDecimal absBigDecimal = BigDecimalUtil.absBigDecimal(proportion);
                                BigDecimal decimal = BigDecimalUtil.multiplyBigDecimal(totalFee, absBigDecimal);
                                multiply = (BigDecimalUtil.subtractBigDecimal(totalFee, decimal)).longValue();
                            } else if (proportion.compareTo(new BigDecimal(0)) == 1) {
                                multiply = (totalFee.multiply(proportion)).longValue();
                            }
                            Map<String, Object> updateMap = updateService.updateCampaign(token.getAccessToken(), accountId, campaignId, multiply, userId);
                            if (!Check.isNull(updateMap)) {
                                Integer code = (Integer) updateMap.get("code");
                                if (code != 0) {
                                    JSONObject failJson = new JSONObject();
                                    failJson.put("message", updateMap.get("message"));
                                    failJson.put("campaignName", campaign.getCampaignName());
                                    failArr.add(failJson);
                                }
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            json.put("totalCount", campaignIds.size());
            json.put("failCount", failArr.size());
            json.put("failInfo", failArr);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 查询广告组列表
     *
     * @param kuaiShouGroup
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/getUnitList")
    public Result<IPage<KuaiShouGroup>> getUnitList(KuaiShouGroup kuaiShouGroup,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        Result<IPage<KuaiShouGroup>> result = new Result<IPage<KuaiShouGroup>>();
        String unitName = kuaiShouGroup.getUnitName();
        kuaiShouGroup.setUnitName(null);
        QueryWrapper<KuaiShouGroup> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouGroup, req.getParameterMap());
        if (!Check.isNull(unitName)) {
            queryWrapper.like("unit_name", unitName);
        }
        queryWrapper.orderByDesc("group_create_time");
        Page<KuaiShouGroup> page = new Page<KuaiShouGroup>(pageNo, pageSize);
        IPage<KuaiShouGroup> pageList = kuaiShouGroupService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 获取区域列表
     *
     * @param
     * @return
     */
    @Autowired
    private IKuaiShouRegionListParentService kuaiShouRegionListParentService;

    @GetMapping(value = "/getRegion")
    public Result<List<KuaiShouRegionListParent>> getRegion(KuaiShouRegionListParent kuaiShouRegionListParent, HttpServletRequest req) {
        Result<List<KuaiShouRegionListParent>> result = new Result<>();
        try {
            QueryWrapper<KuaiShouRegionListParent> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouRegionListParent, req.getParameterMap());
            List<KuaiShouRegionListParent> pageList = kuaiShouRegionListParentService.list(queryWrapper);
            result.setSuccess(true);
            result.setResult(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);

        }
        return result;
    }


    /**
     * 创建广告计划
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/campaignCreate")
    public Result<Object> campaignCreate(@RequestBody JSONObject requestJson) {
        Result<Object> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            JSONObject campaignJson = new JSONObject();
            campaignJson.put("campaign_name", requestJson.getString("campaignName"));
            campaignJson.put("type", requestJson.getInteger("type"));
            campaignJson.put("day_budget", requestJson.getLong("dayBudget"));
            Map<String, Object> campaignMap = iKuaishouInterfaceService.campaignCreate(oauthToken.getAccessToken(), accountId, campaignJson);
            Integer code = (Integer) campaignMap.get("code");
            if (code != 0) {
                throw new Exception((String) campaignMap.get("message"));
            }
            result.setSuccess(true);
            result.setResult(campaignMap.get("campaignId"));
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());

        }
        return result;

    }


    /**
     * 获取应用列表
     */

    @GetMapping(value = "/getAppList")
    public Result<List<KuaiShouAppList>> getAppList(KuaiShouAppList kuaiShouAppList, HttpServletRequest req) {
        Result<List<KuaiShouAppList>> result = new Result<>();
        try {
            QueryWrapper<KuaiShouAppList> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouAppList, req.getParameterMap());
            queryWrapper.orderByDesc("return_time");
            List<KuaiShouAppList> appList = kuaiShouAppListService.list(queryWrapper);
            result.setSuccess(true);
            result.setResult(appList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }

        return result;
    }


    /**
     * 获取人群包
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/getPopulationList")
    public Result<List<KuaishouPopulation>> queryPageList(Long accountId) {
        Result<List<KuaishouPopulation>> result = new Result();
        QueryWrapper<KuaishouPopulation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("status", 4);
        queryWrapper.orderByDesc("put_time");
        List<KuaishouPopulation> list = populationService.list(queryWrapper);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }


    /**
     * 获取商业兴趣
     *
     * @param kuaiShouTargetingTags BUSINESS_INTEREST：商业兴趣
     *                              APP_INTEREST：APP行为
     *                              FANS_STAR：网红类别
     *                              INTEREST_VIDEO：兴趣视频
     * @param req
     * @return
     */
    @GetMapping(value = "/getTargetList")
    public Result<List<KuaiShouTargetingTags>> getTargetList(KuaiShouTargetingTags kuaiShouTargetingTags, HttpServletRequest req) {
        Result<List<KuaiShouTargetingTags>> result = new Result<>();
        try {
            QueryWrapper<KuaiShouTargetingTags> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouTargetingTags, req.getParameterMap());
            queryWrapper.orderByAsc("tag_id");
            List<KuaiShouTargetingTags> targetingTagList = targetingTagsMapper.selectList(queryWrapper);
            result.setSuccess(true);
            result.setResult(targetingTagList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 获取可选的深度类型
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/getIsActivate")
    public Result<JSONObject> getIsActivate(Long accountId) {
        Result result = new Result<JSONObject>();
        try {
            CtopOauthToken token = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("未获取授权信息");
            }
            JSONObject deepConversionJson = iKuaishouInterfaceService.getDeepConversionInfosV2(accountId, token.getAccessToken());
            if (Check.isNull(deepConversionJson)) {
                throw new Exception("深度类型数据返回为空");
            }
            result.setSuccess(true);
            result.setResult(deepConversionJson);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }

        return result;

    }


    /**
     * 获取app列表
     *
     * @param accountId
     * @param appName
     * @return
     */
    @GetMapping(value = "/getAppSearch")
    public Result<JSONObject> getAppSearch(Long accountId, String appName) {
        Result result = new Result<JSONObject>();
        try {
            CtopOauthToken token = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("未获取授权信息");
            }
            JSONArray appArray = iKuaishouInterfaceService.getAppSearch(accountId, token.getAccessToken(), appName);
            result.setSuccess(true);
            result.setResult(appArray);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }

        return result;
    }

    /**
     * 获取项目最高出价
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/getProjectMaxBid")
    public Result<BigDecimal> getProjectMaxBid(Long accountId) {
        Result<BigDecimal> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("请传入accountId");
            }
            BigDecimal maxBid = batchService.getProjectMaxBid(accountId);
            result.setSuccess(true);
            result.setResult(maxBid);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }

        return result;

    }


    /**
     * 获取项目最高出价
     *
     * @param campaignId
     * @return
     */
    @GetMapping(value = "/checkUnitName")
    public Result<Boolean> checkUnitName(Long campaignId, String unitName) {
        Result<Boolean> result = new Result<>();
        try {
            if (Check.isNull(campaignId)) {
                throw new Exception("请传入广告计划id");
            }
            if (Check.isNull(unitName)) {
                throw new Exception("请传入广告组名称");
            }
            Boolean checkUnitName = batchService.checkUnitName(campaignId, unitName);
            result.setSuccess(true);
            result.setResult(checkUnitName);
            if (!checkUnitName) {
                result.setMessage("广告组名称该计划下已存在");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }

        return result;
    }


    /**
     * 批量创建广告组
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/createUnit")
    public Result<JSONObject> createUnit(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参为空");
            }
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }

            JSONObject unitJson = batchService.createUnit(requestJson, token);
            result.setSuccess(true);
            result.setResult(unitJson);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }

        return result;
    }


    /**
     * 获取 创意列表
     *
     * @param kuaiShouCreative
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/getCreativeList")
    public Result<IPage<KuaiShouCreative>> getCreativeList(KuaiShouCreative kuaiShouCreative, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<KuaiShouCreative>> result = new Result<>();
        String creativeName = kuaiShouCreative.getCreativeName();
        kuaiShouCreative.setCreativeName(null);
        QueryWrapper<KuaiShouCreative> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouCreative, req.getParameterMap());
        if (!Check.isNull(creativeName)) {
            queryWrapper.like("creative_name", creativeName);
        }
        queryWrapper.orderByDesc("creative_create_time");
        Page<KuaiShouCreative> page = new Page<>(pageNo, pageSize);
        IPage<KuaiShouCreative> creativeList = kuaiShouCreativeService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(creativeList);
        return result;
    }


    /**
     * 批量修改广告组预算
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateUnitBudget")
    public Result<JSONObject> batchUpdateUnitBudget(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }
            Long dayBudget = requestJson.getLong("dayBudget");
            if (Check.isNull(dayBudget)) {
                throw new Exception("预算信息为空");
            }
            String userId = requestJson.getString("userId");
            JSONArray unitIds = requestJson.getJSONArray("unitIds");
            JSONArray failArr = new JSONArray();
            if (!Check.isNull(unitIds)) {
                for (int i = 0; i < unitIds.size(); i++) {
                    Long unitId = unitIds.getLong(i);
                    if (!Check.isNull(unitId)) {
                        Map<String, Object> updateMap = updateService.updateUnitDayBudget(token.getAccessToken(), accountId, unitId, dayBudget, userId);
                        if (!Check.isNull(updateMap)) {
                            Integer code = (Integer) updateMap.get("code");
                            if (code != 0) {
                                JSONObject failJson = new JSONObject();
                                failJson.put("message", updateMap.get("message"));
                                KuaiShouGroup group = batchService.getUnitInfo(accountId, unitId);
                                if (!Check.isNull(group)) {
                                    failJson.put("unitName", group.getUnitName());
                                }
                                failArr.add(failJson);
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            json.put("totalCount", unitIds.size());
            json.put("failCount", failArr.size());
            json.put("failInfo", failArr);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 根据比例批量修改广告组预算
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateUnitBudgetByProportion")
    public Result<JSONObject> batchUpdateUnitBudgetByProportion(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }
            BigDecimal proportion = requestJson.getBigDecimal("proportion");
            if (proportion.compareTo(new BigDecimal(0)) == 0) {
                throw new Exception("比例不能为0");
            }
            String userId = requestJson.getString("userId");
            JSONArray unitIds = requestJson.getJSONArray("unitIds");
            JSONArray failArr = new JSONArray();
            if (!Check.isNull(unitIds)) {
                for (int i = 0; i < unitIds.size(); i++) {
                    Long unitId = unitIds.getLong(i);
                    if (!Check.isNull(unitId)) {
                        KuaiShouGroup group = batchService.getUnitInfo(accountId, unitId);
                        if (!Check.isNull(group)) {
                            Long dayBudget = group.getDayBudget();
                            if (Check.isNull(dayBudget)) {
                                continue;
                            }
                            BigDecimal totalFee = new BigDecimal(dayBudget);

                            Long multiply = 0L;
                            if (proportion.compareTo(new BigDecimal(0)) == -1) {
                                BigDecimal absBigDecimal = BigDecimalUtil.absBigDecimal(proportion);
                                BigDecimal decimal = BigDecimalUtil.multiplyBigDecimal(totalFee, absBigDecimal);
                                multiply = (BigDecimalUtil.subtractBigDecimal(totalFee, decimal)).longValue();
                            } else if (proportion.compareTo(new BigDecimal(0)) == 1) {
                                multiply = (totalFee.multiply(proportion)).longValue();
                            }

                            Map<String, Object> updateMap = updateService.updateUnitDayBudget(token.getAccessToken(), accountId, unitId, multiply, userId);
                            if (!Check.isNull(updateMap)) {
                                Integer code = (Integer) updateMap.get("code");
                                if (code != 0) {
                                    JSONObject failJson = new JSONObject();
                                    failJson.put("message", updateMap.get("message"));
                                    if (!Check.isNull(group)) {
                                        failJson.put("unitName", group.getUnitName());
                                    }
                                    failArr.add(failJson);
                                }
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            json.put("totalCount", unitIds.size());
            json.put("failCount", failArr.size());
            json.put("failInfo", failArr);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 批量修改广告组状态
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateUnitStatus")
    public Result<JSONObject> batchUpdateUnitStatus(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }
            Integer putStatus = requestJson.getInteger("putStatus");
            if (putStatus == null) {
                throw new Exception("请选择状态");
            }
            String userId = requestJson.getString("userId");
            JSONArray unitIds = requestJson.getJSONArray("unitIds");
            JSONArray failArr = new JSONArray();
            if (!Check.isNull(unitIds)) {
                for (int i = 0; i < unitIds.size(); i++) {
                    Long unitId = unitIds.getLong(i);
                    if (!Check.isNull(unitId)) {
                        Map<String, Object> updateMap = updateService.updateUnitStatus(token.getAccessToken(), accountId, unitId, putStatus, userId);
                        if (!Check.isNull(updateMap)) {
                            Integer code = (Integer) updateMap.get("code");
                            if (code != 0) {
                                JSONObject failJson = new JSONObject();
                                failJson.put("message", updateMap.get("message"));
                                KuaiShouGroup group = batchService.getUnitInfo(accountId, unitId);
                                if (!Check.isNull(group)) {
                                    failJson.put("campaignName", group.getUnitName());
                                }
                                failArr.add(failJson);
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            json.put("totalCount", unitIds.size());
            json.put("failCount", failArr.size());
            json.put("failInfo", failArr);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 根据比列批量修改广告组出价
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateUnitBidByProportion")
    public Result<JSONObject> batchUpdateUnitBidByProportion(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }
            BigDecimal proportion = requestJson.getBigDecimal("proportion");
            if (proportion.compareTo(new BigDecimal(0)) == 0) {
                throw new Exception("比例不能为0");
            }
            String userId = requestJson.getString("userId");
            JSONArray unitIds = requestJson.getJSONArray("unitIds");
            JSONArray failArr = new JSONArray();
            if (!Check.isNull(unitIds)) {
                for (int i = 0; i < unitIds.size(); i++) {
                    Long unitId = unitIds.getLong(i);
                    if (!Check.isNull(unitId)) {
                        KuaiShouGroup group = batchService.getUnitInfo(accountId, unitId);
                        if (Check.isNull(group)) {
                            continue;
                        }
                        Long groupBid;
                        Long bid = group.getBid();
                        Long cpaBid = group.getCpaBid();
                        if (!Check.isNull(cpaBid)) {
                            groupBid = cpaBid;
                        } else {
                            groupBid = bid;
                        }
                        BigDecimal totalFee = new BigDecimal(groupBid);
                        Long multiply = 0L;
                        if (proportion.compareTo(new BigDecimal(0)) == -1) {
                            BigDecimal absBigDecimal = BigDecimalUtil.absBigDecimal(proportion);
                            BigDecimal decimal = BigDecimalUtil.multiplyBigDecimal(totalFee, absBigDecimal);
                            multiply = (BigDecimalUtil.subtractBigDecimal(totalFee, decimal)).longValue();
                        } else if (proportion.compareTo(new BigDecimal(0)) == 1) {
                            multiply = (totalFee.multiply(proportion)).longValue();
                        }
                        Map<String, Object> updateMap = updateService.updateUnitBid(token.getAccessToken(), accountId, unitId, multiply, userId);
                        if (!Check.isNull(updateMap)) {
                            Integer code = (Integer) updateMap.get("code");
                            if (code == 0) {
                                kuaiShouGroupService.getGroupByUnitId(token.getAccessToken(), accountId, unitId);
                            } else {
                                JSONObject failJson = new JSONObject();
                                failJson.put("message", updateMap.get("message"));
                                if (!Check.isNull(group)) {
                                    failJson.put("unitName", group.getUnitName());
                                }
                                failArr.add(failJson);
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            json.put("totalCount", unitIds.size());
            json.put("failCount", failArr.size());
            json.put("failInfo", failArr);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 批量修改广告组状态
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateUnitBid")
    public Result<JSONObject> batchUpdateUnitBid(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }
            Long bid = requestJson.getLong("bid");
            if (bid == null) {
                throw new Exception("请输入出价");
            }

            Long deepConversionBid = requestJson.getLong("deepConversionBid");
            String userId = requestJson.getString("userId");
            JSONArray unitIds = requestJson.getJSONArray("unitIds");
            JSONArray failArr = new JSONArray();
            if (!Check.isNull(unitIds)) {
                for (int i = 0; i < unitIds.size(); i++) {
                    Long unitId = unitIds.getLong(i);
                    if (!Check.isNull(unitId)) {
                        KuaiShouGroup group = batchService.getUnitInfo(accountId, unitId);

                        Map<String, Object> updateMap = updateService.updateUnitBid(token.getAccessToken(), accountId, unitId, bid, userId);
                        if (!Check.isNull(deepConversionBid) && deepConversionBid != 0) {
                            Long updateDeepConversionBid = group.getDeepConversionBid();
                            if (!Check.isNull(updateDeepConversionBid) && updateDeepConversionBid != 0) {
                                Map<String, Object> updateDeepMap = updateService.updateUnitDeepConversionBid(token.getAccessToken(), accountId, unitId, deepConversionBid, userId);
                            }
                        }
                        kuaiShouGroupService.getGroupByUnitId(token.getAccessToken(), accountId, unitId);
                        if (!Check.isNull(updateMap)) {
                            Integer code = (Integer) updateMap.get("code");
                            if (code != 0) {
                                JSONObject failJson = new JSONObject();
                                failJson.put("message", updateMap.get("message"));
                                if (!Check.isNull(group)) {
                                    failJson.put("unitName", group.getUnitName());
                                }
                                failArr.add(failJson);
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            json.put("totalCount", unitIds.size());
            json.put("failCount", failArr.size());
            json.put("failInfo", failArr);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 获取封面列表
     *
     * @param kuaiShouImageGet
     * @param req
     * @return
     */
    @GetMapping(value = "/getImageList")
    public Result<IPage<KuaiShouImageGet>> getImageList(KuaiShouImageGet kuaiShouImageGet, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<KuaiShouImageGet>> result = new Result<>();
        try {
            QueryWrapper<KuaiShouImageGet> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouImageGet, req.getParameterMap());
            queryWrapper.orderByDesc("stat_date");
            Page<KuaiShouImageGet> page = new Page<>(pageNo, pageSize);
            IPage<KuaiShouImageGet> pageList = kuaiShouImageGetService.page(page, queryWrapper);
            result.setSuccess(true);
            result.setResult(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 获取视频列表
     *
     * @param kuaiShouVideoGet
     * @param req
     * @return
     */
    @GetMapping(value = "/getVideoList")
    public Result<IPage<KuaiShouVideoGet>> getVideoList(KuaiShouVideoGet kuaiShouVideoGet, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        @RequestParam(name = "startDate", defaultValue = "") String startDate,
                                                        @RequestParam(name = "endDate", defaultValue = "") String endDate, HttpServletRequest req) {
        Result<IPage<KuaiShouVideoGet>> result = new Result<>();
        try {

            Long accountId = kuaiShouVideoGet.getAccountId();
            kuaiShouVideoGet.setAccountId(null);
            if (Check.isNull(accountId)) {
                throw new Exception("账户id不能为空");
            }
            QueryWrapper<KuaiShouVideoGet> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouVideoGet, req.getParameterMap());
            queryWrapper.eq("account_id", accountId);
            if (!Check.isNull(startDate) && !Check.isNull(endDate)) {
                queryWrapper.between("stat_date", startDate, endDate);
            }
            queryWrapper.orderByDesc("stat_date");
            queryWrapper.groupBy("signature");
            Page<KuaiShouVideoGet> page = new Page<>(pageNo, pageSize);
            IPage<KuaiShouVideoGet> pageList = kuaiShouVideoGetService.page(page, queryWrapper);
            result.setSuccess(true);
            result.setResult(pageList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }

        return result;
    }

    /**
     * 获取素材信息
     *
     * @param code
     * @return
     */
    @GetMapping(value = "/getCreativeCopywriter")
    public Result<MaterialInfo> getCreativeCopywriter(String code, Long accountId) {
        Result<MaterialInfo> result = new Result<>();
        try {
            Long projectId = materialInfoMapper.getProjectIdByAccountId(accountId);
            QueryWrapper<MaterialInfo> materialInfoQueryWrapper = new QueryWrapper<>();
            materialInfoQueryWrapper.eq("code", code);
            materialInfoQueryWrapper.eq("project_id", projectId);
            materialInfoQueryWrapper.last("limit 1");
            MaterialInfo materialInfo = materialInfoMapper.selectOne(materialInfoQueryWrapper);
            result.setSuccess(true);
            result.setResult(materialInfo);
        } catch (Exception e) {

            e.printStackTrace();
            result.setSuccess(false);
        }

        return result;
    }


    /**
     * 获取行动号召按钮
     *
     * @param campaignId
     * @return
     */
    @GetMapping(value = "/getActionBarText")
    public Result<List<KuaiShouActionBarText>> queryPageList(String campaignId) {
        Result<List<KuaiShouActionBarText>> result = new Result<>();
        QueryWrapper<KuaiShouCampaign> wrapper = new QueryWrapper<>();
        wrapper.eq("campaign_id", campaignId);
        wrapper.orderByDesc("create_time");
        wrapper.last("limit 1");
        KuaiShouCampaign campaign = campaignMapper.selectOne(wrapper);
        if (!Check.isNull(campaignId)) {
            QueryWrapper<KuaiShouActionBarText> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", campaign.getCampaignType());
            List<KuaiShouActionBarText> list = actionBarTextService.list(queryWrapper);
            result.setSuccess(true);
            result.setResult(list);
        } else {
            result.setSuccess(false);
            result.setMessage("未获取到广告计划信息");
        }

        return result;
    }


    @GetMapping(value = "/getActionBarTextByType")
    public Result<List<KuaiShouActionBarText>> getActionBarTextByType(Integer type) {
        Result<List<KuaiShouActionBarText>> result = new Result<>();
        QueryWrapper<KuaiShouActionBarText> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        List<KuaiShouActionBarText> list = actionBarTextService.list(queryWrapper);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }


    /**
     * 创建创意
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/createCreative")
    public Result createCreative(@RequestBody JSONObject requestJson) {
        Result result = new Result<>();
        try {
            Map<String, Object> map = batchService.batchCreateCreative(requestJson);
            Integer code = (Integer) map.get("code");
            if (code == 0) {
                result.setSuccess(true);
                result.setMessage("创建成功");
            } else {
                result.setSuccess(false);
                result.setMessage((String) map.get("message"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("系统错误");
        }
        return result;
    }


    /**
     * 批量修改广告组状态
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateCreativeStatus")
    public Result<JSONObject> batchUpdateCreativeStatus(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("账号信息为空");
            }
            Integer putStatus = requestJson.getInteger("putStatus");
            if (putStatus == null) {
                throw new Exception("请选择状态");
            }
            String userId = requestJson.getString("userId");
            JSONArray creativeIds = requestJson.getJSONArray("creativeIds");
            JSONArray failArr = new JSONArray();
            if (!Check.isNull(creativeIds)) {
                for (int i = 0; i < creativeIds.size(); i++) {
                    Long creativeId = creativeIds.getLong(i);
                    if (!Check.isNull(creativeId)) {
                        Map<String, Object> updateMap = updateService.updateCreativeStatus(token.getAccessToken(), accountId, creativeId, putStatus, userId);
                        if (!Check.isNull(updateMap)) {
                            Integer code = (Integer) updateMap.get("code");
                            if (code != 0) {
                                JSONObject failJson = new JSONObject();
                                failJson.put("message", updateMap.get("message"));
                                KuaiShouCreative creative = batchService.getCreativeInfo(accountId, creativeId);
                                if (!Check.isNull(creative)) {
                                    failJson.put("campaignName", creative.getCreativeName());
                                }
                                failArr.add(failJson);
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            json.put("totalCount", creativeIds.size());
            json.put("failCount", failArr.size());
            json.put("failInfo", failArr);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 查询 定向模板
     *
     * @param kuaiShouDirectionalTemplate
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/getDirectionalTemplate")
    public Result<List<KuaiShouDirectionalTemplate>> getDirectionalTemplate(KuaiShouDirectionalTemplate kuaiShouDirectionalTemplate,
                                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                            HttpServletRequest req) {
        Result<List<KuaiShouDirectionalTemplate>> result = new Result<>();
        QueryWrapper<KuaiShouDirectionalTemplate> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouDirectionalTemplate, req.getParameterMap());
        List<KuaiShouDirectionalTemplate> templates = kuaiShouDirectionalTemplateService.list(queryWrapper);
        result.setSuccess(true);
        result.setResult(templates);
        return result;
    }

    /**
     * 添加 快手-定向模板
     *
     * @return
     */
    @PostMapping(value = "/addDirectionalTemplate")
    public Result<KuaiShouDirectionalTemplate> add(@RequestBody KuaiShouDirectionalTemplate kuaiShouDirectionalTemplate) {
        Result<KuaiShouDirectionalTemplate> result = new Result<KuaiShouDirectionalTemplate>();
        try {
            kuaiShouDirectionalTemplateService.save(kuaiShouDirectionalTemplate);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    /**
     * 编辑 定向模板
     *
     * @param
     * @return
     */
    @PutMapping(value = "/editDirectionalTemplate")
    public Result<KuaiShouDirectionalTemplate> editDirectionalTemplate(@RequestBody KuaiShouDirectionalTemplate kuaiShouDirectionalTemplate) {
        Result<KuaiShouDirectionalTemplate> result = new Result<KuaiShouDirectionalTemplate>();
        KuaiShouDirectionalTemplate kuaiShouDirectionalTemplateEntity = kuaiShouDirectionalTemplateService.getById(kuaiShouDirectionalTemplate.getId());
        if (kuaiShouDirectionalTemplateEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = kuaiShouDirectionalTemplateService.updateById(kuaiShouDirectionalTemplate);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除 定向模板
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/deleteDirectionalTemplate")
    public Result<?> deleteDirectionalTemplate(@RequestParam(name = "id", required = true) String id) {
        try {
            kuaiShouDirectionalTemplateService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }


    /**
     * 获取 广告组详情
     *
     * @param accountId
     * @param unitId
     * @return
     */
    @GetMapping(value = "/getUnitDetail")
    public Result<JSONObject> getUnitDetail(Long accountId, Long unitId) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(accountId) || Check.isNull(unitId)) {
                throw new Exception("参数错误");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            kuaiShouGroupService.getGroupByUnitId(oauthToken.getAccessToken(), oauthToken.getAccountId(), unitId);
            JSONObject returnJson = new JSONObject();
            QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
            groupQueryWrapper.eq("account_id", accountId);
            groupQueryWrapper.eq("unit_id", unitId);
            groupQueryWrapper.orderByDesc("create_time").last("limit 1");
            KuaiShouGroup group = kuaiShouGroupService.getOne(groupQueryWrapper);
            if (!Check.isNull(group)) {
                returnJson.put("baseInfo", group);
                QueryWrapper<KuaiShouAppInfo> appInfoQueryWrapper = new QueryWrapper<>();
                appInfoQueryWrapper.eq("account_id", accountId);
                appInfoQueryWrapper.eq("unit_id", unitId);
                appInfoQueryWrapper.orderByDesc("create_time").last("limit 1");
                KuaiShouAppInfo appInfo = appInfoService.getOne(appInfoQueryWrapper);
                if (!Check.isNull(appInfo)) {
                    returnJson.put("appInfo", appInfo);
                }
                QueryWrapper<KuaiShouGroupTarget> targetQueryWrapper = new QueryWrapper<>();
                targetQueryWrapper.eq("account_id", accountId);
                targetQueryWrapper.eq("unit_id", unitId);
                targetQueryWrapper.orderByDesc("create_time").last("limit 1");
                KuaiShouGroupTarget target = targetService.getOne(targetQueryWrapper);
                if (!Check.isNull(target)) {
                    returnJson.put("target", target);
                }
            }
            result.setSuccess(true);
            result.setResult(returnJson);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 修改广告计划
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/updateCampaign")
    public Result<JSONObject> updateCampaign(@RequestBody JSONObject requestJson) {

        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参为空");
            }
            JSONObject campaignJson = batchService.updateCampaign(requestJson);
            result.setSuccess(true);
            result.setResult(campaignJson);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }


        return result;

    }


    /**
     * 修改广告组
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/updateUnit")
    public Result<JSONObject> updateUnit(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参为空");
            }
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }

            JSONObject unitJson = batchService.updateUnit(requestJson, oauthToken);
            result.setSuccess(true);
            result.setResult(unitJson);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 批量修改广告组定向
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateUnit")
    public Result<JSONObject> batchUpdateUnit(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参为空");
            }

            JSONArray unitIds = requestJson.getJSONArray("unitIds");
            if (Check.isNull(unitIds)) {
                throw new Exception("请选择需要修改的广告组");
            }
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }

            JSONObject returnJson = new JSONObject();
            JSONArray failArr = new JSONArray();
            for (int i = 0; i < unitIds.size(); i++) {
                Long unitId = unitIds.getLong(i);
                requestJson.put("unitId", unitId);
                JSONObject unitJson = batchService.updateUnit(requestJson, oauthToken);
                if (!Check.isNull(unitJson)) {
                    Integer code = unitJson.getInteger("code");
                    if (code != 0) {
                        JSONObject failJson = new JSONObject();
                        failJson.put("message", unitJson.get("message"));
                        KuaiShouGroup group = batchService.getUnitInfo(requestJson.getLong("accountId"), unitId);
                        if (!Check.isNull(group)) {
                            failJson.put("unitName", group.getUnitName());
                        }
                        failArr.add(failJson);
                    }
                }
            }
            returnJson.put("totalCount", unitIds.size());
            returnJson.put("failCount", failArr.size());
            returnJson.put("failInfo", failArr);
            result.setSuccess(true);
            result.setResult(returnJson);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 修改广告创意
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/updateCreative")
    public Result<JSONObject> updateCreative(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参为空");
            }
            Long accountId = requestJson.getLong("accountId");
            if (Check.isNull(accountId)) {
                throw new Exception("请输入需创建账号");
            }


            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }

            JSONObject creativeJson = batchService.updateCreative(requestJson, oauthToken);
            result.setSuccess(true);
            result.setResult(creativeJson);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 获取视频信息
     *
     * @param photoId
     * @return
     */
    @GetMapping(value = "/getVideoDetail")
    public Result<KuaiShouVideoGet> getVideoDetail(String photoId) {
        Result<KuaiShouVideoGet> result = new Result<>();
        try {
            if (Check.isNull(photoId)) {
                throw new Exception("参数错误");
            }
            QueryWrapper<KuaiShouVideoGet> videoGetQueryWrapper = new QueryWrapper<>();
            videoGetQueryWrapper.eq("photo_id", photoId);
            videoGetQueryWrapper.orderByDesc("create_time").last("limit 1");
            KuaiShouVideoGet video = videoGetService.getOne(videoGetQueryWrapper);
            result.setResult(video);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 获取图片信息
     *
     * @param accountId
     * @param imageToken
     * @return
     */
    @GetMapping(value = "/getImageDetail")
    public Result<KuaiShouImageGet> getImageDetail(Long accountId, String imageToken) {
        Result<KuaiShouImageGet> result = new Result<>();
        try {
            if (Check.isNull(accountId) || Check.isNull(imageToken)) {
                throw new Exception("参数错误");
            }
            QueryWrapper<KuaiShouImageGet> imageGetQueryWrapper = new QueryWrapper<>();
            imageGetQueryWrapper.eq("account_id", accountId);
            imageGetQueryWrapper.eq("image_token", imageToken);
            imageGetQueryWrapper.orderByDesc("create_time").last("limit 1");
            KuaiShouImageGet image = imageGetService.getOne(imageGetQueryWrapper);
            result.setResult(image);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 获取地域信息
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/getRegionDetail")
    public Result<JSONArray> getRegionDetail(@RequestBody JSONObject requestJson) {
        Result<JSONArray> result = new Result<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("参数错误");
            }
            JSONArray returnArr = new JSONArray();
            JSONArray regionArr = requestJson.getJSONArray("regionArr");
            if (!Check.isNull(regionArr)) {
                for (int i = 0; i < regionArr.size(); i++) {
                    Long regionId = regionArr.getLong(i);
                    if (!Check.isNull(regionId)) {
                        QueryWrapper<KuaiShouRegionListParent> regionListParentQueryWrapper = new QueryWrapper<>();
                        regionListParentQueryWrapper.eq("region_id", regionId);
                        regionListParentQueryWrapper.last("limit 1");
                        KuaiShouRegionListParent region = regionListParentService.getOne(regionListParentQueryWrapper);
                        if (!Check.isNull(region)) {
                            JSONObject returnJson = new JSONObject();
                            returnJson.put("value", region.getRegionId());
                            returnJson.put("label", region.getName());
                            returnArr.add(returnJson);
                        }
                    }
                }
            }
            result.setSuccess(true);
            result.setResult(returnArr);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);

        }
        return result;
    }


    /**
     * 批量复制组
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchCopyUnit")
    public Result<JSONObject> batchCopyUnit(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            if (Check.isNull(accountId)) {
                throw new Exception("账户id不能为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到token信息");
            }

            if (Check.isNull(requestJson)) {
                throw new Exception("入参为空");
            }
            JSONArray unitIds = requestJson.getJSONArray("unitIds");
            if (Check.isNull(unitIds)) {
                throw new Exception("请选择需要复制的广告组");
            }

            Long copyToCampaignId = requestJson.getLong("copyToCampaignId");
            JSONObject returnJson = new JSONObject();
            JSONArray failArr = new JSONArray();
            for (int i = 0; i < unitIds.size(); i++) {
                Long unitId = unitIds.getLong(i);
                if (Check.isNull(unitId)) {
                    continue;
                }
                kuaiShouGroupService.getGroupByUnitId(oauthToken.getAccessToken(), oauthToken.getAccountId(), unitId);
                kuaiShouGroupService.getCreativeByUnit(oauthToken.getAccessToken(), oauthToken.getAccountId(), unitId);
                QueryWrapper<KuaiShouGroup> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("account_id", accountId);
                queryWrapper.eq("unit_id", unitId);
                KuaiShouGroup group = groupMapper.selectOne(queryWrapper);
                if (Check.isNull(group)) {
                    continue;
                }
                String unitNameStr = group.getUnitName();
                String unitName;

                if (unitNameStr.contains("#")) {
                    int lastIndexOf = unitNameStr.lastIndexOf("#");
                    unitName = unitNameStr.substring(0, lastIndexOf);
                } else {
                    unitName = unitNameStr;
                }
                group.setUnitName(unitName + RandomUtil.verifyCode());
                JSONObject unitJson = batchService.copyUnit(group, copyToCampaignId, oauthToken, null);
                if (!Check.isNull(unitJson)) {
                    Integer code = unitJson.getInteger("code");
                    if (code != 0) {
                        JSONObject failJson = new JSONObject();
                        failJson.put("message", unitJson.get("message"));
                        failJson.put("unitName", unitJson.get("unitName"));
                        failArr.add(failJson);
                    }
                }
                Thread.sleep(200);
            }
            returnJson.put("totalCount", unitIds.size());
            returnJson.put("failCount", failArr.size());
            returnJson.put("failInfo", failArr);
            result.setSuccess(true);
            result.setResult(returnJson);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 复制组
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/copyUnit")
    public Result<JSONObject> copyUnit(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            JSONObject returnJson = new JSONObject();

            Long unitId = requestJson.getLong("unitId");
            kuaiShouGroupService.getGroupByUnitId(oauthToken.getAccessToken(), oauthToken.getAccountId(), unitId);
            kuaiShouGroupService.getCreativeByUnit(oauthToken.getAccessToken(), oauthToken.getAccountId(), unitId);
            Long copyToCampaignId = requestJson.getLong("copyToCampaignId");
            JSONArray failArr = new JSONArray();
            Integer createCount = requestJson.getInteger("createCount");
            if (Check.isNull(createCount) || createCount == 0) {
                throw new Exception("请选择迭代次数");
            }
            if (createCount == 1) {
                JSONObject createJson = batchService.createUnit(requestJson, oauthToken);
                if (!Check.isNull(createJson)) {
                    failArr = createJson.getJSONArray("fail");
                }
            } else if (createCount > 1) {
                QueryWrapper<KuaiShouGroup> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("account_id", accountId);
                queryWrapper.eq("unit_id", unitId);
                KuaiShouGroup group = groupMapper.selectOne(queryWrapper);
                if (Check.isNull(group)) {
                    throw new Exception("未获取到广告组信息");
                }
                String unitNameStr = group.getUnitName();
                String unitName;

                if (unitNameStr.contains("#")) {
                    int lastIndexOf = unitNameStr.lastIndexOf("#");
                    unitName = unitNameStr.substring(0, lastIndexOf);
                } else {
                    unitName = unitNameStr;
                }

                Integer createType = requestJson.getInteger("createType");
                JSONObject otherJson = requestJson.getJSONObject("otherJson");
                if (createType == 1) { // 系统生成
                    for (int i = 0; i < createCount; i++) {
                        String randomName = unitName + RandomUtil.verifyCode();
                        group.setUnitName(randomName);
                        JSONObject copyUnitJson = batchService.copyUnit(group, copyToCampaignId, oauthToken, otherJson);
                        if (copyUnitJson.getInteger("code") != 0) {
                            JSONObject errJson = new JSONObject();
                            errJson.put("message", copyUnitJson.getString("message"));
                            returnJson.put("unitName", randomName);
                            failArr.add(errJson);
                        }
                    }

                } else if (createType == 2) { // 自定义
                    JSONArray unitNames = requestJson.getJSONArray("unitNames");
                    if (Check.isNull(unitNames)) {
                        throw new Exception("请输入广告组名称");
                    }
                    if (!Check.isNull(unitNames)) {
                        for (int i = 0; i < unitNames.size(); i++) {
                            String copyUnitName = String.valueOf(unitNames.get(i));
                            if (Check.isNull(copyUnitName)) {
                                continue;
                            }
                            group.setUnitName(copyUnitName);
                            JSONObject copyUnitJson = batchService.copyUnit(group, copyToCampaignId, oauthToken, otherJson);
                            if (copyUnitJson.getInteger("code") != 0) {
                                JSONObject errJson = new JSONObject();
                                errJson.put("message", copyUnitJson.getString("message"));
                                returnJson.put("unitName", copyUnitName);
                                failArr.add(errJson);
                            }
                        }

                    }

                }
            }

            returnJson.put("failCount", failArr.size());
            returnJson.put("failInfo", failArr);
            result.setResult(returnJson);
            result.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 复制组
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/copyUnitUpdate")
    public Result<JSONObject> copyUnitUpdate(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            Integer totalCount = null;
            Long accountId = requestJson.getLong("accountId");
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            Long copyUnitId = requestJson.getLong("copyUnitId");
            kuaiShouGroupService.getCreativeByUnit(oauthToken.getAccessToken(), oauthToken.getAccountId(), copyUnitId);
            JSONObject returnJson = new JSONObject();
            JSONObject groupJson = requestJson.getJSONObject("groupArr");
            requestJson.remove("groupArr");
            requestJson.remove("groupArr");
            JSONArray failArr = new JSONArray();
            Integer createType = requestJson.getInteger("createType");
            if (createType == 1) { //系统生成
                // 需要获取创建条数
                String unitName = groupJson.getString("unitName");
                Integer createCount = requestJson.getInteger("createCount");
                totalCount = createCount;
                if (unitName.contains("#")) {
                    int lastIndexOf = unitName.lastIndexOf("#");
                    unitName = unitName.substring(0, lastIndexOf);
                }
                for (int i = 0; i < createCount; i++) {
                    String randomName = unitName + RandomUtil.verifyCode() + "_" + i;
                    groupJson.put("unitName", randomName);
                    requestJson.put("groupArr", groupJson);
                    JSONObject createJson = batchService.copyUpdateUnit(requestJson, oauthToken);
                    if (createJson.getInteger("code") != 0) {
                        JSONObject errJson = new JSONObject();
                        errJson.put("message", createJson.getString("message"));
                        errJson.put("unitName", randomName);
                        failArr.add(errJson);
                    }
                }

            } else if (createType == 2) { // 自定义
                JSONArray unitNames = groupJson.getJSONArray("unitName");
                groupJson.remove("unitName");
                totalCount = unitNames.size();
                for (int i = 0; i < unitNames.size(); i++) {
                    JSONObject nameJson = unitNames.getJSONObject(i);
                    if (Check.isNull(nameJson)) {
                        continue;
                    }
                    groupJson.put("unitName", nameJson.getString("unitName"));
                    requestJson.put("groupArr", groupJson);
                    JSONObject createJson = batchService.copyUpdateUnit(requestJson, oauthToken);
                    if (createJson.getInteger("code") != 0) {
                        JSONObject errJson = new JSONObject();
                        errJson.put("message", createJson.getString("message"));
                        errJson.put("unitName", nameJson.getString("unitName"));
                        failArr.add(errJson);
                    }

                }
            }

            returnJson.put("totalCount", totalCount);
            returnJson.put("failCount", failArr.size());
            returnJson.put("failInfo", failArr);
            result.setResult(returnJson);
            result.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 获取人群包
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/pullPopulationList")
    public Result pullPopulationList(Long accountId) {
        Result result = new Result<>();
        try {

            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            Thread thread = new Thread() {
                @Override
                public void run() {
                    iKuaishouInterfaceService.getPopulationList(accountId, oauthToken.getAccessToken());
                }
            };
            thread.start();

            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 获取创意
     *
     * @param accountId
     * @param campaignId
     * @return
     */
    @GetMapping(value = "/getAsyncCreativeList")
    public Result getAsyncCreativeList(Long accountId, Long campaignId) {
        Result result = new Result<>();
        try {
            if (Check.isNull(campaignId) || Check.isNull(accountId)) {
                throw new Exception("必填参数不能为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            Thread thread = new Thread() {
                @Override
                public void run() {
                    iKuaishouInterfaceService.getAsyncCreativeList(accountId, oauthToken.getAccessToken(), campaignId);
                }
            };
            thread.start();

            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 获取当前组下创意数
     *
     * @param accountId
     * @param unitId
     * @return
     */
    @GetMapping(value = "/checkCreativeCount")
    public Result checkCreativeCount(Long accountId, Long unitId) {
        Result result = new Result<>();
        try {
            if (Check.isNull(unitId) || Check.isNull(accountId)) {
                throw new Exception("必填参数不能为空");
            }
            Integer count = kuaiShouCreativeService.checkCreativeCount(accountId, unitId);
            result.setResult(count);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    @GetMapping(value = "/getConvertList")
    public Result<List<ConvertVo>> getConvertList(Long accountId, Integer type) {
        Result result = new Result<>();
        try {
            if (Check.isNull(accountId) || Check.isNull(type)) {
                throw new Exception("必填参数不能为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }

            List<ConvertVo> convertList = iKuaishouInterfaceService.getConvertList(accountId, oauthToken.getAccessToken(), type);
            result.setResult(convertList);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 批量修改广告创意
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/batchUpdateCreative")
    public Result<JSONObject> batchUpdateCreative(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参为空");
            }

            Long accountId = requestJson.getLong("accountId");
            if (Check.isNull(accountId)) {
                throw new Exception("请输入需创建账号");
            }


            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }


            JSONArray creativeIds = requestJson.getJSONArray("creativeIds");
            if (Check.isNull(creativeIds)) {
                throw new Exception("请选择需要修改的广告创意");
            }
            JSONObject creativeJson = requestJson.getJSONObject("creativeJson");
            JSONObject returnJson = new JSONObject();
            JSONArray failArr = new JSONArray();
            for (int i = 0; i < creativeIds.size(); i++) {
                Long creativeId = creativeIds.getLong(i);
                creativeJson.put("creativeId", creativeId);
                JSONObject unitJson = batchService.updateCreative(creativeJson, oauthToken);
                if (!Check.isNull(unitJson)) {
                    Integer code = unitJson.getInteger("code");
                    if (code != 0) {
                        JSONObject failJson = new JSONObject();
                        failJson.put("message", unitJson.get("message"));
                        KuaiShouCreative creative = batchService.getCreativeInfo(requestJson.getLong("accountId"), creativeId);
                        if (!Check.isNull(creative)) {
                            failJson.put("creativeName", creative.getCreativeName());
                        }
                        failArr.add(failJson);
                    }
                }
            }
            returnJson.put("totalCount", creativeIds.size());
            returnJson.put("failCount", failArr.size());
            returnJson.put("failInfo", failArr);

            result.setSuccess(true);
            result.setResult(returnJson);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 获取可选的动态词包
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/creativeWord")
    public Result<JSONArray> creativeWord(Long accountId) {
        Result<JSONArray> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("入参为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            JSONArray creativeWordArr = iKuaishouInterfaceService.getCreativeWord(accountId, oauthToken.getAccessToken());
            result.setResult(creativeWordArr);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 获取可选的动态词包
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/getPageList")
    public Result<JSONArray> getPageList(Long accountId, Long appId, String viewComp) {
        Result<JSONArray> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("入参为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            JSONArray pageArr = iKuaishouInterfaceService.getPageList(accountId, oauthToken.getAccessToken(), appId, viewComp);
            result.setResult(pageArr);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 获取可选的动态词包
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/getAppId")
    public Result<Long> getAppId(Long accountId, Long unitId) {
        Result<Long> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("入参为空");
            }
            QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
            groupQueryWrapper.eq("account_id", accountId);
            groupQueryWrapper.eq("unit_id", unitId);
            KuaiShouGroup one = kuaiShouGroupService.getOne(groupQueryWrapper);
            if (!Check.isNull(one)) {
                result.setResult(one.getAppId());
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
            }


        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 收藏标题
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/titleCollection")
    public Result<Long> titleCollection(Long accountId, String title) {
        Result<Long> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("入参为空");
            }

            KuaiShouAdvertiserBaseInfo baseInfo = KuaiShouAdvertiserBaseInfoService.getBaseInfo(accountId);
            Long userId = null;
            if (!Check.isNull(baseInfo)) {
                userId = Long.valueOf(baseInfo.getUserId());
            }


        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 同步素材
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/syncVideo")
    public Result<Boolean> syncVideo(Long accountId) {
        Result<Boolean> result = new Result<>();
        try {
            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
            String startDate = DateUtils.getAnotherDay("yyyy-MM-dd", nowDate, -30);
            syncPullMaterialService.getSyncVideoList(accountId, startDate, nowDate);
            Thread.sleep(5 * 1000L);
            result.setSuccess(true);
            result.setResult(true);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 同步应用
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/syncAppList")
    public Result<Boolean> syncAppList(Long accountId) {
        Result<Boolean> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("入参为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            iKuaishouInterfaceService.getAppList(oauthToken.getAccountId(), oauthToken.getAccessToken());
            result.setSuccess(true);
            result.setResult(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResult(false);
            result.setMessage(e.getMessage());
        }

        return result;
    }


    /**
     * 同步应用
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/getWhiteList")
    public Result<JSONObject> getWhiteList(Long accountId) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("入参为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }

            JSONObject data = batchService.getWhiteList(accountId, oauthToken.getAccessToken());
            result.setSuccess(true);
            result.setResult(data);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResult(null);
            result.setMessage(e.getMessage());
        }

        return result;
    }


    /**
     * 贴纸类型
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/getCreativeWordStyles")
    public Result<JSONArray> getCreativeWordStyles(Long accountId) {
        Result<JSONArray> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("入参为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }

            JSONArray data = batchService.getCreativeWordStyles(accountId, oauthToken.getAccessToken());
            result.setSuccess(true);
            result.setResult(data);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResult(null);
            result.setMessage(e.getMessage());
        }

        return result;
    }

    /**
     * 创意分类
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/getCreativeCategory")
    public Result<JSONArray> getCreativeCategory(Long accountId) {
        Result<JSONArray> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("入参为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }

            JSONArray data = batchService.getCreativeCategory(accountId, oauthToken.getAccessToken());
            result.setSuccess(true);
            result.setResult(data);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResult(null);
            result.setMessage(e.getMessage());
        }

        return result;
    }


    /**
     * 获取创意标签白名单
     *
     * @param accountId
     * @return
     */
    @GetMapping(value = "/getCategoryWhite")
    public Result<JSONObject> getCategoryWhite(Long accountId) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("入参为空");
            }
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            JSONObject data = batchService.getCategoryWhite(accountId, oauthToken.getAccessToken());
            result.setSuccess(true);
            result.setResult(data);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResult(null);
            result.setMessage(e.getMessage());
        }

        return result;
    }


}
