package com.gxwebsoft.cms.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.date.DateUtil;
import com.gxwebsoft.cms.entity.Article;
import com.gxwebsoft.cms.service.ArticleService;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.cms.service.ArticleCheckService;
import com.gxwebsoft.cms.entity.ArticleCheck;
import com.gxwebsoft.cms.param.ArticleCheckParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.controller.WeChatController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 控制器
 *
 * @author 科技小王子
 * @since 2024-11-19 22:01:03
 */
@Api(tags = "管理")
@RestController
@RequestMapping("/api/cms/article-check")
public class ArticleCheckController extends BaseController {
    @Resource
    private ArticleCheckService articleCheckService;
    @Resource
    private ArticleService articleService;

    @Autowired
    private WeChatController weChatController;
    @Autowired
    private RequestUtil requestUtil;

    @ApiOperation("分页查询")
    @GetMapping("/page")
    public ApiResult<PageResult<ArticleCheck>> page(ArticleCheckParam param) {
        // 使用关联查询
        return success(articleCheckService.pageRel(param));
    }

    @ApiOperation("查询全部")
    @GetMapping()
    public ApiResult<List<ArticleCheck>> list() {
        ArticleCheckParam param = new ArticleCheckParam();
        param.setUserId(getLoginUserId());
        param.setStatus(0);
        // 使用关联查询
        List<ArticleCheck> list = articleCheckService.listRel(param);
        for (ArticleCheck articleCheck : list) {
            articleCheck.setArticle(articleService.getByIdRel(articleCheck.getArticleId()));
        }
        return success(list);
    }

    @PreAuthorize("hasAuthority('cms:articleCheck:list')")
    @ApiOperation("根据id查询")
    @GetMapping("/{id}")
    public ApiResult<ArticleCheck> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(articleCheckService.getByIdRel(id));
    }

    @ApiOperation("添加")
    @PostMapping()
    public ApiResult<?> save(@RequestBody ArticleCheck articleCheck) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            articleCheck.setUserId(loginUser.getUserId());
        }
        if (articleCheckService.save(articleCheck)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("修改")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ArticleCheck articleCheck, HttpServletRequest request) throws WxErrorException {
        if (articleCheckService.updateById(articleCheck)) {
            ArticleCheck articleCheck1 = articleCheckService.getByIdRel(articleCheck.getId());
            List<ArticleCheck> articleCheckList = articleCheckService.listByArticleId(articleCheck1.getArticleId());
            Article article = articleService.getById(articleCheck1.getArticleId());
            boolean sendMsg = false;
            String result = "";
            if (articleCheck.getStatus().equals(2)) {
                article.setStatus(2);
                articleService.updateById(article);
                sendMsg = true;
                result = "驳回";
            } else if (articleCheck.getStatus().equals(1)) {
                int passNum = 0;
                for (ArticleCheck articleCheck2 : articleCheckList) {
                    if (articleCheck2.getStatus().equals(1)) {
                        passNum++;
                    }
                }
                if (passNum > 0) {
                    article.setStatus(0);
                    articleService.updateById(article);
                    sendMsg = true;
                    result = "通过";
                }
            }
            if (sendMsg) {
                requestUtil.setTenantId(getTenantId().toString());
                requestUtil.setAccessToken(JwtUtil.getAccessToken(request));
                User user = requestUtil.getByUserId(article.getUserId());
                if (user != null) {
                    List<WxMaSubscribeMessage.MsgData> data = new ArrayList<>();
                    data.add(new WxMaSubscribeMessage.MsgData("thing5", article.getTitle()));
                    data.add(new WxMaSubscribeMessage.MsgData("thing2", result));
                    data.add(new WxMaSubscribeMessage.MsgData("time4", DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss")));
                    weChatController.sendMessage(user.getOpenid(), "NLnexmnhiVl_e4fiC6OwfbTlpssAuvXWoPNwITyTcC4", "package/user/myTv",
                            data);
                }
            }
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (articleCheckService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("批量添加")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<ArticleCheck> list) {
        if (articleCheckService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("批量修改")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<ArticleCheck> batchParam) {
        if (batchParam.update(articleCheckService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("批量删除")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (articleCheckService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
