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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.toutiao.modules.adlab.entity.CtopAdlabProjectDetail;
import cn.com.ctop.toutiao.modules.adlab.service.ICtopAdlabProjectDetailService;
import cn.com.ctop.toutiao.modules.adlab.service.IUpdateProjectService;
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 org.jeecg.common.api.vo.Result;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 投放管家项目详情
 */
@Slf4j
@RestController
@RequestMapping("/adlab/ctopAdlabProjectDetail")
public class CtopAdlabProjectDetailController {

    @Autowired
    private ICtopAdlabProjectDetailService ctopAdlabProjectDetailService;

    @Autowired
    private IUpdateProjectService updateProjectService;

    @Autowired
    private ICtopOauthTokenService oauthTokenService;

    /**
     * 分页列表查询
     */
    @PostMapping(value = "/list")
    public Result<IPage<CtopAdlabProjectDetail>> queryPageList(@RequestBody JSONObject requestBody,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                               HttpServletRequest req) {
        Result<IPage<CtopAdlabProjectDetail>> result = new Result<>();
        QueryWrapper<CtopAdlabProjectDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", requestBody.getString("userId"));
        if (!requestBody.getString("name").isEmpty()) {
            queryWrapper.like("name", requestBody.getString("name"));
        }
        if (!requestBody.getJSONArray("accountIds").isEmpty()) {
            queryWrapper.in("account_id", requestBody.getJSONArray("accountIds"));
        }
        if (!"".equals(requestBody.getString("optStatus"))) {
            queryWrapper.eq("opt_status", requestBody.getString("optStatus"));
        }
        if (!requestBody.getJSONArray("createTime").isEmpty()) {
            queryWrapper.ge("create_time", requestBody.getJSONArray("createTime").get(0));
            queryWrapper.le("create_time", requestBody.getJSONArray("createTime").get(1));
        }
        Page<CtopAdlabProjectDetail> page = new Page<>(pageNo, pageSize);
        IPage<CtopAdlabProjectDetail> pageList = ctopAdlabProjectDetailService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     */
    @PostMapping(value = "/add")
    public Result<CtopAdlabProjectDetail> add(@RequestBody CtopAdlabProjectDetail ctopAdlabProjectDetail) {
        Result<CtopAdlabProjectDetail> result = new Result<>();
        try {
            ctopAdlabProjectDetailService.save(ctopAdlabProjectDetail);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     */
    @PostMapping(value = "/edit")
    public Result<CtopAdlabProjectDetail> edit(@RequestBody JSONArray requestBody) {
        Result<CtopAdlabProjectDetail> result = new Result<>();
        if (requestBody.isEmpty()) {
            result.error500("请选择数据");
        } else {
            CtopAdlabProjectDetail ctopAdlabProjectDetail = new CtopAdlabProjectDetail();
            ctopAdlabProjectDetail.setOptStatus((String) ((Map) requestBody.get(0)).get("optStatus"));
            requestBody.forEach(it -> {
                Map<String, Object> temp = (Map<String, Object>) it;
                //先更新头条后台数据
                JSONObject repo = updateProjectService.updateGroupStatus(oauthTokenService.getTokenByAccountId((Long) temp.get("accountId")), temp);
                List<JSONObject> params = new ArrayList<>();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("accountId", temp.get("accountId"));
                jsonObject.put("groupId", temp.get("groupId"));
                jsonObject.put("userId", temp.get("userId"));
                params.add(jsonObject);
                if (repo.getInteger("code") == 0) {
                    if ("DELETED".equals(((Map<String, Object>) it).get("optStatus"))) {
                    	ctopAdlabProjectDetailService.removeById((Long) temp.get("groupId"));
                    } else {
                        ctopAdlabProjectDetailService.putStorage(params);
                    }
                } else {
                    result.error500(repo.getString("message"));
                }
            });
        }
        return result;
    }

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

    /**
     * 批量删除
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<CtopAdlabProjectDetail> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<CtopAdlabProjectDetail> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.ctopAdlabProjectDetailService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     */
    @GetMapping(value = "/queryById")
    public Result<CtopAdlabProjectDetail> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<CtopAdlabProjectDetail> result = new Result<>();
        CtopAdlabProjectDetail ctopAdlabProjectDetail = ctopAdlabProjectDetailService.getById(id);
        if (ctopAdlabProjectDetail == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(ctopAdlabProjectDetail);
            result.setSuccess(true);
        }
        return result;
    }
}
