package com.hotent.portal.controller;


import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.jwt.JwtTokenHandler;
import com.hotent.base.util.*;
import com.hotent.portal.model.PortalNewsNoticeRead;
import com.hotent.portal.persistence.manager.PortalNewsNoticeReadManager;
import com.hotent.uc.api.impl.util.ContextUtil;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.api.service.IUserService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.controller.BaseController;
import com.hotent.base.feign.UCFeignService;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.util.time.DateFormatUtil;
import com.hotent.portal.model.PortalNewsNotice;
import com.hotent.portal.persistence.manager.PortalNewsNoticeManager;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 *  前端控制器
 *
 * @company 广州宏天软件股份有限公司
 * @author 赵祥云
 * @since 2020-07-03
 */
@RestController
@Api(tags="新闻公告管理")
@ApiGroup(group= {ApiGroupConsts.GROUP_PORTAL})
@RequestMapping("/portalNewsNotice/v1/")
public class PortalNewsNoticeController extends BaseController<PortalNewsNoticeManager, PortalNewsNotice> {

	@Resource
	UCFeignService ucFeignService;
	@Resource
	PortalNewsNoticeReadManager portalNewsNoticeReadManager;
	@Resource
	JwtTokenHandler jwtTokenHandler;
	@Resource
	IUserService userServiceImpl;

	@GetMapping("/getNews")
	@ApiOperation("根据分类id查询实体")
	public List<PortalNewsNotice> getNews(
			@ApiParam(name="classifyId", value="分类id") @RequestParam String classifyId,
			@ApiParam(name="page", value="页号", required = false) @RequestParam(required = false) String page,
			@ApiParam(name="pageSize", value="分页大小", required = false) @RequestParam(required = false) String pageSize) {
		try {
			HttpServletRequest request = HttpUtil.getRequest();
			if (request != null) {
				String token = request.getHeader("Authorization");
				String authToken = token.substring(7);
				Claims claims = jwtTokenHandler.parseToken(authToken);
				String account = (String)claims.get("sub");
				IUser userByAccount = userServiceImpl.getUserByAccount(account);
				SecurityContextHolder.getContext().setAuthentication(null);
				ContextUtil.setCurrentUser(userByAccount);
			}
		} catch (Exception e) {}

		return baseService.getNews(classifyId, page, pageSize);
	}


	@PostMapping(value="/query", produces={"application/json; charset=utf-8" })
	@ApiOperation("分页查询结果")
	public PageList<PortalNewsNotice> query(@ApiParam(name="queryFilter", value="分页查询信息") @RequestBody QueryFilter<PortalNewsNotice> queryFilter) {
		PageList<PortalNewsNotice> list = baseService.query(queryFilter);
		Set<String> set = new HashSet<>();
		list.getRows().forEach(item->{
			set.add(item.getCreateBy());
		});
		Map<String,String> map = new HashMap<>();
		if(BeanUtils.isNotEmpty(set) && set.size()>0){
			ArrayNode users = ucFeignService.getUserByIdsOrAccounts(StringUtil.join(set, ","));
			if(BeanUtils.isNotEmpty(users) && users.size()>0){
				users.forEach(item->{
					map.put(item.get("id").asText(),item.get("fullname").asText());
				});
			}
		}
		if(map.size()>0){
			list.getRows().forEach(item->{
				if(map.containsKey(item.getCreateBy())){
					item.setCreateByName(map.get(item.getCreateBy()));
				}
			});
		}
		return list;
	}

	@GetMapping("/getNewsById")
	@ApiOperation("根据新闻id查询实体")
	public PortalNewsNotice getNewsById(@ApiParam(name="id", value="新闻数据id") @RequestParam String id) {
		PortalNewsNotice portalNewsNotice = baseService.get(id);
		if(StringUtil.isNotEmpty(portalNewsNotice.getCreateBy())){
			JsonNode createUser= ucFeignService.getUserById(portalNewsNotice.getCreateBy()).getValue();
			if(BeanUtils.isNotEmpty(createUser) && createUser.has("fullname")){
				portalNewsNotice.setCreateByName(createUser.get("fullname").asText());
			}
		}
		if(StringUtil.isNotEmpty(portalNewsNotice.getUpdateBy())){
			JsonNode updateUser= ucFeignService.getUserById(portalNewsNotice.getUpdateBy()).getValue();
			if(BeanUtils.isNotEmpty(updateUser) && updateUser.has("fullname")){
				portalNewsNotice.setUpdateByName(updateUser.get("fullname").asText());
			}
		}
		return portalNewsNotice;
	}

	@PostMapping("exportNews")
	@ApiOperation(value = "根据id集合导出新闻公告", httpMethod = "POST", notes = "根据id集合导出新闻公告")
	public void exportNews(HttpServletResponse response, HttpServletRequest request, @RequestBody List<String> ids) throws Exception{
		String fileName = "newsNotice_" + DateFormatUtil.format(LocalDateTime.now(), "yyyy_MMdd_HHmm");
		String json = baseService.export(ids);
		HttpUtil.downLoadFile(request, response, json, "newsNotice.json", fileName);
	}

