package com.mortals.xhx.busiz.applets.web;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.busiz.applets.req.NewsReq;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.news.model.NewsCategoryQuery;
import com.mortals.xhx.module.news.model.NewsEntity;
import com.mortals.xhx.module.news.model.NewsQuery;
import com.mortals.xhx.module.news.service.NewsCategoryService;
import com.mortals.xhx.module.news.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mortals.framework.ap.SysConstains.PAGEINFO_KEY;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED_CONTENT;

/**
 * 小程序 新闻列表
 *
 * @author: zxfei
 * @date: 2023/10/7 16:57
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/news")
public class NewsApiController extends AbstractBaseController<NewsReq> {
    @Autowired
    private ParamService paramService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private NewsCategoryService newsCategoryService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private UserService userService;


    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "top", paramService.getParamBySecondOrganize("News", "top"));
        this.addDict(model, "viewNums", paramService.getParamBySecondOrganize("News", "viewNums"));
        this.addDict(model, "categoryId", newsCategoryService.find(new NewsCategoryQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName(), (o, n) -> n)));
        this.addDict(model, "deptId", deptService.find(new DeptQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getDeptName(), (o, n) -> n)));
        this.addDict(model, "createUserId", userService.find(new UserQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getRealName(), (o, n) -> n)));

    }

    /**
     * 新闻频道分类
     */
    @PostMapping(value = "categoryList")
    public Rest<Object> categoryList(){
        String busiDesc = "新闻频道";
        Rest<Object> rest = Rest.ok();
        try {
            rest.setData(newsCategoryService.find(new NewsCategoryQuery()));
        }catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }


    /**
     * 新闻列表
     */
    @PostMapping(value = "newsList")
    public Rest<Object> newsList(@RequestBody NewsReq newsReq) {
        String busiDesc = "新闻列表";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(newsReq));
        Rest<Object> rest = Rest.ok();
        Map<String, Object> model = new HashMap<>();
        Context context = this.getContext();
        if (ObjectUtils.isEmpty(context) || ObjectUtils.isEmpty(context.getUser())) {
            throw new AppException(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT);
        }
        try {
            PageInfo pageInfo = buildPageInfo(newsReq);
            NewsQuery query = new NewsQuery();

            if(!ObjectUtils.isEmpty(newsReq.getNewsCategoryId())){
               query.setCategoryId(newsReq.getNewsCategoryId());
            }

            query.setOrderColList(Arrays.asList(new OrderCol("createTime", OrderCol.DESCENDING)));
            Result<NewsEntity> result = newsService.find(query, pageInfo, context);
//            List<NewsListInfo> collect = result.getList().stream().map(item -> {
//                NewsListInfo newsListInfo = new NewsListInfo();
//                BeanUtils.copyProperties(item, newsListInfo, BeanUtil.getNullPropertyNames(item));
//                return newsListInfo;
//            }).collect(Collectors.toList());
            model.put(KEY_RESULT_DATA, result.getList());
            model.put(PAGEINFO_KEY, result.getPageInfo());
            super.parsePageInfo(model, result.getPageInfo());
            rest.setData(model);
            this.init(model, context);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }

    /**
     * 新闻详细
     */
    @PostMapping(value = "newsInfo")
    public Rest<NewsEntity> appealInfo(@RequestBody NewsReq newsReq) {
        String busiDesc = "新闻详细";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(newsReq));
        Rest<NewsEntity> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();
        Map<String, Object> model = new HashMap<>();
        try {
            if (ObjectUtils.isEmpty(newsReq.getId())) {
                throw new AppException("详细查询id不能为空!");
            }
            NewsEntity newsEntity = newsService.get(newsReq.getId(), context);
            rest.setData(newsEntity);
            this.init(model, context);
            rest.setDict(model.get("dict"));
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }

    /**
     * 新闻点赞
     */
    @PostMapping(value = "up")
    public Rest<NewsEntity> upNews(@RequestBody NewsReq newsReq) {
        String busiDesc = "新闻点赞";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(newsReq));
        Rest<NewsEntity> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();
        Map<String, Object> model = new HashMap<>();
        try {
            if (ObjectUtils.isEmpty(newsReq.getId())) {
                throw new AppException("新闻id不能为空!");
            }
            NewsEntity newsEntity = newsService.upNews(newsReq.getId(),context,1);
            rest.setData(newsEntity);
            this.init(model, context);
            rest.setDict(model.get("dict"));
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }

    /**
     * 新闻取消点赞
     */
    @PostMapping(value = "cancelUp")
    public Rest<NewsEntity> cancelUpNews(@RequestBody NewsReq newsReq) {
        String busiDesc = "新闻点赞";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(newsReq));
        Rest<NewsEntity> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();
        Map<String, Object> model = new HashMap<>();
        try {
            if (ObjectUtils.isEmpty(newsReq.getId())) {
                throw new AppException("新闻id不能为空!");
            }
            NewsEntity newsEntity = newsService.upNews(newsReq.getId(),context,-1);
            rest.setData(newsEntity);
            this.init(model, context);
            rest.setDict(model.get("dict"));
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }

    /**
     * 新闻浏览
     */
    @PostMapping(value = "view")
    public Rest<NewsEntity> viewNews(@RequestBody NewsReq newsReq) {
        String busiDesc = "新闻浏览";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(newsReq));
        Rest<NewsEntity> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();
        Map<String, Object> model = new HashMap<>();
        try {
            if (ObjectUtils.isEmpty(newsReq.getId())) {
                throw new AppException("新闻id不能为空!");
            }
            NewsEntity newsEntity = newsService.viewNews(newsReq.getId(),context);
            rest.setData(newsEntity);
            this.init(model, context);
            rest.setDict(model.get("dict"));
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }

    /**
     * 新闻分享
     */
    @PostMapping(value = "share")
    public Rest<NewsEntity> shareNews(@RequestBody NewsReq newsReq) {
        String busiDesc = "新闻分享";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(newsReq));
        Rest<NewsEntity> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();
        Map<String, Object> model = new HashMap<>();
        try {
            if (ObjectUtils.isEmpty(newsReq.getId())) {
                throw new AppException("新闻id不能为空!");
            }
            NewsEntity newsEntity = newsService.shareNews(newsReq.getId(),context);
            rest.setData(newsEntity);
            this.init(model, context);
            rest.setDict(model.get("dict"));
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }
}
