package org.jeecg.modules.bytedance.advertise.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.bytedance.advertise.dockapi.MarketingService;
import org.jeecg.modules.bytedance.advertise.entity.AiBytedanceAdvertiserStrategy;
import org.jeecg.modules.bytedance.advertise.entity.ByteDanceAdvertisePlan;
import org.jeecg.modules.bytedance.advertise.service.IByteDanceAdvertisePlanService;
import org.jeecg.modules.bytedance.advertise.vo.PlanSearchVo;
import org.jeecg.modules.bytedance.common.entity.CtopOauthToken;
import org.jeecg.modules.bytedance.common.service.ICtopOauthTokenService;
import org.jeecg.modules.bytedance.common.utils.Check;
import org.jeecg.modules.bytedance.report.service.IBytedanceAdvertiserHourlyReportService;
import org.jeecg.modules.bytedance.report.service.IBytedancePlanHourlyReportService;
import org.jeecg.modules.bytedance.report.service.IBytedanceReportMaterialDailyService;
import org.jeecg.modules.system.service.ISysRoleService;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 投放数据
 * @author jeecg-boot
 * @date   2021-05-18
 * @version V1.0
 */
@RestController
@RequestMapping("/advertiser/bytedanceReportController")
@Api(tags="投放数据")
@Slf4j
public class BytedanceReportController {
	@Autowired
	private IBytedanceAdvertiserHourlyReportService bytedanceAdvertiserHourlyReportService;

	@Autowired
	private IBytedancePlanHourlyReportService bytedancePlanHourlyReportService;

	@Autowired
	private IBytedanceReportMaterialDailyService bytedanceReportMaterialDailyService;

	@Autowired
	private ISysRoleService sysRoleService;

	@Autowired
	private MarketingService marketingService;

	@Autowired
	private ICtopOauthTokenService tokenService;

	@Autowired
	private IByteDanceAdvertisePlanService byteDanceAdvertisePlanService;



