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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCreative;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.service.*;
import cn.com.ctop.kuaishou.modules.report.entity.EtlKuaiShouGroupDailyReport;
import cn.com.ctop.kuaishou.modules.report.entity.ProjectMember;
import cn.com.ctop.kuaishou.modules.report.service.IEtlKuaiShouGroupDailyReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/kuaishou/dingpan")
public class DingPanController {
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private IKuaishouInterfaceService interfaceService;
    @Autowired
    private IKuaiShouGroupService groupService;
    @Autowired
    private IKuaiShouCreativeService creativeService;
    @Autowired
    private IBatchService batchService;
    @Autowired
    private IKuaiShouUpdateService updateService;
    @Autowired
    private IKuaiShouGroupTemplateService groupTemplateService;
    @Autowired
    private IEtlKuaiShouGroupDailyReportService etlKuaiShouGroupDailyReportService;

    /**
     * 获取创意监测链接
     *
     * @param accountId
     * @param unitId
     * @return
     */
    @GetMapping(value = "/getClickTrackUrlByUnitId")
    public Result<String> getClickTrackUrlByUnitId(Long accountId, Long unitId) {
        Result<String> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("请输入账户id");
            }
            if (Check.isNull(unitId)) {
                throw new Exception("请输入组id");
            }
            CtopOauthToken token = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("未获取到账户授权信息");
            }
            groupService.getCreativeByUnit(token.getAccessToken(), token.getAccountId(), unitId);
            String clickTrackUr = creativeService.getClickTrackUrl(accountId, unitId);
            result.setSuccess(true);
            result.setResult(clickTrackUr);

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


    /**
     * 修改监测链接
     *
     * @param accountId
     * @param unitId
     * @param clickTrackUr
     * @return
     */
    @GetMapping(value = "/updateClickTrackUrlByUnitId")
    public Result<String> updateClickTrackUrlByUnitId(Long accountId, Long unitId, String clickTrackUr) {
        Result<String> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("请输入账户id");
            }
            if (Check.isNull(unitId)) {
                throw new Exception("请输入组id");
            }
            if (Check.isNull(clickTrackUr)) {
                throw new Exception("请输入监测链接");
            }
            CtopOauthToken token = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("未获取到账户授权信息");
            }
            List<KuaiShouCreative> creatives = creativeService.getCreativeListByAccountIdAndUnitId(accountId, unitId);
            if (Check.isNull(creatives)) {
                throw new Exception("此组下暂无创意");
            }
            for (KuaiShouCreative creative : creatives) {
                JSONObject json = new JSONObject();
                json.put("creativeId", creative.getCreativeId());
                if (creative.getCreativeMaterialType() == 1) {
                    json.put("clickTrackUrl", clickTrackUr);
                } else if (creative.getCreativeMaterialType() == 4) {
                    json.put("impressionUrl", clickTrackUr);
                    json.put("clickTrackUrl", clickTrackUr);
                }
                batchService.updateCreative(json, token);
            }
            result.setSuccess(true);
            result.setResult("修改成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    @GetMapping(value = "/updateTemplate")
    public Result<String> updateTemplate(Long accountId, Long unitId, Long templateId) {
        Result<String> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("请输入账户id");
            }
            if (Check.isNull(unitId)) {
                throw new Exception("请输入组id");
            }
            if (Check.isNull(templateId)) {
                throw new Exception("请输入模板Id");
            }
            CtopOauthToken token = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("未获取到账户授权信息");
            }
            groupService.getGroupByUnitId(token.getAccessToken(), token.getAccountId(), unitId);
            KuaiShouGroup kuaiShouGroup = groupService.selectGroupByUnitId(accountId, unitId);
            if (Check.isNull(kuaiShouGroup)) {
                throw new Exception("组信息为空");
            }
            Integer sceneId = JSONArray.parseArray(kuaiShouGroup.getSceneId()).getInteger(0);
            JSONObject unitJson = new JSONObject();
            unitJson.put("advertiser_id", accountId);
            unitJson.put("unit_id", unitId);
            if (sceneId != 5) {
                unitJson.put("template_id", templateId);
            } else {
                JSONObject unionJson = groupTemplateService.getUnionJson(templateId);
                if (Check.isNullMap(unionJson)) {
                    throw new Exception("根据定向模板未获取到相关信息");
                }
                unitJson.put("target", unionJson.getJSONObject("target"));
            }
            JSONObject jsonObject = updateService.updateUnit(token.getAccessToken(), unitJson);
            Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                result.setSuccess(true);
                result.setMessage("修改成功");
            } else {
                result.setSuccess(false);
                result.setMessage(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 修改出价
     *
     * @param accountId
     * @param unitId
     * @param bid
     * @param bidType
     * @return
     */
    @GetMapping(value = "/updateBid")
    public Result<String> updateBid(Long accountId, Long unitId, Long bid, Integer bidType) {
        Result<String> result = new Result<>();
        try {
            if (Check.isNull(accountId)) {
                throw new Exception("请输入账户id");
            }
            if (Check.isNull(unitId)) {
                throw new Exception("请输入组id");
            }
            if (Check.isNull(bidType)) {
                throw new Exception("请输入出价类型");
            }
            if (Check.isNull(bid)) {
                throw new Exception("请输入出价");
            }
            CtopOauthToken token = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(token)) {
                throw new Exception("未获取到账户授权信息");
            }

            JSONObject unitJson = new JSONObject();
            unitJson.put("advertiser_id", accountId);
            unitJson.put("unit_id", unitId);
            if (bidType == 2) {
                unitJson.put("bid", bid);
            } else if (bidType == 10) {
                unitJson.put("cpa_bid", bid);
            }
            JSONObject jsonObject = updateService.updateUnit(token.getAccessToken(), unitJson);
            Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                QueryWrapper<EtlKuaiShouGroupDailyReport> wrapper = new QueryWrapper<>();
                wrapper.eq("account_id", accountId);
                wrapper.eq("unit_id", unitId);
                EtlKuaiShouGroupDailyReport etl = new EtlKuaiShouGroupDailyReport();
                etl.setBid(bid);
                etlKuaiShouGroupDailyReportService.update(etl, wrapper);
                result.setSuccess(true);
                result.setMessage("修改成功");
            } else {
                result.setSuccess(false);
                result.setMessage(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


}
