package com.ruoyi.web.controller.ehs;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ehsMyMessage.domain.EhsMyMessage;
import com.ruoyi.ehsMyMessage.service.IEhsMyMessageService;
import com.ruoyi.ehsNoticeMessage.domain.EhsNoticeMessageDept;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.commons.lang3.StringUtils;
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.ehsNoticeMessage.domain.EhsNoticeMessage;
import com.ruoyi.ehsNoticeMessage.service.IEhsNoticeMessageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 内部公告Controller
 *
 * @author ruoyi
 * @date 2023-12-06
 */
@Api(tags="内部公告管理")
@RestController
@RequestMapping("/ehsNoticeMessage/ehsNoticeMessage")
public class EhsNoticeMessageController extends BaseController
{
    @Autowired
    private IEhsNoticeMessageService ehsNoticeMessageService;
	@Autowired
	private ISysDeptService deptService;
	@Autowired
	private IEhsMyMessageService ehsMyMessageService;
/**
 * 查询内部公告列表
 */
@PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:list')")
@GetMapping("/list")
	public TableDataInfo list(EhsNoticeMessageDept ehsNoticeMessage)
	{
		startPage();
		ehsNoticeMessage.setDeptId(SecurityUtils.getDeptId());
		ehsNoticeMessage.setStatus("1");
		ehsNoticeMessage.setFileDeptId(SecurityUtils.getDeptId());
		List<EhsNoticeMessageDept> list = ehsNoticeMessageService.selectEhsNoticeMessageList(ehsNoticeMessage);
		return getDataTable(list);
	}
	@PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:listAdmin')")
	@GetMapping("/listAdmin")
	public TableDataInfo listAdmin(EhsNoticeMessage ehsNoticeMessage)
	{
		startPage();
		ehsNoticeMessage.setCreateDeptId(SecurityUtils.getDeptId());
		List<EhsNoticeMessage> list = ehsNoticeMessageService.selectEhsNoticeMessageListAdmin(ehsNoticeMessage);
		return getDataTable(list);
	}
	/**
	 * 导出内部公告列表
	 */
	@PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:export')")
	@Log(title = "内部公告", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, EhsNoticeMessageDept ehsNoticeMessage)
	{
		ehsNoticeMessage.setDeptId(SecurityUtils.getDeptId());
		ehsNoticeMessage.setStatus("1");
		ehsNoticeMessage.setFileDeptId(SecurityUtils.getDeptId());
		List<EhsNoticeMessageDept> list = ehsNoticeMessageService.selectEhsNoticeMessageList(ehsNoticeMessage);
		if(!list.isEmpty()){
			for(int i=0;i<list.size();i++){
				list.get(i).setIsRead(list.get(i).getIsRead()==0 ?0L: 1L);
				list.get(i).setDeptName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
			}
		}
		ExcelUtil<EhsNoticeMessageDept> util = new ExcelUtil<EhsNoticeMessageDept>(EhsNoticeMessageDept.class);
		util.exportExcel(response, list, "内部公告数据");
	}
	@PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:export')")
	@Log(title = "内部公告", businessType = BusinessType.EXPORT)
	@PostMapping("/exportAdmin")
	public void exportAdmin(HttpServletResponse response, EhsNoticeMessage ehsNoticeMessage)
	{
		ehsNoticeMessage.setCreateDeptId(SecurityUtils.getDeptId());
		List<EhsNoticeMessage> list = ehsNoticeMessageService.selectEhsNoticeMessageListAdmin(ehsNoticeMessage);
		if(!list.isEmpty()){
			for(int i=0;i<list.size();i++){
				list.get(i).setDeptListName(list.get(i).getAllDept()==1 ?"全部": list.get(i).getDeptListName());
				list.get(i).setReadDeptId(StringUtils.isEmpty(list.get(i).getReadDeptId()) ?"0": String.valueOf(list.get(i).getReadDeptId().split(",").length));
			}
		}
		ExcelUtil<EhsNoticeMessage> util = new ExcelUtil<EhsNoticeMessage>(EhsNoticeMessage.class);
		util.exportExcel(response, list, "NoticeMessage");
	}
	/**
	 * 获取内部公告详细信息
	 */
	@PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:query')")
	@GetMapping(value = "/{noticeMessageId}")
	public AjaxResult getInfo(@PathVariable("noticeMessageId") Long noticeMessageId)
	{
		EhsNoticeMessage ehsNoticeMessage = ehsNoticeMessageService.selectEhsNoticeMessageByNoticeMessageId(noticeMessageId);
		if(StringUtils.isNotEmpty(ehsNoticeMessage.getDeptList())){
			String[] s =ehsNoticeMessage.getDeptList().split(",");
			Long[] l = new Long[s.length];
			for (int i =0;i<s.length;i++ ) {
				l[i] = Long.parseLong(s[i]);
			}
			ehsNoticeMessage.setDeptListArray(l);
		}
		return success(ehsNoticeMessage);
	}

