package com.fs.app.controller;


import com.fs.app.annotation.Login;
import com.fs.app.param.CrmDoReadMsgParam;
import com.fs.app.utils.JwtUtils;
import com.fs.common.core.domain.R;
import com.fs.crm.param.CrmMsgListQueryParam;
import com.fs.crm.service.ICrmMsgService;
import com.fs.crm.vo.CrmMsgListQueryVO;
import com.fs.crm.vo.CrmMsgTypeVO;
import com.fs.system.service.ISysDictDataService;
import com.fs.system.vo.DictVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

import static com.fs.common.constant.Constants.PAGE_SIZE;


@Api("消息接口")
@RestController
@RequestMapping(value="/app/crmMsg")
public class CrmMsgController extends  AppBaseController {
	@Autowired
    JwtUtils jwtUtils;
	@Autowired
	ICrmMsgService msgService;
	@Autowired
	private ISysDictDataService dictDataService;
	@Login
	@ApiOperation("获取消息数量")
	@GetMapping("/getMsgCount")
	public R getMsgCount(HttpServletRequest request){
		Long count= msgService.selectCrmMsgCountByUserId(Long.parseLong(getUserId()));
		return R.ok().put("counts",count);

	}
	@Login
	@ApiOperation("获取消息")
	@GetMapping("/getMsg")
	public R getMsg(HttpServletRequest request){
		//获取用户未读总数
		//获取所有类型
		List<DictVO> types=dictDataService.selectDictDataListByType("crm_msg_type");
		List<CrmMsgTypeVO> counts=new ArrayList<>();
		for(DictVO v:types){
			Long count= msgService.selectCrmMsgCountByUserId(Long.parseLong(getUserId()),Integer.parseInt(v.getDictValue()));
			String title=msgService.selectCrmNewMsgByUserId(Long.parseLong(getUserId()),Integer.parseInt(v.getDictValue()));
			CrmMsgTypeVO typeVO=new CrmMsgTypeVO();
			typeVO.setMsgType(Integer.parseInt(v.getDictValue()));
			typeVO.setTotal(count);
			if(title!=null){
				typeVO.setTitle(title);
			}
			typeVO.setMsgTypeName(v.getDictLabel());
			counts.add(typeVO);
		}
		return R.ok().put("counts",counts);
	}


	@Login
	@GetMapping("/getMsgList")
	@ApiOperation("获取我的消息列表")
	public R getMsgList(CrmMsgListQueryParam param)
	{
		PageHelper.startPage(param.getPage(), PAGE_SIZE);
		param.setCompanyId(getCompanyId());
		param.setCompanyUserId(Long.parseLong(getUserId()));
		List<CrmMsgListQueryVO> list = msgService.selectCrmMsgListQuery(param);
		PageInfo<CrmMsgListQueryVO> listPageInfo=new PageInfo<>(list);
		return R.ok().put("data",listPageInfo);
	}



	@Login
	@PostMapping("/doRead")
	@ApiOperation("已读")
	public R doRead(@RequestBody CrmDoReadMsgParam param)
	{
		msgService.setReadByType(Long.parseLong(getUserId()),param.getMsgType());
		return R.ok("操作成功");
	}


	@Login
	@ApiOperation("全部已读")
	@PostMapping("/setAllRead")
	public R setAllRead()
	{
		msgService.setAllRead(Long.parseLong(getUserId()));
		return R.ok();
	}




}
