package org.gyk.modules.lssj.cxcsssjbjchuzhijilu.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.gyk.common.api.Result;
import org.gyk.modules.lssj.cxcsssjbjchuzhijilu.entity.CxcSssjBjChuzhijilu;
import org.gyk.modules.lssj.cxcsssjbjchuzhijilu.mapper.CxcSssjBjChuzhijiluMapper;
import org.gyk.modules.lssj.cxcsssjbjchuzhijilu.service.ICxcSssjBjChuzhijiluService;
import org.jeecgframework.poi.word.WordExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 实时数据报警处置记录
 * @Author: jeecg-boot
 * @Date:   2023-10-17
 * @Version: V1.0
 */
@Api(tags="实时数据报警处置记录")
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/cxcsssjbjchuzhijilu/cxcSssjBjChuzhijilu")
@Slf4j
public class CxcSssjBjChuzhijiluController {
	@Autowired
	private ICxcSssjBjChuzhijiluService cxcSssjBjChuzhijiluService;
	@Autowired
	private CxcSssjBjChuzhijiluMapper cxcSssjBjChuzhijiluMapper;
	@Value(value = "${muban}")
	private String uppath;

	 /**
	  * 压缩机报警处置记录
	  *
	  * @param
	  * @return Result<String>
	  */
	 @RequestMapping("/BaoJinChuZhi")
	 public Result<?> BaoJinChuZhi(@RequestBody JSONObject params ) {
		 DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

		 LocalDateTime sbsj = LocalDateTime.now();

		 String userid = params.getString("userid");
		 String zc = params.getString("zc");
		 String jzh = params.getString("jzh");
		 String bjmc = params.getString("bjmc");
		 String bjsj = params.getString("bjsj");
		 String bjms = params.getString("bjms");
		 String yyfx = params.getString("yyfx");
		 String czcs = params.getString("czcs");
		 String czry = params.getString("czry");

		 List<String> userOrgCode = cxcSssjBjChuzhijiluService.queryOrgCode(userid);
		 String orgcode = userOrgCode.get(0);
//		 log.info("hi:"+userid+" name:"+czry+" time:"+bjsj+" "+jzh+" "+bjmc+" "+bjms+" "+yyfx+" "+czcs+" "+zc);

		 LocalDateTime bjdate = LocalDateTime.parse(bjsj, df);

		 CxcSssjBjChuzhijilu cxcSssjBjChuzhijilu = new CxcSssjBjChuzhijilu();
		 cxcSssjBjChuzhijilu.setZhanchang(zc);
		 cxcSssjBjChuzhijilu.setJizuhao(jzh);
		 cxcSssjBjChuzhijilu.setBjName(bjmc);
		 cxcSssjBjChuzhijilu.setBjTime(bjdate);
		 cxcSssjBjChuzhijilu.setBjMs(bjms);
		 cxcSssjBjChuzhijilu.setFenxiString(yyfx);
		 cxcSssjBjChuzhijilu.setChuzhicuoshiString(czcs);
		 cxcSssjBjChuzhijilu.setCreateBy(czry);
		 cxcSssjBjChuzhijilu.setCreateTime(sbsj);
		 cxcSssjBjChuzhijilu.setSysOrgCode(orgcode);

		 cxcSssjBjChuzhijiluService.save(cxcSssjBjChuzhijilu);

		 return Result.ok("添加成功！");
	 }

	/**
	 * 分页列表查询
	 *
	 * @param
	 * @param pageNo
	 * @param pageSize
	 * @param
	 * @return
	 */

	@GetMapping(value = "/list")
	public IPage<CxcSssjBjChuzhijilu> queryPageList(@RequestParam(value = "pageNo") int pageNo,@RequestParam(value = "pageSize") int pageSize,@RequestParam(value = "zhanc") String zhanc,@RequestParam(value = "jzh") String jzh,@RequestParam(name = "startTime", required = false) String startTime,
								   @RequestParam(name = "endTime", required = false) String endTime) {
		LambdaQueryWrapper<CxcSssjBjChuzhijilu> lmq = Wrappers.lambdaQuery();
		lmq.between(CxcSssjBjChuzhijilu::getBjTime,startTime,endTime);
		lmq.eq(CxcSssjBjChuzhijilu::getZhanchang,zhanc);
		lmq.eq(CxcSssjBjChuzhijilu::getJizuhao,jzh);
		lmq.orderByAsc(CxcSssjBjChuzhijilu::getBjTime);

		IPage<CxcSssjBjChuzhijilu> iPage = new Page<>(pageNo,pageSize);
		IPage<CxcSssjBjChuzhijilu> list = cxcSssjBjChuzhijiluMapper.selectPage(iPage,lmq);



//		Map<String,String> mapjldxx = sssjTools.getJldnameByJldid(zhanc,jzh);
//
		list.getRecords().forEach(item->{
			String[] arr = item.getBjName().split("\\*");
			item.setBjName(arr[1]);
		});

//        log.info("total:"+list.getSize()+" "+list.getTotal());

		return list;
	}

