package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IFileInfoService;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.toutiao.entity.ByteDanceCustomAudience;
import cn.com.ctop.toutiao.entity.ByteDanceUserOrientationTemplate;
import cn.com.ctop.toutiao.service.IByteDanceAdvertiserDataService;
import cn.com.ctop.toutiao.service.IByteDanceCreativeService;
import cn.com.ctop.toutiao.service.IByteDanceCustomAudienceService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 头条广告主相关 2019年7月10日14:13:04
 *
 * @author 宋英豪
 */
@Slf4j
@RestController
@RequestMapping("toutiao")
public class ByteDanceAdvertiserPostController {
    @Autowired
    private IByteDanceAdvertiserDataService advertiserDataService;
    @Autowired
    private IByteDanceCreativeService creativeService;
    @Autowired
    private IFileInfoService fileInfoService;
    @Autowired
    private IByteDanceCustomAudienceService audienceService;
    @Autowired
    private ISysDictItemService sysDictItemService;

    /**
     * 1：获取广告主信息
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/info")
    public Map<String, Object> advertiserInfo(String accountId) {
        return advertiserDataService.getAdvertiserInfo(accountId);
    }

    /**
     * 2：获取广告主广告计划信息
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/plan/get")
    public Map<String, Object> advertiserPlan(String accountId, String ids) {
        return advertiserDataService.getAdvertiserPlan(accountId, ids, null);
    }

    /**
     * 3：修改广告计划信息状态
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/plan/update/status")
    public Map<String, Object> advertiserPlanUpdateStatus(String accountId, String adIds, String optStatus) {
        return advertiserDataService.advertiserPlanUpdateStatus(accountId, adIds, optStatus);
    }

    /**
     * 3：修改广告计划信息
     *
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/ad/update")
    public Map<String, Object> advertiserAdUpdate(String accountId, Long adId, String optStatus) {
        ByteDanceUserOrientationTemplate template = new ByteDanceUserOrientationTemplate();
        return advertiserDataService.advertiserAdUpdate(accountId, adId, template);
    }


    /**
     * 4：修改广告计划信息状态
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/plan/update/bid")
    public Map<String, Object> advertiserPlanUpdateBid(String accountId, String adIds, String bids) {
        return advertiserDataService.advertiserPlanUpdateBid(accountId, adIds, bids);
    }

    /**
     * 5：修改广告计划信息状态
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/plan/update/budget")
    public Map<String, Object> advertiserPlanUpdateBudget(String accountId, String adIds, String budgets) {
        return advertiserDataService.advertiserPlanUpdateBudget(accountId, adIds, budgets);
    }

    /**
     * 6：获取广告主广告预算信息
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/budget/get/")
    public Map<String, Object> advertiserBudget(String accountId) {
        return advertiserDataService.getAdvertiserBudget(accountId);
    }

    /**
     * 7：获取广告主广告组信息
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/campaign/get")
    public Map<String, Object> advertiserCampaign(String accountId, String ids) {
        return advertiserDataService.getAdvertiserCampaign(accountId, ids, null);
    }

    /**
     * 7：获取广告主广告组信息
     *
     * @param accountId 本平台广告主id
     */
    @GetMapping("/advertiser/campaign/list")
    public Map<String, Object> advertiserCampaignList(String accountId) {
        return advertiserDataService.getAdvertiserCampaignList(accountId);
    }

    /**
     * 8：获取广告主广告创意信息
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/creative/get")
    public Map<String, Object> getAdvertiserCreative(String accountId, String ids) {
        return creativeService.getAdvertiserCreative(accountId, ids, null);
    }

    /**
     * 9：修改广告创意信息状态
     * @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/update/status/")
    public Map<String, Object> advertiserCreativeUpdateStatus(String accountId, String creativeIds, String optStatus) {
        return creativeService.advertiserCreativeUpdateStatus(accountId, creativeIds, optStatus);
    }

    /**
     * 10：获取广告主广告创意素材信息
     * @param accountId 本平台广告主id
     * @param creativeIds 广告创意id
     */
    @RequestMapping("/advertiser/creative/material/read")
    public Map<String, Object> advertiserCreativeMaterial(String accountId, String creativeIds) {
        return advertiserDataService.getAdvertiserCreativeMaterial(accountId, creativeIds);
    }

