package com.ruoyi.web.controller.ehs;

import java.util.List;
import java.util.Arrays;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ehsHiddenDanger.domain.EhsHiddenDanger;
import com.ruoyi.ehsMaterial.domain.EhsMaterial;
import com.ruoyi.ehsMaterial.service.IEhsMaterialService;
import com.ruoyi.ehsNoticeMessage.domain.EhsNoticeMessage;
import com.ruoyi.ehsNoticeMessage.service.IEhsNoticeMessageService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ehsMyMessage.domain.EhsMyMessage;
import com.ruoyi.ehsMyMessage.service.IEhsMyMessageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 我的的消息Controller
 *
 * @author ruoyi
 * @date 2024-01-16
 */
@Api(tags="我的的消息管理")
@RestController
@RequestMapping("/ehsMyMessage/ehsMyMessage")
public class EhsMyMessageController extends BaseController
{
    @Autowired
    private IEhsMyMessageService ehsMyMessageService;
	@Autowired
	private IEhsNoticeMessageService ehsNoticeMessageService;
	@Autowired
	private IEhsMaterialService ehsMaterialService;
	@Autowired
	private ISysDictDataService dictDataService;
/**
 * 查询我的的消息列表
 */
//@PreAuthorize("@ss.hasPermi('ehsMyMessage:ehsMyMessage:list')")
@GetMapping("/list")
	public TableDataInfo list(EhsMyMessage ehsMyMessage)
	{
		startPage();
		List<EhsMyMessage> list = ehsMyMessageService.selectEhsMyMessageList(ehsMyMessage);
		return getDataTable(list);
	}

	/**
	 * 导出我的的消息列表
	 */
	//@PreAuthorize("@ss.hasPermi('ehsMyMessage:ehsMyMessage:export')")
	@Log(title = "我的的消息", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, EhsMyMessage ehsMyMessage)
	{
		List<EhsMyMessage> list = ehsMyMessageService.selectEhsMyMessageList(ehsMyMessage);
		ExcelUtil<EhsMyMessage> util = new ExcelUtil<EhsMyMessage>(EhsMyMessage.class);
		util.exportExcel(response, list, "我的的消息数据");
	}

	/**
	 * 获取我的的消息详细信息
	 */
	//@PreAuthorize("@ss.hasPermi('ehsMyMessage:ehsMyMessage:query')")
	@GetMapping(value = "/{myMessageId}")
	public AjaxResult getInfo(@PathVariable("myMessageId") Long myMessageId)
	{
		return success(ehsMyMessageService.selectEhsMyMessageByMyMessageId(myMessageId));
	}