	//模板导出
	@GetMapping("/export")
	public void export(String id, HttpServletResponse response) throws Exception {
		//1.获取list
		LambdaQueryWrapper<CxcSssjBjChuzhijilu> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(CxcSssjBjChuzhijilu::getId,id);
		CxcSssjBjChuzhijilu bjChuzhiJilu = cxcSssjBjChuzhijiluService.getOne(queryWrapper);
		//2.获取map
		Map<String, Object> map = new HashMap<>();

		//4.处理数据,防止导出word报错
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

		map.put("zhanchang",bjChuzhiJilu.getZhanchang());
		map.put("jizuhao",bjChuzhiJilu.getJizuhao());
		String[] nmstr = bjChuzhiJilu.getBjName().split("\\*");
		map.put("bjname",nmstr[1]);
		map.put("bjtime",df.format(bjChuzhiJilu.getBjTime()));
		if (bjChuzhiJilu.getBjMs() == null || bjChuzhiJilu.getBjMs().isEmpty()) {
			map.put("bjms","");
		} else {
			map.put("bjms",bjChuzhiJilu.getBjMs());
		}

		if (bjChuzhiJilu.getFenxiString() == null || bjChuzhiJilu.getFenxiString().isEmpty()) {
			map.put("yyfx","");
		} else {
			map.put("yyfx",bjChuzhiJilu.getFenxiString());
		}

		if (bjChuzhiJilu.getChuzhicuoshiString() == null || bjChuzhiJilu.getChuzhicuoshiString().isEmpty()) {
			map.put("czcs","");
		} else {
			map.put("czcs",bjChuzhiJilu.getChuzhicuoshiString());
		}

		map.put("czr",bjChuzhiJilu.getCreateBy());
		map.put("cztime",df.format(bjChuzhiJilu.getCreateTime()));

		String path = uppath + File.separator;
		String fileName = path + "baojingchuzhi.docx";//这是模板路径1
		String fileName2 = path + "baojingchuzhiOut.docx";//这是导出路径

		try {
			XWPFDocument doc = WordExportUtil.exportWord07(fileName, map);
			//5.输出word文件
			FileOutputStream fos = new FileOutputStream(fileName2);
			doc.write(fos);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//2022-06-10 niujl
		// String fileName = uppath + "\\result.xlsx";
		try {
			//避免文件名中文乱码，将UTF8打散重组成ISO-8859-1编码方式
			fileName2 = new String(fileName2.getBytes("UTF8"), "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		//设置响应头的类型
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		//让浏览器下载文件,name是上述默认文件下载名
		response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName2 + "\"");
		InputStream inputStream = null;
		OutputStream outputStream = null;
		//在service层中已经将数据存成了excel临时文件，并返回了临时文件的路径
		String downloadPath = fileName2;
		//根据临时文件的路径创建File对象，FileInputStream读取时需要使用
		File file = new File(downloadPath);
		//Niujl 2023.07.17
		long fileSize = new File(fileName2).length();
		response.addHeader("Content-Length", String.valueOf(fileSize));

		try {
			//通过FileInputStream读临时文件，ServletOutputStream将临时文件写给浏览器
			inputStream = new FileInputStream(file);
			outputStream = response.getOutputStream();
			int len = -1;
			byte[] b = new byte[1024];
			while ((len = inputStream.read(b)) != -1) {
				outputStream.write(b);
			}
			//刷新
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//关闭输入输出流
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 *   添加
	 *
	 * @param cxcSssjBjChuzhijilu
	 * @return
	 */
//	@AutoLog(value = "实时数据报警处置记录-添加")
//	@ApiOperation(value="实时数据报警处置记录-添加", notes="实时数据报警处置记录-添加")
//	@PostMapping(value = "/add")
//	public Result<?> add(@RequestBody CxcSssjBjChuzhijilu cxcSssjBjChuzhijilu) {
//		cxcSssjBjChuzhijiluService.save(cxcSssjBjChuzhijilu);
//		return Result.ok("添加成功！");
//	}
	
	/**
	 *  编辑
	 *
	 * @param cxcSssjBjChuzhijilu
	 * @return
//	 */
//	@AutoLog(value = "实时数据报警处置记录-编辑")
//	@ApiOperation(value="实时数据报警处置记录-编辑", notes="实时数据报警处置记录-编辑")
//	@PutMapping(value = "/edit")
//	public Result<?> edit(@RequestBody CxcSssjBjChuzhijilu cxcSssjBjChuzhijilu) {
//		cxcSssjBjChuzhijiluService.updateById(cxcSssjBjChuzhijilu);
//		return Result.ok("编辑成功!");
//	}
//
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */


}