    /**
     * 12：广告组更新状态信息 @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/campaign/update/status")
    public Map<String, Object> advertiserCampaignUpdateStatus(String accountId, String campaignIds, String optStatus) {
        return advertiserDataService.advertiserCampaignUpdateStatus(accountId, campaignIds, optStatus);
    }

    /**
     * 13：广告组更新信息 @param accountId 本平台广告主id
     */
    @RequestMapping("/advertiser/campaign/update")
    public Map<String, Object> advertiserCampaignUpdate(String accountId, Long campaignId, String budgetMode, Integer budget, String campaignName) {
        return advertiserDataService.advertiserCampaignUpdate(accountId, campaignId, budgetMode, budget, campaignName);
    }

    /**
     * 14：获取人群包信息
     */
    @RequestMapping("/advertiser/custom/audience/select")
    public Map<String, Object> customAudienceSelect(String accountId) {
        return advertiserDataService.advertiserCustomAudienceSelect(accountId);
    }

    /**
     * 14：获取流量包数据
     */
    @RequestMapping("/advertiser/custom/package/get")
    public Map<String, Object> flowPackageGet(String accountId) {
        return advertiserDataService.flowPackageGet(accountId);
    }


    /**
     * 15：上传视频信息
     *
     * @param accountId 本平台广告主id
     * @
     */
    @RequestMapping("/advertiser/video/add")
    public Map<String, Object> advertiserVideoAdd(String accountId, String videoUrl) {
        return fileInfoService.uploadVideoToBytedance(accountId, videoUrl);
    }

    /**
     * 15：上传图片信息
     *
     * @param accountId 本平台广告主id
     * @
     */
    @RequestMapping("/advertiser/image/add")
    public Map<String, Object> advertiserImageAdd(String accountId, String imageUrl) {
        return fileInfoService.uploadImageToBytedance(accountId, imageUrl);
    }

    /**
     * @param audience
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     * @功能：查询字典数据
     */
    @RequestMapping(value = "/audience/list", method = RequestMethod.GET)
    public Result<IPage<ByteDanceCustomAudience>> audiencePageList(ByteDanceCustomAudience audience, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                   @RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize, HttpServletRequest req) {
        Result<IPage<ByteDanceCustomAudience>> result = new Result<>();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        audience.setAdvertiserId(user.getId());
        QueryWrapper<ByteDanceCustomAudience> queryWrapper = QueryGenerator.initQueryWrapper(audience, req.getParameterMap());
        queryWrapper.orderByAsc("sort_order");
        Page<ByteDanceCustomAudience> page = new Page<>(pageNo, pageSize);
        IPage<ByteDanceCustomAudience> pageList = audienceService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * @param sysDictItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     * @功能：查询字典数据
     */
    @RequestMapping(value = "dictitem/list", method = RequestMethod.GET)
    public Result<IPage<SysDictItem>> dictitemPageList(SysDictItem sysDictItem, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysDictItem>> result = new Result<>();
        QueryWrapper<SysDictItem> queryWrapper = QueryGenerator.initQueryWrapper(sysDictItem, req.getParameterMap());
        queryWrapper.orderByAsc("sort_order");
        Page<SysDictItem> page = new Page<>(pageNo, pageSize);
        IPage<SysDictItem> pageList = sysDictItemService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @GetMapping("loadAllData")
    public Map<String, Object> loadAllData() {
        Map<String, Object> result = new HashMap<>();
        List<CtopOauthToken> kuaishouTokens = tokenService.getTokenListByType(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
        kuaishouInterfaceService.loadAllKuaishouData(kuaishouTokens);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
        return result;
    }

    @GetMapping("loadSingleData")
    public Map<String, Object> loadSingleData(Long accountId) {
        Map<String, Object> result = new HashMap<>();
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId + "");
        if (null != token && token.getMediaId() == CtopAdConstant.PLATFORM_TYPE_KUAISHOU) {
            kuaishouInterfaceService.loadKuaishouDataSingle(token);
        } else {
            log.info("token异常");
        }
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
        return result;
    }

    @GetMapping("loadData")
    public Map<String, Object> loadData() {
        Map<String, Object> result = new HashMap<>();
        try {
            kuaishouInterfaceService.loadData();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
        return result;
    }

    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;
}
