package cn.iocoder.yudao.module.inspection.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.db.TenantBaseDO;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.github.pagehelper.PageHelper;
import cn.iocoder.yudao.module.core.controller.BaseController;
import cn.iocoder.yudao.module.inspection.entity.InspectionNews;
import cn.iocoder.yudao.module.inspection.entity.InspectionNewsComment;
import cn.iocoder.yudao.module.inspection.service.IInspectionNewsCommentService;
import cn.iocoder.yudao.module.inspection.service.IInspectionNewsService;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import cn.iocoder.yudao.module.shop.service.IShopMallPartnersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin-api/appInspection/news")
public class AppNewsController extends BaseController {
    @Autowired
    private IInspectionNewsService inspectionNewsService;
    @Autowired
    private IInspectionNewsCommentService commentService;
    @Autowired
    private AdminUserApi sysUserService;
    @Autowired
    private DeptApi deptService;
    @Autowired
    private IShopMallPartnersService partnersService;
    @Autowired
    private DictDataService dictTypeService;
    @Resource
    private RoleService roleService;
    @Resource
    private PermissionApi permissionApi;

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/editType")
    public CommonResult editType()
    {
        List<DictDataDO> data = dictTypeService.getDictDataListByDictType("inspection_hygg");
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<DictDataDO>();
        }
        //获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        List<Long> roleIds = permissionApi.getRoleIdsByUserId(loginUser.getId());
        List<RoleDO> roleList = roleService.getRoleList(roleIds);
        List<String> roleKeys = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());
        if (roleKeys.contains("jcgf")){
            data = data.stream().filter(it->{
                return it.getValue().equals("zflm")||it.getValue().equals("jcztz");
            }).collect(Collectors.toList());
        }else if (roleKeys.contains("jcshop")){
            data = data.stream().filter(it->{
                return it.getValue().equals("jczgg");
            }).collect(Collectors.toList());
        }
        return success(data);
    }
    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/listType")
    public CommonResult listType()
    {
        List<DictDataDO> data = dictTypeService.getDictDataListByDictType("inspection_hygg");
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<DictDataDO>();
        }
        data = data.stream().filter(it->{
            return !it.getValue().equals("jcztz");
        }).collect(Collectors.toList());

        return success(data);
    }
    @GetMapping("/listGfClass")
    public CommonResult listGfClass()
    {
        List<String> list = inspectionNewsService.listGfClass("zflm");
        return success(list);
    }
    @GetMapping("/list")
    public CommonResult list(InspectionNews inspectionNews,
                             @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                             @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {
        Page<InspectionNews> page = new Page<>(pageNum, pageSize);
        IPage<InspectionNews> list = inspectionNewsService.selectInspectionNewsList(page,inspectionNews);
        return success(list);
    }

    @GetMapping("/ownList")
    public CommonResult ownList(InspectionNews inspectionNews,@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize)
    {
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        inspectionNews.setCreator(loginUser.getId().toString());
        Page<InspectionNews> page = new Page<>(pageNum, pageSize);
        IPage<InspectionNews> list = inspectionNewsService.selectInspectionNewsList(page,inspectionNews);
        return success(list);
    }
    @PostMapping("/add")
    public CommonResult add(@RequestBody InspectionNews inspectionNews) throws Exception {
        //获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
//        AdminUserRespDTO user = sysUserService.getUser(loginUser.getId());
        List<Long> roleIds = permissionApi.getRoleIdsByUserId(loginUser.getId());
        List<RoleDO> roleList = roleService.getRoleList(roleIds);

        List<String> roleKeys = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());

        if (roleKeys.contains("jcgf")) {
            if (StringUtils.isEmpty(inspectionNews.getCategory())) {
                //检测官方
                inspectionNews.setCategory("zflm");
            } else {
                if (!inspectionNews.getCategory().equals("zflm") && !inspectionNews.getCategory().equals("jcztz")) {
                    throw new Exception("权限不足");
                }
            }
            //根据部门获取发布单位
            AdminUserRespDTO user = sysUserService.getUser(loginUser.getId());
            DeptRespDTO sysDept = deptService.getDept(user.getDeptId());
            inspectionNews.setPublishUnit(ObjectUtil.isEmpty(sysDept) ? "检测官方" : sysDept.getName());
//            if (inspectionNews.getCategory().equals("jcztz")){
//                //如果是内部通知 进行websocket通知
//                try {
//                    msgSocket.sendToAll("newMsg");
//                }catch (Exception e){
//                    logger.error(e.getMessage());
//                }
//
//            }
        } else if (roleKeys.contains("jcshop")) {
            //检测站
            inspectionNews.setCategory("jczgg");
            ShopMallPartners partners = partnersService.selectShopMallPartnersByUserId(loginUser.getId(), "jc");
            inspectionNews.setPublishUnit(partners.getPartnerName());
        }

        //判断是否为当前登录用户创建的
        return toAjax(inspectionNewsService.insertInspectionNews(inspectionNews));
    }

    @PostMapping("/edit")
    public CommonResult edit(@RequestBody InspectionNews inspectionNews)
    {
        //判断是否为当前登录用户创建的
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        InspectionNews inspectionNews1 = inspectionNewsService.selectInspectionNewsById(inspectionNews.getId());
        if (!inspectionNews1.getCreator().equals(loginUser.getId().toString())){
            return error("禁止编辑");
        }
        inspectionNews.setPublishUnit(null);
        inspectionNews.setCategory(null);
        return toAjax(inspectionNewsService.updateInspectionNews(inspectionNews));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PostMapping("/del")
    public CommonResult remove(@RequestParam("id") Long id)
    {
        //判断是否为当前登录用户创建的
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        InspectionNews inspectionNews1 = inspectionNewsService.selectInspectionNewsById(id);
        if (!inspectionNews1.getCreator().equals(loginUser.getId().toString())){
            return error("禁止删除");
        }
        return toAjax(inspectionNewsService.deleteInspectionNewsById(id));
    }
    //获取 详细信息
    @GetMapping("/getDetail")
    public CommonResult getDetail(Long newsId)
    {
       return success(inspectionNewsService.getDetail(newsId));
    }

    /**
     * 新增阅读数量
     * @param newsId
     * @return
     */
    @PostMapping("/addReadNum")
    public CommonResult addReadNum(@RequestParam("newsId") Long newsId,Long objectId)
    {
        inspectionNewsService.addReadNum(newsId,objectId);
        return CommonResult.ok();
    }

    /**
     * 点赞/收藏
     * @param newsId
     * @param type
     * @return
     */
    @PostMapping("/likeOrCollect")
    public CommonResult likeOrCollect(@RequestParam("newsId") Long newsId,@RequestParam("type") String type)
    {
        inspectionNewsService.likeOrCollect(newsId,type);
        return CommonResult.ok();
    }



    /**
     * 新增评论
     * @param inspectionNewsComment
     * @return
     */
    @PostMapping("/addInspectionNewsComment")
    public CommonResult addInspectionNewsComment(@RequestBody InspectionNewsComment inspectionNewsComment)
    {
        inspectionNewsService.addInspectionNewsComment(inspectionNewsComment);
        return CommonResult.ok();
    }

    /**
     * 删除评论
     * @param commentId
     * @return
     */
    @PostMapping("/delNewsComment")
    public CommonResult delNewsComment(Long commentId)
    {
        //判断是否为当前登录用户创建的
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        InspectionNewsComment comment = commentService.getById(commentId);
        if (!comment.getCreator().equals(loginUser.getId().toString())){
            return error("禁止删除");
        }
        return toAjax(commentService.removeById(commentId));
    }
    /**
     * 获取评论列表
     * @return
     */
    @GetMapping("/getCommentList")
    public CommonResult getCommentList(Long newsId,
                                       @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                                       @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {

        Page<InspectionNewsComment> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<InspectionNewsComment> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionNewsComment::getNewsId,newsId).orderByDesc(TenantBaseDO::getCreateTime);
        IPage<InspectionNewsComment> commentList = commentService.page(page,queryWrapper);
        return success(commentList);
    }
    /**
     * 我的收藏
     * @return
     */
    @GetMapping("/collectionNews")
    public CommonResult collectionNews(String newsName,
                                       @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                                       @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {
        Page<InspectionNews> page = new Page<>(pageNum, pageSize);
        IPage<InspectionNews> newsList = inspectionNewsService.collectionNews(page,newsName);
        return success(newsList);
    }

    /**
     * 获取未读消息数量
     * @return
     */
    @GetMapping("/newMsgNum")
    public CommonResult newMsgNum(Long partnerId)
    {
        return success(inspectionNewsService.newMsgNum(partnerId));
    }

    /**
     * 获取未读消息列表
     * @return
     */
    @GetMapping("/msgList")
    public CommonResult msgList(Long partnerId,
                                @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                                @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {
        Page<InspectionNews> page = new Page<>(pageNum, pageSize);
        IPage<InspectionNews> news = inspectionNewsService.msgList(page,partnerId);
        return success(news);
    }

}
