package com.bohuikeji.delivery.backstage.controller.api.share;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bohuikeji.delivery.backstage.entity.TNews;
import com.bohuikeji.delivery.backstage.service.ITNewsService;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.back.DataPage;
import com.bohuikeji.frame.module.admin.entity.configure.PageConf;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Collection;
import java.util.List;

/**
 * 信息发布
 */
@Slf4j
@Api(tags = {"信息消息相关接口"})
@RestController
@RequestMapping("/api/news")
public class NewsApi extends ApiController {
    // 消息推送的队列名
    @Value("${tools.queue-pix}")
    String pix_new;

    @Autowired
    ITNewsService newsService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @ApiOperation("推送消息")
    @PostMapping("/addNews")
    public APIEntity save(@RequestBody TNews tNews){
        /*  发送到消息队列 */
        rabbitTemplate.convertAndSend(pix_new+".news",tNews);
        return APIEntity.success();
    }
    /**
     * 客户下单所有骑手会接收到消息
     * 派送员App消息列表
     * @return
     */
    @ApiOperation("客户下单所有骑手会接收到消息/派送员App接受消息列表")
    @GetMapping("/courierOrNewsAll")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})

    public APIEntity<IPage<TNews>> courierNewsAll(DataPage<TNews> page){
        return APIEntity.success(newsService.page(page,new QueryWrapper<TNews>().eq("message_cate_id",0).eq("message_identifier","tcourier")));
    }

    /**
     * 平台/加盟商发布消息需要全部客户查看
     * 客户App接收消息列表
     * @return
     */
    @ApiOperation("平台/加盟商发布消息需要全部客户查看/客户App接受消息列表")
    @GetMapping("/customerOrNewsAll")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    public APIEntity<List<TNews>> customerNewsAll(){
        return APIEntity.success(newsService.list(new QueryWrapper<TNews>().eq("message_cate_id",0).eq("message_identifier","tCustomer")));
    }


    /**
     *
     * 未读取消息数量
     * @return
     */
    @ApiOperation("未读取消息数量")
    @GetMapping("/get/news/num")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="tableName",value="端名（t_courier、t_customer）",dataType="String", paramType = "query",example="",required=true)})
    public APIEntity getNewsNum(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String tableName){
        if(StringUtils.isBlank(tableName)){
            return APIEntity.fail("需要查询的端名不能为空，请联系管理园");
        }
        Integer newCunt = newsService.count(new QueryWrapper<TNews>().orderByDesc("create_time")
                        .eq("publish_model",tableName).eq("receive_user_id",id).eq("news_type",1).eq("news_read",false));
        return APIEntity.success(newCunt);
    }

    /**
     *
     * 客户App消息列表
     * @return
     */
    @ApiOperation("客户App消息列表")
    @GetMapping("/getCustomerId")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="customerId",value="客户登陆id",dataType="Integer", paramType = "query")})
    public APIEntity getCustomerId(@RequestAttribute("JwtUserId") Integer id,DataPage page){
        /* 获得表名 */
        String tableName = "t_customer";
        page = (DataPage) newsService.page(page,new QueryWrapper<TNews>().orderByDesc("create_time")
                .eq("publish_model",tableName).eq("receive_user_id",id));
        return APIEntity.success(page);
    }

    /**
     *
     * 派送员App消息列表
     * @return
     */
    @ApiOperation("派送员App消息列表")
    @GetMapping("/getCourierId")
    public APIEntity getCourierId(@RequestAttribute("JwtUserId") Integer id,DataPage page){
        /* 获得表名 */
        String tableName = "t_courier";
        page = (DataPage) newsService.page(page,new QueryWrapper<TNews>().orderByDesc("create_time")
                .eq("publish_model",tableName).eq("receive_user_id",id).eq("news_type",1)
        );
        return APIEntity.success(page);
    }

    /**
     * 未读取的消息改为已读状态
     * @param newsList
     * @return
     */
   /* @PostMapping("/update/isRead")
    @ApiOperation("信息改为已读状态")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="newsList",value="新闻信息id",dataType="List", paramType = "query")})
    public APIEntity getCourierId(@RequestBody List<TNews> newsList){
        for (TNews i : newsList){
            i.setNewsRead(true);
        }
        newsService.updateBatchById(newsList);
        return APIEntity.success();
    }*/

    /**
     * 全部已读
     * @param id
     * @return
     */
    @GetMapping("/update/news/true")
    @ApiOperation("全部已读")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="tableName",value="端名（t_courier、t_customer）",dataType="String", paramType = "query",example="",required=true)})
    public APIEntity updateNewTrue(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String tableName){
        log.info("操作表的名称：{}",tableName);
        if(StringUtils.isBlank(tableName)){
            return APIEntity.fail("需要查询的端名不能为空，请联系管理园");
        }
        List<TNews> tNews = newsService.list(new QueryWrapper<TNews>().eq("publish_model",tableName).eq("receive_user_id",id).eq("news_type",1).eq("news_read",false));
        if(tNews.size()<1){
            return APIEntity.success("已读成功");
        }
        for (TNews i : tNews){
            newsService.updateById(i.setNewsRead(true));
        }
        return APIEntity.success("已读成功");
    }

    /**
     * 删除全部消息
     * @param id
     * @return
     */
    @PostMapping("/del/news")
    @ApiOperation("删除全部消息")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="tableName",value="端名（t_courier、t_customer）",dataType="String", paramType = "query",example="",required=true)})
    public APIEntity delNews(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String tableName){
        newsService.removeByIds(newsService.list(new QueryWrapper<TNews>().eq("publish_model",tableName).eq("receive_user_id",id)));
        return APIEntity.success("清除成功");
    }

    /**
     * 删除单个消息
     * @param id
     * @return
     */
    @PostMapping("/del/new")
    @ApiOperation("删除单个消息")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="tableName",value="端名（t_courier、t_customer）",dataType="String", paramType = "query",example="",required=true),
            @ApiImplicitParam(name="newsId",value="消息Id",dataType="String", paramType = "query",example="",required=true)})
    public APIEntity delNew(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String tableName,Integer newsId){
        newsService.removeByIds(newsService.list(new QueryWrapper<TNews>().eq("publish_model",tableName).eq("receive_user_id",id).eq("news_id",newsId)));
        return APIEntity.success("清除成功");
    }

    /**
     *
     * 派送员App通知公告列表
     * @return
     */
    @ApiOperation("派送员App通知公告列表")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount","id"})
    @GetMapping("/getNews")
    public APIEntity getNews(@RequestAttribute("JwtUserId") Integer id,DataPage page){
        System.out.println("登陆用户："+id);
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@:[{}]",id);
        /*System.out.println("登陆用户："+id);
        List<TNews> tNews = newsService.list(new QueryWrapper<TNews>().eq("receive_user_id",id).eq("news_type",2).eq("publish_type",1).eq("publish_model","t_courier"));
        if(tNews != null){
            System.out.println("登陆用户的公告通知："+tNews);
            page.setRecords(tNews);
        }*/
        page = (DataPage) newsService.page(page,new QueryWrapper<TNews>()
                .eq("publish_type",2)
                .eq("news_type",2)
                .eq("publish_model","t_courier")
                .orderByDesc("create_time").or()
                .eq("receive_user_id",id)
                .eq("news_type",2)
                .eq("publish_type",1)
                .eq("publish_model","t_courier"));
        return APIEntity.success(page);
    }


    /**
     * 根据消息id查看消息详情
     * @return
     */
    @ApiOperation("根据消息id查看消息详情")
    @GetMapping("/seeNew")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="newsId",value="消息id",dataType="Integer", paramType = "query")})
    public APIEntity<TNews> seeNew(Integer newsId){
        TNews tNews = newsService.getOne(new QueryWrapper<TNews>().eq("news_id",newsId));
        if(tNews != null){
            //tNews.setStatus("已查看");
            newsService.updateById(tNews);
        }
        return APIEntity.success(tNews);
    }

    /**
     * 判断消息是否已读
     * @return
     */
    @ApiOperation("判断消息是否已读")
    @GetMapping("/getIsRead")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="courierId",value="派送员id",dataType="Integer", paramType = "query")})
    public APIEntity<Boolean> getIsRead(Integer courierId){
        List<TNews> list = newsService.list(new QueryWrapper<TNews>().eq("receive_user_id",courierId));
        for (TNews i : list){
            boolean isRead = i.getNewsRead();
            if (!isRead){
               return APIEntity.success(true);
            }
        }
        return APIEntity.success(false);
    }

    /**
     * 生成消息配置文件
     * @return
     */
    @ApiOperation("生成消息配置文件")
    @GetMapping("/getConfig")
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    public APIEntity getconfig(){
        return APIEntity.success(PageConf.getPageConf(TNews.class));
    }


}
