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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouActionBarText;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCreative;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouActionBarTextService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouCreativeService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
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 lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@RestController
@RequestMapping("/MaterialRefuse/")
public class MaterialRefuseController {
    @Autowired
    private CtopOauthTokenMapper oauthTokenMapper;
    @Autowired
    private IKuaiShouUpdateService updateService;
    @Autowired
    private IKuaiShouCreativeService creativeService;
    @Autowired
    private IKuaiShouActionBarTextService actionBarTextService;
    static ExecutorService executorService = Executors.newFixedThreadPool(15);


    @GetMapping(value = "getRefuseCreative")
    public Result<IPage<KuaiShouCreative>> getRefuseCreative(KuaiShouCreative creative,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                             HttpServletRequest req) {
        Result<IPage<KuaiShouCreative>> result = new Result<>();
        try {
            String creativeName = creative.getCreativeName();
            creative.setCreativeName(null);
            QueryWrapper<KuaiShouCreative> queryWrapper = QueryGenerator.initQueryWrapper(creative, req.getParameterMap());
            queryWrapper.eq("status", 42);
            if (!Check.isNull(creativeName)) {
                queryWrapper.like("creative_name", creativeName);
            }
            queryWrapper.orderByDesc("creative_create_time");
            Page<KuaiShouCreative> page = new Page<KuaiShouCreative>(pageNo, pageSize);
            IPage<KuaiShouCreative> pageList = creativeService.page(page, queryWrapper);
            result.setSuccess(true);
            result.setResult(pageList);

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


    @GetMapping(value = "getAllActionBarText")
    public Result<List<KuaiShouActionBarText>> getAllActionBarText() {
        Result<List<KuaiShouActionBarText>> result = new Result<>();
        try {
            //  QueryWrapper<KuaiShouActionBarText> actionBarTextQueryWrapper = new QueryWrapper<>();
            List<KuaiShouActionBarText> list = actionBarTextService.list();
            result.setResult(list);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    @GetMapping(value = "syncCreative")
    public Result<Boolean> syncCreative(Long accountId, Long campaignId) {
        Result<Boolean> result = new Result<>();
        try {
            QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account_id", accountId);
            queryWrapper.eq("media_id", 2);
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("limit 1");
            CtopOauthToken ctopOauthToken = oauthTokenMapper.selectOne(queryWrapper);
            if (Check.isNull(ctopOauthToken)) {
                throw new Exception("未获取到授权信息");
            }
            creativeService.syncCreative(accountId, ctopOauthToken.getAccessToken(), campaignId, 1);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @PostMapping(value = "updateCreative")
    public Result<Boolean> updateCreative(@RequestBody JSONObject jsonObject) {
        Result<Boolean> result = new Result<>();
        if (Check.isNull(jsonObject)) {
            result.setSuccess(false);
            result.setMessage("入参为空");
            return result;
        }

        Long accountId = jsonObject.getLong("accountId");
        QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("media_id", 2);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 1");
        CtopOauthToken ctopOauthToken = oauthTokenMapper.selectOne(queryWrapper);
        if (Check.isNull(ctopOauthToken)) {
            result.setSuccess(false);
            result.setMessage("未获取到授权信息");
            return result;
        }

        Map<String, Object> creativeMap = updateService.updateCreative(ctopOauthToken.getAccessToken(), accountId, jsonObject);
        if (Check.isNullMap(creativeMap)) {
            result.setSuccess(false);
            result.setMessage("修改失败，返回为空");
            return result;
        }

        if ((Integer) creativeMap.get("code") != 0) {
            result.setSuccess(false);
            result.setMessage((String) creativeMap.get("message"));
            return result;
        }
        result.setSuccess(true);

        return result;
    }


    @PostMapping(value = "batchUpdateCreative")
    public Result<Boolean> batchUpdateCreative(@RequestBody JSONObject jsonObject) {

        Result<Boolean> result = new Result<>();
        if (Check.isNull(jsonObject)) {
            result.setSuccess(false);
            result.setMessage("入参为空");
            return result;
        }

        Long accountId = jsonObject.getLong("accountId");
        QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("media_id", 2);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 1");
        CtopOauthToken ctopOauthToken = oauthTokenMapper.selectOne(queryWrapper);
        if (Check.isNull(ctopOauthToken)) {
            result.setSuccess(false);
            result.setMessage("未获取到授权信息");
            return result;
        }

        Integer type = jsonObject.getInteger("type");
        if (Check.isNull(type)) {
            result.setSuccess(false);
            result.setMessage("请选择修改类型");
            return result;
        }


        JSONArray creativeArr = jsonObject.getJSONArray("creativeArr");
        if (Check.isNull(creativeArr)) {
            result.setSuccess(false);
            result.setMessage("请选择修改创意");
            return result;
        }


        for (int i = 0; i < creativeArr.size(); i++) {
            JSONObject creativeJson = creativeArr.getJSONObject(i);
            if (!Check.isNull(creativeJson)) {
                Long creativeId = creativeJson.getLong("creativeId");
                JSONObject requestJson = new JSONObject();
                requestJson.put("creativeId", creativeId);
                if (type == 0) {  // 替换修改广告语
                    String description = creativeJson.getString("description");
                    requestJson.put("description", creativeService.convertMoString(description));
                } else if (type == 1) { // 替换广告语
                    String updateDescription = jsonObject.getString("updateDescription");
                    String updateActionBarText = jsonObject.getString("updateActionBarText");
                    if (Check.isNull(updateDescription) && Check.isNull(updateActionBarText)) {
                        result.setSuccess(false);
                        result.setMessage("广告语和行动号召按钮不能同时为空");
                        return result;
                    }
                    if (!Check.isNull(updateDescription)) {
                        requestJson.put("description", updateDescription);
                    }
                    if (!Check.isNull(updateActionBarText)) {
                        requestJson.put("actionBarText", updateActionBarText);
                    }

                }

                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        Map<String, Object> creativeMap = updateService.updateCreative(ctopOauthToken.getAccessToken(), accountId, requestJson);
                        Integer code = (Integer) creativeMap.get("code");
                        if (code == 0) {
                            log.info("拒审重提成功,accountId:{},creativeId:{}", accountId, creativeId);
                        } else {
                            log.info("拒审重提失败,accountId:{},creativeId:{}", accountId, creativeId);
                        }
                    }
                });


            }

        }

        result.setSuccess(true);
        result.setMessage("异步执行中，请稍后查看");
        return result;
    }


}