    /**
     * 新增我的的消息
     */
    @ApiOperation("新增我的的消息")
    //@PreAuthorize("@ss.hasPermi('ehsMyMessage:ehsMyMessage:add')")
    @Log(title = "我的的消息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EhsMyMessage ehsMyMessage)
    {
        return toAjax(ehsMyMessageService.save(ehsMyMessage));
    }

    /**
     * 修改我的的消息
     */
    @ApiOperation("修改我的的消息")
    //@PreAuthorize("@ss.hasPermi('ehsMyMessage:ehsMyMessage:edit')")
    @Log(title = "我的的消息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EhsMyMessage ehsMyMessage)
    {
        return toAjax(ehsMyMessageService.updateById(ehsMyMessage));
    }

    /**
     * 删除我的的消息
     */
    @ApiOperation("删除我的的消息")
    //@PreAuthorize("@ss.hasPermi('ehsMyMessage:ehsMyMessage:remove')")
    @Log(title = "我的的消息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{myMessageIds}")
    public AjaxResult remove(@PathVariable Long[] myMessageIds)
    {
        return toAjax(ehsMyMessageService.removeByIds(Arrays.asList(myMessageIds)));
    }

	/**
	 * 获取待处理货待阅读的消息
	 * @return
	 */
	@GetMapping("/getUnread")
	public AjaxResult getUnread()
	{
		AjaxResult ajr = new AjaxResult();
		//判断角色，只有局端和乡镇隐患管理员角色才计算
		if(SecurityUtils.hasRole("HDDept") ||SecurityUtils.hasRole("HDAdmin")) {
			EhsMyMessage ehsMyMessage = new EhsMyMessage();
			ehsMyMessage.setMyMessageType("0");
			ehsMyMessage.setMyUserId(SecurityUtils.getUserId());
			EhsMyMessage msg = ehsMyMessageService.selectEhsMyMessageByMyMessageMax(ehsMyMessage);
			if (msg == null) {
				ajr.put("msgHD", "0");
			} else {
				int mCount = (msg.getMyMessageKey().split(",")).length;
				ajr.put("msgHD", mCount);
				/*if (msg.getMyMessageState().equals("N"))
					ajr.put("msgHD", "1");
				else
					ajr.put("msgHD", "0");*/
			}
		}else{
			ajr.put("msgHD", "0");
		}
		//分析是否有本人的未读消息通知
		//消息通知的每一记录，我的消息都应该有一条记录，如果没有，说明未读，并向我的消息插入一条记录，并设置为未读
		//消息通知模块点击阅读按钮后，需要同时修改我的消息的已读标志
		//统计我的消息类型=1的所有未读数量。
		EhsMyMessage myMsg = new EhsMyMessage();
		myMsg.setNoticeDeptId(SecurityUtils.getDeptId());
		myMsg.setNoticeStatus("1");
		myMsg.setNoticeMesgType(0L);
		myMsg.setMyMessageType("1");
		myMsg.setMyUserId(SecurityUtils.getUserId());
		List<EhsMyMessage> list = ehsMyMessageService.selectUnReadNotice(myMsg);
		if(!list.isEmpty()){
			for(EhsMyMessage emsg :list){
				EhsMyMessage msgNew = new EhsMyMessage();
				msgNew.setMyMessageKey(emsg.getMyMessageId().toString());
				ehsMyMessageService.saveMyMessage(msgNew);
			}
		}
		EhsMyMessage msgQuery = new EhsMyMessage();
		msgQuery.setMyMessageType("1");
		msgQuery.setMyMessageState("N");
		msgQuery.setMyUserId(SecurityUtils.getUserId());
		Long msgCount = ehsMyMessageService.msgCount(msgQuery);
		ajr.put("msg",msgCount.toString());
		///////////////////////// 物资消息
		if(SecurityUtils.hasRole("store")  ) {
			for (int i = 1; i <= 4; i++) {
				EhsMyMessage myMMsg = buildMaterialMsg(Long.parseLong(String.valueOf(i)));
				int mCount = 0;
				if (myMMsg != null && StringUtils.isNotEmpty(myMMsg.getMyMessageKey())) {
					mCount = (myMMsg.getMyMessageKey().split(",")).length;
				}
				switch (i) {
					case 1:
						ajr.put("msgMaterial1", mCount);
						break;
					case 2:
						ajr.put("msgMaterial2", mCount);
						break;
					case 3:
						ajr.put("msgMaterial3", mCount);
						break;
					case 4:
						ajr.put("msgMaterial4", mCount);
						break;
				}
			}
		}
		return  ajr;
	}
	@GetMapping("/setReadByHD")
	public AjaxResult setReadByHD()
	{
		EhsMyMessage msgQuery = new EhsMyMessage();
		msgQuery.setMyMessageState("Y");
		msgQuery.setMyUserId(SecurityUtils.getUserId());
		return toAjax(ehsMyMessageService.updateHDbyKeyUserId(msgQuery));
	}

	/**
	 * 待处理出库消息
	 * @return
	 */
	@GetMapping("/getSendQuantity/{classFirst}")
	public AjaxResult getSendQuantity(@PathVariable Long  classFirst)
	{
		return success(buildMaterialMsg(classFirst));
	}
	private EhsMyMessage buildMaterialMsg(Long  classFirst){
		EhsMaterial ehsMaterial = new EhsMaterial();
		if(classFirst!=0)
			ehsMaterial.setClassFirst(classFirst);
		String myMsgType ="m"+classFirst.toString();
		ehsMaterial.setIsSendQuantity(1);
		List<EhsMaterial> list = ehsMaterialService.selectEhsMaterialList(ehsMaterial);
		String[] MaterialIds = list.stream().map(item -> item.getMaterialDetailId().toString()).toArray(String[]::new);
		String strmIds = StringUtils.join(MaterialIds,",");
		EhsMyMessage ehsMyMessage = new EhsMyMessage();
		ehsMyMessage.setMyMessageType(myMsgType);
		ehsMyMessage.setMyUserId(SecurityUtils.getUserId());
		EhsMyMessage msg = ehsMyMessageService.selectEhsMyMessageByMyMessageMax(ehsMyMessage);
		boolean isNew =false;
		if(msg==null   ){
			if(StringUtils.isNotEmpty(strmIds))
				isNew = true;
			else
				isNew = false;
		}else{
			if(StringUtils.isNotEmpty(strmIds)) {
				if(!strmIds.equals(msg.getMyMessageKey())) {//两者不一致
					String[] newIds = strmIds.split(",");
					String oldIds = "," + msg.getMyMessageKey() + ",";
					for (String id : newIds) {
						if (oldIds.indexOf("," + id + ",") == -1) {//不包含，表示有新的id
							isNew = true;
							break;
						}
					}
				}else{//两者一致
					msg.setMyMessageDesc("");
					return msg;
				}
			}
		}
		if (isNew) {//有新的id，生成一个新记录
			EhsMyMessage msgNew = new EhsMyMessage();
			msgNew.setMyUserId(SecurityUtils.getUserId());
			msgNew.setMyMessageType(myMsgType);
			String strMaterial = DictUtils.getDictLabel("material_class_fast",classFirst.toString());
			msgNew.setMyMessageDesc(strMaterial+"有" +list.size()+"条待处理出库!");
			msgNew.setMyMessageKey(strmIds);
			msgNew.setMyMessageState("N");
			ehsMyMessageService.save(msgNew);
			return msgNew;
		}
		ehsMyMessage.setMyMessageDesc("");
		return ehsMyMessage;
	}
	@GetMapping("/setMaterial/{myMessageId}")
	public AjaxResult setMaterial(@PathVariable Long  myMessageId)
	{
		EhsMyMessage msgQuery = new EhsMyMessage();
		msgQuery.setMyMessageState("Y");
		msgQuery.setMyMessageId(myMessageId);
		return toAjax(ehsMyMessageService.updateById(msgQuery));
	}

	/**
	 * 获取待阅读消息提醒
	 * @return
	 */
	@GetMapping("/getNoticeMsg")
	public AjaxResult getNoticeMsg(){
		EhsMyMessage myMsg = new EhsMyMessage();
		myMsg.setNoticeDeptId(SecurityUtils.getDeptId());
		myMsg.setNoticeStatus("1");
		myMsg.setNoticeMesgType(0L);
		myMsg.setMyMessageType("1");
		myMsg.setMyUserId(SecurityUtils.getUserId());
		List<EhsMyMessage> list = ehsMyMessageService.selectUnReadNotice(myMsg);
		Long[] ids =null;
		EhsMyMessage returnMymsg = new EhsMyMessage();
		if(!list.isEmpty()){//表示有新增的消息通知
			for(EhsMyMessage emsg :list){
				EhsMyMessage msgNew = new EhsMyMessage();
				msgNew.setMyMessageKey(emsg.getMyMessageId().toString());
				ehsMyMessageService.saveMyMessage(msgNew);
			}
			ids = list.stream().map(item->item.getMyMessageId()).toArray(Long[]::new);
			returnMymsg.setMyMessageDesc("您有"+ids.length+"条新的消息通知未阅读！");
		}else{//没有新增的消息通知，
			returnMymsg.setMyMessageDesc("");
		}
		//计算全部未阅读的消息
		EhsMyMessage msgQuery = new EhsMyMessage();
		msgQuery.setMyMessageType("1");
		msgQuery.setMyMessageState("N");
		msgQuery.setMyUserId(SecurityUtils.getUserId());
		Long msgCount = ehsMyMessageService.msgCount(msgQuery);
		ids  = new Long[Integer.parseInt(msgCount.toString())];
		//需要根据现有未阅读消息通知数量生成一个数组，返回前端，以便前端根据这个数组计算未阅读数量
		for(int i=0;i<msgCount;i++){
			ids[i]=Long.valueOf(i) ;
		}
		returnMymsg.setMyMessageKey(StringUtils.join(ids,","));
		returnMymsg.setMyMessageType("1");
		returnMymsg.setMyMessageState("N");
		return success(returnMymsg);
	}
}
