package com.ruoyi.web.controller.ehs;

import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ehsNoticeMessage.domain.EhsNoticeMessage;
import com.ruoyi.ehsNoticeMessage.service.IEhsNoticeMessageService;
import com.ruoyi.system.service.ISysDeptService;
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.ehsNoticeMessageFile.domain.EhsNoticeMessageFile;
import com.ruoyi.ehsNoticeMessageFile.service.IEhsNoticeMessageFileService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 通知公告附件Controller
 *
 * @author ruoyi
 * @date 2023-12-07
 */
@Api(tags="通知公告附件管理")
@RestController
@RequestMapping("/ehsNoticeMessageFile/ehsNoticeMessageFile")
public class EhsNoticeMessageFileController extends BaseController
{
    @Autowired
    private IEhsNoticeMessageFileService ehsNoticeMessageFileService;
	@Autowired
	private ISysDeptService deptService;
	@Autowired
	private IEhsNoticeMessageService ehsNoticeMessageService;
/**
 * 查询通知公告附件列表
 */
@PreAuthorize("@ss.hasPermi('ehsNoticeMessageFile:ehsNoticeMessageFile:list')")
@GetMapping("/list")
	public TableDataInfo list(EhsNoticeMessageFile ehsNoticeMessageFile)
	{
		startPage();
		List<EhsNoticeMessageFile> list = ehsNoticeMessageFileService.selectEhsNoticeMessageFileList(ehsNoticeMessageFile);
		return getDataTable(list);
	}

	/**
	 * 导出通知公告附件列表
	 */
	@PreAuthorize("@ss.hasPermi('ehsNoticeMessageFile:ehsNoticeMessageFile:export')")
	@Log(title = "通知公告附件", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, EhsNoticeMessageFile ehsNoticeMessageFile)
	{
		List<EhsNoticeMessageFile> list = ehsNoticeMessageFileService.selectEhsNoticeMessageFileList(ehsNoticeMessageFile);
		ExcelUtil<EhsNoticeMessageFile> util = new ExcelUtil<EhsNoticeMessageFile>(EhsNoticeMessageFile.class);
		util.exportExcel(response, list, "通知公告附件数据");
	}

	/**
	 * 获取通知公告附件详细信息
	 */
	@PreAuthorize("@ss.hasPermi('ehsNoticeMessageFile:ehsNoticeMessageFile:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") String id)
	{
		return success(ehsNoticeMessageFileService.selectEhsNoticeMessageFileById(id));
	}

    /**
     * 新增通知公告附件
     */
    @ApiOperation("新增通知公告附件")
    @PreAuthorize("@ss.hasPermi('ehsNoticeMessageFile:ehsNoticeMessageFile:add')")
    @Log(title = "通知公告附件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EhsNoticeMessageFile ehsNoticeMessageFile)
    {
        return toAjax(ehsNoticeMessageFileService.save(ehsNoticeMessageFile));
    }

    /**
     * 修改通知公告附件
     */
    @ApiOperation("修改通知公告附件")
    @PreAuthorize("@ss.hasPermi('ehsNoticeMessageFile:ehsNoticeMessageFile:edit')")
    @Log(title = "通知公告附件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EhsNoticeMessageFile ehsNoticeMessageFile)
    {
        return toAjax(ehsNoticeMessageFileService.updateById(ehsNoticeMessageFile));
    }

    /**
     * 删除通知公告附件
     */
    @ApiOperation("删除通知公告附件")
    @PreAuthorize("@ss.hasPermi('ehsNoticeMessageFile:ehsNoticeMessageFile:remove')")
    @Log(title = "通知公告附件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(ehsNoticeMessageFileService.removeByIds(Arrays.asList(ids)));
    }

	/**
	 * 文件列表，并按企业是否上传
	 */
	@PreAuthorize("@ss.hasPermi('ehsNoticeMessageFile:ehsNoticeMessageFile:listFile')")
	@GetMapping("/listFile")
	public TableDataInfo listFile(EhsNoticeMessageFile ehsNoticeMessageFile)
	{

		EhsNoticeMessage ehsNoticeMessage =ehsNoticeMessageService.getById(ehsNoticeMessageFile.getNoticeMessageId());
		SysDept dept = new SysDept();
		dept.setDeptIds(ehsNoticeMessage.getDeptList());
		List<SysDept> depts = deptService.selectDeptList(dept);
		Map<Long, String> comMap = new HashMap<Long, String>() ;
		Long[] cidsTemp = new Long[depts.size()];
		int j=0;
		for(SysDept bas :depts){
			comMap.put(bas.getDeptId(),bas.getDeptName());
			cidsTemp[j]=bas.getDeptId();
			j++;
		}
		ehsNoticeMessageFile.setState(1);
		List<EhsNoticeMessageFile> fileList = ehsNoticeMessageFileService.selectEhsNoticeMessageFileList(ehsNoticeMessageFile);
		// fileList里面有deptId,但没有deptName,这里给他设置把，以后再说循环查库的问题
		String cids=",";
		for(EhsNoticeMessageFile efile:fileList){
			cids= efile.getDeptId()+",";
			// 避免循环查数据库库
			efile.setDeptName(StringUtils.isEmpty(comMap.get(efile.getDeptId()))?"未知部门":comMap.get(efile.getDeptId()));
			//SysDept sysDept = deptService.selectDeptById(efile.getDeptId());
			//efile.setDeptName(sysDept.getDeptName());

		}
		//String[] cc = ehsNoticeMessageFile.getCompaynList().split(",");
		/*for(int i=0;i<cidsTemp.length;i++){
			if(cids.indexOf(cidsTemp[i].toString())==-1){
				EhsNoticeMessageFile emFile = new EhsNoticeMessageFile();
				emFile.setDeptName(comMap.get(cidsTemp[i]));
				fileList.add(emFile);
			}
		}*/
		return getDataTable(fileList);
	}
	@GetMapping("/downloadlist/{id}")
	public void downLoadList( @PathVariable("id") Long id, HttpServletResponse response ) throws UnsupportedEncodingException {
		EhsNoticeMessage ehsNoticeMessage = ehsNoticeMessageService.selectEhsNoticeMessageByNoticeMessageId(id);
		response.reset();
		response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(ehsNoticeMessage.getTitle()+"附件.zip", "UTF-8"));
		response.setCharacterEncoding("utf-8");

		response.setContentType("application/octet-stream");

		try(ZipOutputStream zipOutputStream=new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())))
		{
			EhsNoticeMessageFile ehsNoticeMessageFile = new EhsNoticeMessageFile();
			ehsNoticeMessageFile.setNoticeMessageId(id);
			List<EhsNoticeMessageFile> fileList = ehsNoticeMessageFileService.selectEhsNoticeMessageFileList(ehsNoticeMessageFile);
			for(EhsNoticeMessageFile efile:fileList)
			{
				File file =new File(efile.getFileName());
				String fileName=file.getName();
				ZipEntry ze = new ZipEntry(fileName);
				zipOutputStream.putNextEntry(ze);
				try(BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file))){
					byte[] bytes = new byte[1024];
					int i=0;
					while((i=bis.read(bytes))!=-1)
					{
						zipOutputStream.write(bytes,0,i);
					}
					zipOutputStream.closeEntry();
				}catch (Exception e)
				{
					e.printStackTrace();
				}
			}

		}catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
