package cn.com.ctop.toutiao.modules.material.controller;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.StringUtils;
import cn.com.ctop.toutiao.modules.material.entity.ByteDanceAdvertisePlan;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceAdvertisePlanService;
import com.alibaba.fastjson.JSONArray;
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.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 今日头条广告计划信息
 */
@Slf4j
@RestController
@RequestMapping("/ctop/byteDanceAdvertisePlan")
public class ByteDanceAdvertisePlanController {

    @Autowired
    ICtopOauthTokenService ctopOauthTokenService;

    @Autowired
    private IByteDanceAdvertisePlanService byteDanceAdvertisePlanService;

    /**
     * 分页列表查询
     */
    @GetMapping(value = "/list")
    public Result<IPage<ByteDanceAdvertisePlan>> queryPageList(ByteDanceAdvertisePlan byteDanceAdvertisePlan,
                                                               @RequestParam(name = "status", defaultValue = "") String status,
                                                               @RequestParam(name = "startDate", defaultValue = "") String startDate,
                                                               @RequestParam(name = "endDate", defaultValue = "") String endDate,
                                                               @RequestParam(name = "accountId", defaultValue = "") String accountId,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                               HttpServletRequest req) {
        Result<IPage<ByteDanceAdvertisePlan>> result = new Result<>();
        if (!accountId.isEmpty()) {
            byteDanceAdvertisePlan.setAccountId(accountId);
        }
        QueryWrapper<ByteDanceAdvertisePlan> queryWrapper = QueryGenerator.initQueryWrapper(byteDanceAdvertisePlan, req.getParameterMap());
        if (status != null && !"".equals(status.trim())) {
            queryWrapper.eq("opt_status", "AD_STATUS_" + status);
        }
        if (null != startDate && !"".equals(startDate)) {
            queryWrapper.ge("ad_create_time", startDate + " 00:00:00");
        }
        if (null != endDate && !"".equals(endDate)) {
            queryWrapper.le("ad_create_time", endDate + " 11:59:59");
        }
        queryWrapper.ne("opt_status", "AD_STATUS_DELETE");
        Page<ByteDanceAdvertisePlan> page = new Page<>(pageNo, pageSize);
        IPage<ByteDanceAdvertisePlan> pageList = byteDanceAdvertisePlanService.page(page, queryWrapper);
        //处理计划投放状态
        if (!pageList.getRecords().isEmpty()) {
            pageList.getRecords().forEach(it -> {
                if ("AD_STATUS_ENABLE".equals(it.getOptStatus())) {
                    it.setPlanStatus(true);
                } else {
                    it.setPlanStatus(false);
                }
            });
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     */
    @PostMapping(value = "/add")
    public Result<List<ByteDanceAdvertisePlan>> add(@RequestBody ByteDanceAdvertisePlan byteDanceAdvertisePlan) {

        Result<List<ByteDanceAdvertisePlan>> result = new Result<>();
        List<String> names = (List) byteDanceAdvertisePlan.getNames();
        String landingType = byteDanceAdvertisePlan.getLandingType();
        List<ByteDanceAdvertisePlan> byteDanceAdvertisePlanList = new ArrayList<>();
        try {
            names.forEach(name -> {
                byteDanceAdvertisePlan.setName(name);
                Map<String, Object> advertiserPlan = byteDanceAdvertisePlanService.createAdvertiserPlan(ctopOauthTokenService.getTokenByAccountId(Long.valueOf(byteDanceAdvertisePlan.getAccountId())), landingType, byteDanceAdvertisePlan);
                if (advertiserPlan.get("code").equals(0)) {
                    byteDanceAdvertisePlan.setId(((ByteDanceAdvertisePlan) advertiserPlan.get("data")).getId());
                    byteDanceAdvertisePlan.setAdCreateTime(DateUtils.now());
                    byteDanceAdvertisePlanService.save((ByteDanceAdvertisePlan) advertiserPlan.get("data"));
                    byteDanceAdvertisePlanList.add(byteDanceAdvertisePlanService.getById(((ByteDanceAdvertisePlan) advertiserPlan.get("data")).getId()));
                } else {
                    result.setCode(-200);
                    result.setMessage(advertiserPlan.get("message").toString());
                }
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        result.setResult(byteDanceAdvertisePlanList);
        return result;
    }

    /**
     * 编辑
     */
    @PostMapping(value = "/edit")
    public Result<ByteDanceAdvertisePlan> edit(@RequestBody ByteDanceAdvertisePlan byteDanceAdvertisePlan) {
        Result<ByteDanceAdvertisePlan> result = new Result<>();
        String landingType = byteDanceAdvertisePlan.getLandingType();
        Map<String, Object> map = byteDanceAdvertisePlanService.updateAdvertiserPlan(ctopOauthTokenService.getTokenByAccountId(Long.valueOf(byteDanceAdvertisePlan.getAccountId())), landingType, byteDanceAdvertisePlan);
        if (!map.get("code").equals(0)) {
            result.error500(map.get("message").toString());
        } else {
            boolean ok = byteDanceAdvertisePlanService.updateById(byteDanceAdvertisePlan);
            if (ok) {
                result.success("修改成功!");
            } else {
                result.error500("未知错误");
            }
        }
        return result;
    }

    @PostMapping(value = "/batchEdit/{operate}")
    public Result<List<ByteDanceAdvertisePlan>> edit(@RequestBody List<ByteDanceAdvertisePlan> byteDanceAdvertisePlanList,
                                                     @PathVariable String operate) {
        Result<List<ByteDanceAdvertisePlan>> result = new Result<>();
        if (byteDanceAdvertisePlanList.isEmpty()) {
            log.error("未选择数据");
            result.error500("请选择数据");
        }
        CtopOauthToken token = ctopOauthTokenService.getTokenByAccountId(Long.valueOf(byteDanceAdvertisePlanList.get(0).getAccountId()));
        try {
            if ("status".equals(operate)) {
                JSONArray adIds = new JSONArray();
                String optStatus = byteDanceAdvertisePlanList.get(0).getOptStatus();
                byteDanceAdvertisePlanList.forEach(it -> {
                    adIds.add(it.getId());
                });
                Map<String, Object> map = byteDanceAdvertisePlanService.updateAdvertiserPlanStatus(token, adIds, optStatus);
                if (!map.get("code").equals(0)) {
                    result.error500(map.get("message").toString());
                    return result;
                }
            } else if ("bid".equals(operate)) {
                JSONArray adIds = new JSONArray();
                JSONArray bids = new JSONArray();
                byteDanceAdvertisePlanList.forEach(it -> {
                    adIds.add(it.getId());
                    bids.add(it.getBid());
                });
                Map<String, Object> map = byteDanceAdvertisePlanService.updateAdvertiserPlanBid(token, adIds, bids);
                if (!map.get("code").equals(0)) {
                    result.error500(map.get("message").toString());
                    return result;
                }
            } else if ("budget".equals(operate)) {
                JSONArray adIds = new JSONArray();
                JSONArray budgets = new JSONArray();
                byteDanceAdvertisePlanList.forEach(it -> {
                    adIds.add(it.getId());
                    budgets.add(it.getBudget());
                });
                Map<String, Object> map = byteDanceAdvertisePlanService.updateAdvertiserPlanBudget(token, adIds, budgets);
                if (!map.get("code").equals(0)) {
                    result.error500(map.get("message").toString());
                    return result;
                }
            }
        } catch (Exception e) {
            log.error("头条批量更新接口错误");
        }
        byteDanceAdvertisePlanList.forEach(it -> {
            boolean ok = byteDanceAdvertisePlanService.updateById(it);
            if (ok) {
                result.success("修改成功!");
            } else {
                result.error500("未知错误");
            }
        });
        result.setResult(byteDanceAdvertisePlanList);
        return result;
    }

    /**
     * 通过id删除
     */
    @PostMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            byteDanceAdvertisePlanService.removeById(id);
        } catch (Exception e) {
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     */
    @PostMapping(value = "/deleteBatch")
    public Result<ByteDanceAdvertisePlan> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<ByteDanceAdvertisePlan> result = new Result<>();

        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.byteDanceAdvertisePlanService.removeByIds(Arrays.asList(ids.split(StringUtils.COMMA)));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     */
    @GetMapping(value = "/queryById")
    public Result<ByteDanceAdvertisePlan> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<ByteDanceAdvertisePlan> result = new Result<>();
        ByteDanceAdvertisePlan byteDanceAdvertisePlan = byteDanceAdvertisePlanService.getById(id);
        if (byteDanceAdvertisePlan == null) {
            result.error500("未找到数据");
        } else {
            result.setResult(byteDanceAdvertisePlan);
            result.setSuccess(true);
        }
        return result;
    }
}