	@PostMapping("importNews")
	@ApiOperation(value = "导入新闻公告", httpMethod = "POST", notes = "导入新闻公告")
	public CommonResult importNews(MultipartHttpServletRequest request, HttpServletResponse response, @RequestParam String classifyId) throws Exception{
		MultipartFile file = request.getFile("file");
		String operate = request.getParameter("operate");
		String uzPath = "";
		try {
			String rootRealPath = (FileUtil.getIoTmpdir() +"/attachFiles/unZip/").replace("/", File.separator);
			FileUtil.createFolder(rootRealPath, true);
			String name = file.getOriginalFilename();
			String fileDir = StringUtil.substringBeforeLast(name, ".");
			ZipUtil.unZipFile(file, rootRealPath); // 解压文件
			uzPath = rootRealPath + File.separator + fileDir; // 解压后文件的真正路径
			if(StringUtils.equals(operate,"check")){
				return baseService.importCheck(uzPath,classifyId);
			}else {
				baseService.importFile(uzPath, classifyId);
			}
			return new CommonResult<>(true,"导入成功");
		}catch (Exception e){
			return new CommonResult(false,"导入失败："+e.getMessage());
		}finally {
			if (StringUtil.isNotEmpty(uzPath)) {
				File file1 = new File(uzPath);
				if (file1.exists()) {
					file1.delete();
				}
			}
		}
	}

	@GetMapping("/getNewsForRead")
	@ApiOperation("根据分类id查询实体(包含已读未读状态)")
	public List<PortalNewsNotice> getNewsForRead(
			@ApiParam(name="classifyId", value="分类id") @RequestParam String classifyId,
			@ApiParam(name="page", value="页号", required = false) @RequestParam(required = false) String page,
			@ApiParam(name="pageSize", value="分页大小", required = false) @RequestParam(required = false) String pageSize) {
		List<PortalNewsNotice> list = baseService.getNews(classifyId, page, pageSize);
		List<String> ids = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {
			PortalNewsNotice notice = list.get(i);
			ids.add(notice.getId());
		}
		if(ids.size()>0) {
			IUser user = ContextUtil.getCurrentUser(); //获取当前用户
			QueryWrapper<PortalNewsNoticeRead> wrapper = new QueryWrapper<PortalNewsNoticeRead>();
			wrapper.select("MSG_ID_ as msgId", "count(ID_) as count");
			wrapper.eq("RECEIVER_ID_", user.getUserId());
			wrapper.in("MSG_ID_", ids);
			wrapper.groupBy("MSG_ID_");
			List<Map<String, Object>> selectList = portalNewsNoticeReadManager.getBaseMapper().selectMaps(wrapper);

			Map<String, Integer> dateMap = new HashMap<>();
			for (int i = 0; i <selectList.size() ; i++) {
				Map<String, Object> map = selectList.get(i);
				String msgId = (String)map.get("msgId");
				Long num = (Long)map.get("count");
				dateMap.put(msgId, num.intValue());
			}
			for (int i = 0; i < list.size(); i++) {
				PortalNewsNotice notice = list.get(i);
				Integer msgId = dateMap.get(notice.getId());
				notice.setIsRead(msgId==null? (short)0: (short)1);
			}
		}

		return list;
	}

	@GetMapping("/getNewsForReadById")
	@ApiOperation("根据新闻id查询实体(包含已读未读状态)")
	public PortalNewsNotice getNewsForReadById(@ApiParam(name="id", value="新闻数据id") @RequestParam String id) {
		PortalNewsNotice portalNewsNotice = baseService.get(id);
		IUser user = ContextUtil.getCurrentUser(); //获取当前用户
		Map<String, Object> params = new HashMap<>();
		params.put("userId", user.getUserId());
		params.put("msgId", id);
		List<PortalNewsNoticeRead> list = portalNewsNoticeReadManager.getReadByUser(params);
		if(list==null || list.size()==0) {
			PortalNewsNoticeRead read = new PortalNewsNoticeRead();
			read.setId(UniqueIdUtil.getSuid());
			read.setMsgId(id);
			read.setReceiverId(user.getUserId());
			read.setReceiver(user.getFullname());
			read.setReceiverTime(LocalDateTime.now());
			portalNewsNoticeReadManager.create(read);
		}
		if(StringUtil.isNotEmpty(portalNewsNotice.getCreateBy())){
			JsonNode createUser= ucFeignService.getUserById(portalNewsNotice.getCreateBy()).getValue();
			if(BeanUtils.isNotEmpty(createUser) && createUser.has("fullname")){
				portalNewsNotice.setCreateByName(createUser.get("fullname").asText());
			}
		}
		if(StringUtil.isNotEmpty(portalNewsNotice.getUpdateBy())){
			JsonNode updateUser= ucFeignService.getUserById(portalNewsNotice.getUpdateBy()).getValue();
			if(BeanUtils.isNotEmpty(updateUser) && updateUser.has("fullname")){
				portalNewsNotice.setUpdateByName(updateUser.get("fullname").asText());
			}
		}
		return portalNewsNotice;
	}
}