    /**
     * 新增内部公告
     */
    @ApiOperation("新增内部公告")
    @PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:add')")
    @Log(title = "内部公告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EhsNoticeMessage ehsNoticeMessage)
    {
	    if (ehsNoticeMessage.getAllDept() == 0 && StringUtil.isEmpty(ehsNoticeMessage.getDeptList())) {
		    return error("未选择部门！");
	    } else {
		    ehsNoticeMessage.setStatus("0");
		    ehsNoticeMessage.setCreateUserId(SecurityUtils.getUserId());
		    ehsNoticeMessage.setCreateDeptId(SecurityUtils.getDeptId());
		    if (ehsNoticeMessage.getAllDept() == 1) {
			    List<String> deptList = new ArrayList<>();
			    SysDept dept = new SysDept();
			    dept.setParentId(0L);
			    List<SysDept> depts = deptService.selectAllDeptList(dept);
			    for (SysDept dd : depts) {
				    deptList.add(dd.getDeptId().toString());
			    }
			    ehsNoticeMessage.setDeptList(StringUtils.join(deptList, ","));
		    }
		    //直接发布，不在有先保存，再发布了。
		    ehsNoticeMessage.setStatus("1");
		    ehsNoticeMessage.setIssueTime(new Date());
		    return toAjax(ehsNoticeMessageService.save(ehsNoticeMessage));
	    }
    }

    /**
     * 修改内部公告
     */
    @ApiOperation("修改内部公告")
    @PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:edit')")
    @Log(title = "内部公告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EhsNoticeMessage ehsNoticeMessage)
    {
	    if (ehsNoticeMessage.getAllDept() == 0 && StringUtil.isEmpty(ehsNoticeMessage.getDeptList())) {
		    return error("未选择部门！");
	    } else {
		    ehsNoticeMessage.setStatus("0");
		    ehsNoticeMessage.setCreateUserId(SecurityUtils.getUserId());
		    ehsNoticeMessage.setCreateDeptId(SecurityUtils.getDeptId());
		    if (ehsNoticeMessage.getAllDept() == 1) {
			    List<String> deptList = new ArrayList<>();
			    SysDept dept = new SysDept();
			    dept.setParentId(0L);
			    List<SysDept> depts = deptService.selectAllDeptList(dept);
			    for (SysDept dd : depts) {
				    deptList.add(dd.getDeptId().toString());
			    }
			    ehsNoticeMessage.setDeptList(StringUtils.join(deptList, ","));
		    }
		    return toAjax(ehsNoticeMessageService.updateById(ehsNoticeMessage));
	    }

    }

    /**
     * 删除内部公告
     */
    @ApiOperation("删除内部公告")
    @PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:remove')")
    @Log(title = "内部公告", businessType = BusinessType.DELETE)
	@DeleteMapping("/{noticeMessageIds}")
    public AjaxResult remove(@PathVariable Long[] noticeMessageIds)
    {
        return toAjax(ehsNoticeMessageService.removeByIds(Arrays.asList(noticeMessageIds)));
    }

	/**
	 *发布
	 */
	@ApiOperation("发布公告")
	@PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:issueNews')")
	@Log(title = "发布公告", businessType = BusinessType.UPDATE)
	@GetMapping("/issueNews")
	public AjaxResult issueNews(  EhsNoticeMessage ehsNoticeMessage)
	{
		ehsNoticeMessage.setStatus("1");
		ehsNoticeMessage.setIssueTime(new Date());
		return toAjax(ehsNoticeMessageService.updateById(ehsNoticeMessage));
	}

	@ApiOperation("阅读公告")
	@PreAuthorize("@ss.hasPermi('ehsNoticeMessage:ehsNoticeMessage:detail')")
	@Log(title = "阅读公告", businessType = BusinessType.UPDATE)
	@GetMapping(value = "/detail/{noticeMessageId}")
	public AjaxResult detail(@PathVariable("noticeMessageId") Long noticeMessageId)
	{
		EhsNoticeMessage ehsNoticeMessage =  ehsNoticeMessageService.selectEhsNoticeMessageByNoticeMessageId(noticeMessageId);
		EhsNoticeMessage nm = new EhsNoticeMessage();
		if (StringUtils.isEmpty(ehsNoticeMessage.getReadDeptId()) || ehsNoticeMessage.getReadDeptId().indexOf(SecurityUtils.getDeptId()+ ",") < 0) {
			nm.setReadDeptId(SecurityUtils.getDeptId() + ",");
			nm.setNoticeMessageId(noticeMessageId);
			ehsNoticeMessageService.updateReadCompany(nm);
		}
		EhsMyMessage msgNew = new EhsMyMessage();
		msgNew.setMyMessageKey(noticeMessageId.toString());
		msgNew.setMyMessageState("Y");
		msgNew.setMyUserId(SecurityUtils.getUserId());
		msgNew.setMyMessageType("1");
		ehsMyMessageService.updatebyKeyUserId(msgNew);
		return success(ehsNoticeMessage);
	}

	@GetMapping(value = "/displayDetail/{noticeMessageId}")
	public AjaxResult displayDetail(@PathVariable("noticeMessageId") Long noticeMessageId)
	{
		EhsNoticeMessage ehsNoticeMessage =  ehsNoticeMessageService.selectEhsNoticeMessageByNoticeMessageId(noticeMessageId);
		return success(ehsNoticeMessage);
	}
}