	@ApiOperation(value="投放数据-获取当前用户花费最高的的账户", notes="投放数据-获取当前用户花费最高的的账户")
	@GetMapping(value = "/initAccountIdAndTime")
	public Result initAccountIdAndTime(@RequestParam("userId") String userId,
										 @RequestParam(value = "type",defaultValue = "bytedance") String type) {
		try {
			//查询用户角色
			String roleCode = sysRoleService.getRoleCodeByUserId(userId);
			if (Check.isNull(roleCode)){
				return Result.errorMsg("请输入正确的用户id。");
			}
			//角色为 管理员 || 销售 || 媒介 查询全部
			if ("admin".equals(roleCode) || roleCode.contains("sale") || "meidaManager".equals(roleCode)) {
				userId = null;
			}
			return bytedanceAdvertiserHourlyReportService.initAccountIdAndTime(userId,type);
		}catch (Exception e){
			log.error("投放数据-获取当前用户花费最高的的账户异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}





	@ApiOperation(value="投放数据-获取花费和同比", notes="投放数据-获取花费和同比")
	@GetMapping(value = "/getReportYearOnYearCost")
	public Result getReportYearOnYearCost(@RequestParam("accountId") String accountId,
										 @RequestParam("startTime") String startTime,
										 @RequestParam("endTime") String endTime) {
		try {
			return bytedanceAdvertiserHourlyReportService.getReportYearOnYearCost(accountId,startTime,endTime);
		}catch (Exception e){
			log.error("投放数据-获取花费和环比异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}




	@ApiOperation(value="投放数据-查询账户余额", notes="投放数据-查询账户余额")
	@GetMapping(value = "/getAccountCost")
	public Result getAccountCost(@RequestParam("accountId") String accountId) {
		try {
			return bytedanceAdvertiserHourlyReportService.getAccountCost(accountId);
		}catch (Exception e){
			log.error("投放数据-获取花费和环比异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}


	@ApiOperation(value="投放数据-查询计划数据", notes="投放数据-查询计划数据")
	@GetMapping(value = "/getReportPlanCost")
	public Result getReportPlanCost(@RequestParam("accountId") String accountId,
									@RequestParam("startTime") String startTime,
									@RequestParam("endTime") String endTime,
									@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
									@RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize) {
		try {
			return bytedanceAdvertiserHourlyReportService.getReportPlanCost(accountId,startTime,endTime,pageNum,pageSize);
		}catch (Exception e){
			log.error("投放数据-获取花费和环比异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}



	@ApiOperation(value="投放数据-更新计划出价-bid", notes="投放数据-更新计划出价")
	@GetMapping(value = "/updateADBid")
	public Result updateADBid(@RequestParam("accountId") String accountId,
							  @RequestParam("adId") String adId,
							  @RequestParam("bid") BigDecimal bid) {
		try {
			CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
			List<Map<String, Object>> listMap = new ArrayList<>();
			Map<String, Object> map = new HashMap<>();
			map.put("ad_id",adId);
			map.put("bid",bid);
			listMap.add(map);
			Result result = marketingService.updatePlanBid(token,accountId,listMap);
			if (!result.isSuccess()){
				return Result.errorMsg(result.getMessage());
			}
			ByteDanceAdvertisePlan byteDanceAdvertisePlan = new ByteDanceAdvertisePlan();
			byteDanceAdvertisePlan.setId(Long.valueOf(adId));
			byteDanceAdvertisePlan.setBid(bid);
			//更新 表 定向包id
			byteDanceAdvertisePlanService.updatePlanOrPackage(byteDanceAdvertisePlan);
			return Result.successMsg("修改出价成功。",null);
		}catch (Exception e){
			log.error("投放数据-更新计划出价-bid异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}


	@ApiOperation(value="投放数据-更新计划出价-cpaBid-计划预算", notes="投放数据-更新计划出价-计划预算")
	@GetMapping(value = "/updateADCpaBid")
	public Result updateADCpaBid(@RequestParam("accountId") String accountId,
									@RequestParam("adId") String adId,
									@RequestParam(value = "cpaBid",required = false) BigDecimal cpaBid,
									@RequestParam(value = "adScheduleTime",required = false) String adScheduleTime,
									@RequestParam(value = "budgetMode",required = false) String budgetMode,
									@RequestParam(value = "budget",required = false) BigDecimal budget,
								 	@RequestParam(value = "downloadUrl",required = false) String downloadUrl) {
		try {
			CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
			PlanSearchVo planSearchVo = new PlanSearchVo();
			String[] ids = adId.split(",");
			planSearchVo.setIds(ids);
			//2 获取广告计划
			Result result = marketingService.getPlanList(token,planSearchVo,1,1000);
			if (!result.isSuccess()){
				return Result.errorMsg(result.getMessage());
			}
			JSONObject jsonObject =JSONObject.parseObject(result.getResult().toString());
			JSONArray array = jsonObject.getJSONArray("list");
			List<Map<String,Object>> dataList = JSONArray.parseObject(array.toJSONString(),List.class);
			for (Map<String, Object> map : dataList) {
				//不需要传modifytime字段
				//String modifyTime = map.get("modify_time").toString();
				String modifyTime = null;
				AiBytedanceAdvertiserStrategy strategy = new AiBytedanceAdvertiserStrategy();
				strategy.setAccountId(Long.valueOf(accountId));
				strategy.setAdCpaBid(cpaBid);
				strategy.setAdScheduleTime(adScheduleTime);
				if(null!=downloadUrl&&!downloadUrl.trim().equals("")){
					strategy.setAdDownloadUrl(downloadUrl);
				}
				//strategy.setAdBudgetMode(budgetMode);
				strategy.setAdBudget(budget);
				//3 修改广告计划 中的 cpaBid
				Result resultUpd = marketingService.updateAdvertiserPlan(token,adId,modifyTime,strategy);
				if (!resultUpd.isSuccess()){
					return Result.errorMsg(resultUpd.getMessage());
				}
				ByteDanceAdvertisePlan byteDanceAdvertisePlan = new ByteDanceAdvertisePlan();
				byteDanceAdvertisePlan.setId(Long.valueOf(adId));
				byteDanceAdvertisePlan.setCpaBid(cpaBid);
				byteDanceAdvertisePlan.setScheduleTime(adScheduleTime);
				byteDanceAdvertisePlan.setBudgetMode(budgetMode);
				byteDanceAdvertisePlan.setBudget(Check.isNull(budget) ? null : budget);
				//更新 表 bid || 定向包id || 状态
				byteDanceAdvertisePlanService.updatePlanOrPackage(byteDanceAdvertisePlan);
			}

			return Result.successMsg("修改出价成功。",null);
		}catch (Exception e){
			log.error("投放数据-更新计划出价-cpaBid-计划预算异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}


	@ApiOperation(value="投放数据-获取计划已有定向包", notes="投放数据-获取计划已有定向包")
	@GetMapping(value = "/getADAudiencePackageId")
	public Result getADAudiencePackageId(@RequestParam("accountId") String accountId,
										  @RequestParam("adId") String adId) {
		try {
			//1 获取token
			CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
			PlanSearchVo planSearchVo = new PlanSearchVo();
			String[] ids = adId.split(",");
			planSearchVo.setIds(ids);
			//2 获取广告计划
			Result result = marketingService.getPlanList(token,planSearchVo,1,1000);
			if (!result.isSuccess()){
				return Result.errorMsg(result.getMessage());
			}
			JSONObject jsonObject =JSONObject.parseObject(result.getResult().toString());
			JSONArray array = jsonObject.getJSONArray("list");
			List<Map<String,Object>> dataList = JSONArray.parseObject(array.toJSONString(),List.class);
			Map<String,String> resultMap = new HashMap<>();
			for (Map<String, Object> map : dataList) {
				String packageId = Check.isNull(map.get("audience_package_id")) ? "" : map.get("audience_package_id") .toString();
				resultMap.put("packageId",packageId);
			}
			return Result.successMsg("获取计划定向包id", resultMap);
		}catch (Exception e){
			log.error("投放数据-获取计划已有定向包异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}





	@ApiOperation(value="投放数据-更新计划定向包", notes="投放数据-更新计划定向包")
	@GetMapping(value = "/updateADAudiencePackage")
	public Result updateADAudiencePackage(@RequestParam("accountId") String accountId,
									@RequestParam("adId") String adId,
									@RequestParam("audiencePackageId") String audiencePackageId) {
		try {
			//1 获取token
			CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
			PlanSearchVo planSearchVo = new PlanSearchVo();
			String[] ids = adId.split(",");
			planSearchVo.setIds(ids);
			//2 获取广告计划
			Result result = marketingService.getPlanList(token,planSearchVo,1,1000);
			if (!result.isSuccess()){
				return Result.errorMsg(result.getMessage());
			}
			JSONObject jsonObject =JSONObject.parseObject(result.getResult().toString());
			JSONArray array = jsonObject.getJSONArray("list");
			List<Map<String,Object>> dataList = JSONArray.parseObject(array.toJSONString(),List.class);

			for (Map<String, Object> map : dataList) {
				String modifyTime = map.get("modify_time").toString();
				AiBytedanceAdvertiserStrategy strategy = new AiBytedanceAdvertiserStrategy();
				strategy.setAccountId(Long.valueOf(accountId));
				strategy.setAdAudiencePackageId(audiencePackageId);
				//3 修改广告计划 中的 定向包id
				Result resultUpd = marketingService.updateAdvertiserPlan(token,adId,modifyTime,strategy);
				if (!resultUpd.isSuccess()){
					return Result.errorMsg(resultUpd.getMessage());
				}
				ByteDanceAdvertisePlan byteDanceAdvertisePlan = new ByteDanceAdvertisePlan();
				byteDanceAdvertisePlan.setId(Long.valueOf(adId));
				byteDanceAdvertisePlan.setAudiencePackageId(audiencePackageId);
				//更新 表 定向包id
				byteDanceAdvertisePlanService.updatePlanOrPackage(byteDanceAdvertisePlan);
			}
			return Result.successMsg("更新计划定向包", null);
		}catch (Exception e){
			log.error("投放数据-更新计划定向包异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}


	@ApiOperation(value="投放数据-更新计划状态", notes="投放数据-更新计划状态")
	@GetMapping(value = "/updPlanStatus")
	public Result updPlanStatus(@RequestParam("accountId") String accountId,
							  @RequestParam("adId") Long adId,
							  @RequestParam("optStatus") String optStatus) {
		try {
			CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
			List<Long> list = new ArrayList<>();
			list.add(adId);
			//api 更新计划状态
			Result result = marketingService.updPlanStatus(token,list,optStatus);
			if (result.isSuccess()){
				ByteDanceAdvertisePlan byteDanceAdvertisePlan = new ByteDanceAdvertisePlan();
				byteDanceAdvertisePlan.setId(adId);
				byteDanceAdvertisePlan.setOptStatus(optStatus.equalsIgnoreCase("enable") ? "AD_STATUS_ENABLE" : "AD_STATUS_DISABLE");
				//更新 表 计划状态
				byteDanceAdvertisePlanService.updatePlanOrPackage(byteDanceAdvertisePlan);
				return Result.successMsg(result.getMessage(), null);
			}
			return Result.errorMsg(result.getMessage());
		}catch (Exception e){
			log.error("投放数据-更新计划状态异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}




	@ApiOperation(value="投放数据-素材维度展示", notes="投放数据-素材维度展示")
	@GetMapping(value = "/selectMaterialDailyReport")
	public Result selectMaterialDailyReport(@RequestParam("accountId") String accountId,
					@RequestParam(value = "startTime",defaultValue = "") String startTime,
					@RequestParam(value = "endTime",defaultValue = "") String endTime,
					@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
					@RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){
		try {
			return bytedanceReportMaterialDailyService.getMaterialDailyReportByAccountId(accountId,startTime,endTime,pageNum,pageSize);
		}catch (Exception e){
			log.error("投放数据-获取素材维度报表数据异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}







}
