package org.stm.audit.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.val;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.jeecg.modules.system.service.ISysDictService;
import org.stm.audit.entity.AuditUserEvent;
import org.stm.audit.service.IAuditUserEventService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import java.util.Date;
import java.util.HashMap;

 /**
 * @Description: 事件库
 * @Author: jeecg-boot
 * @Date:   2025-09-19
 * @Version: V1.0
 */
@Api(tags="事件库")
@RestController
@RequestMapping("/audit/auditUserEvent")
@Slf4j
public class AuditUserEventController extends JeecgController<AuditUserEvent, IAuditUserEventService> {
	@Autowired
	private IAuditUserEventService auditUserEventService;
	 @Autowired
	 private ISysDictService sysDictService;
	 @Autowired
	 private ISysDictItemService sysDictItemService;
	
	/**
	 * 分页列表查询
	 *
	 * @param auditUserEvent
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "事件库-分页列表查询")
	@ApiOperation(value="事件库-分页列表查询", notes="事件库-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AuditUserEvent>> queryPageList(AuditUserEvent auditUserEvent,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AuditUserEvent> queryWrapper = QueryGenerator.initQueryWrapper(auditUserEvent, req.getParameterMap());
		Page<AuditUserEvent> page = new Page<AuditUserEvent>(pageNo, pageSize);
		IPage<AuditUserEvent> pageList = auditUserEventService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param auditUserEvent
	 * @return
	 */
	@AutoLog(value = "事件库-添加")
	@ApiOperation(value="事件库-添加", notes="事件库-添加")
	@RequiresPermissions("audit:audit_user_event:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody AuditUserEvent auditUserEvent) {
		auditUserEventService.save(auditUserEvent);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param auditUserEvent
	 * @return
	 */
	@AutoLog(value = "事件库-编辑")
	@ApiOperation(value="事件库-编辑", notes="事件库-编辑")
	@RequiresPermissions("audit:audit_user_event:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody AuditUserEvent auditUserEvent) {
		auditUserEventService.updateById(auditUserEvent);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "事件库-通过id删除")
	@ApiOperation(value="事件库-通过id删除", notes="事件库-通过id删除")
	//@RequiresPermissions("audit:audit_user_event:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		auditUserEventService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "事件库-批量删除")
	@ApiOperation(value="事件库-批量删除", notes="事件库-批量删除")
	//@RequiresPermissions("audit:audit_user_event:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.auditUserEventService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "事件库-通过id查询")
	@ApiOperation(value="事件库-通过id查询", notes="事件库-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AuditUserEvent> queryById(@RequestParam(name="id",required=true) String id) {
		AuditUserEvent auditUserEvent = auditUserEventService.getById(id);
		if(auditUserEvent==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(auditUserEvent);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param auditUserEvent
    */
    @RequiresPermissions("audit:audit_user_event:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AuditUserEvent auditUserEvent) {
        return super.exportXls(request, auditUserEvent, AuditUserEvent.class, "事件库");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("audit:audit_user_event:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
    	int impnum=0;
    	HashMap sjtypemap=new HashMap();
		// 查询机票
		List<SysDictItem> sysDictItemList = sysDictItemService.selectItemsByMainId("1968913811849035778");
		for(int s=0;s<sysDictItemList.size();s++){
			SysDictItem sd=sysDictItemList.get(s);
			sjtypemap.put(sd.getItemText(),sd.getItemValue());
		}

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			try {
				InputStream is = file.getInputStream();

			String filemodelcheckstr= this.isFileModelOk(is);

				InputStream dateis = file.getInputStream();

			if(filemodelcheckstr.equals("")){
				ArrayList xlist = this.readdata(dateis);
				//发现时间	事件解决时间	处置用时	事件系统名称	影响系统名称	事件类型
				// 发现事件渠道	事件描述	事件原因	事件处理人/事件解决方法
				// 经办人	备注
			for(int i=0;i<xlist.size();i++){
				ArrayList dlist=(ArrayList)xlist.get(i);

				AuditUserEvent auben=new AuditUserEvent();
				auben.setDiscTime((Date)dlist.get(0));
				auben.setEndTime((Date)dlist.get(1));
				auben.setCheckTime((String)dlist.get(2));
				auben.setEventName((String)dlist.get(3));
				auben.setLinkSystemName((String)dlist.get(4));
				String sjlx=(String)dlist.get(5);
				String sjlxv=(String)sjtypemap.get(sjlx);

				auben.setEventType(sjlxv);

				auben.setDiscChannel((String)dlist.get(6));
				auben.setEventDesc((String)dlist.get(7));
				auben.setEventCause((String)dlist.get(8));
				auben.setCheckUser((String)dlist.get(9));

				auben.setDutyUser((String)dlist.get(10));
				if(dlist.size()==12){
					auben.setRemark((String)dlist.get(11));
				}



				auditUserEventService.save(auben);
				impnum++;
			}

			}else{
				return Result.ok("文件导入失败！"+filemodelcheckstr);
			}



			} catch (Exception e) {
				log.error("获取对象异常{}", e.getMessage());

		}





		}
		return Result.ok("文件导入成功！数据行数："+impnum);
        //return super.importExcel(request, response, AuditUserEvent.class);
    }

    public String isFileModelOk(InputStream iStream)
	{
    	String flag="";

		int row=0;
		int column=0;
		XSSFWorkbook workbook;
		XSSFSheet sheet;
		XSSFCell cell;
		try {




		workbook=new XSSFWorkbook(iStream);

		sheet=workbook.getSheetAt(0);
		row=sheet.getLastRowNum()+1;//获取行数
		column=sheet.getRow(0).getPhysicalNumberOfCells();//获取列数
		//发现时间	事件解决时间	处置用时	事件系统名称	影响系统名称	事件类型	发现事件渠道	事件描述	事件原因	事件处理人/事件解决方法	经办人	备注
		//判断格式正确
		XSSFRow toprow=sheet.getRow(0);
		XSSFCell cell10 = toprow.getCell(0); // 获取对应元素
		CellType cellType0=cell10.getCellType();
		String zd0=cell10.getStringCellValue();
		if(zd0.equals("发现时间")&&column==12){

		}else{
			flag="文件格式不正确";
		}

			workbook.close();
			iStream.close();

		} catch (Exception e) {

		}


    	return flag;
	}


	 public  ArrayList readdata(InputStream iStream)throws Exception//读取字符串数据
	 {
		  int row=0;
		  int column=0;
		 XSSFWorkbook workbook;
		 XSSFSheet sheet;
		 XSSFCell cell;
		 ArrayList hjxlist=new ArrayList();
		 try {



		 workbook=new XSSFWorkbook(iStream);

		 sheet=workbook.getSheetAt(0);
		 row=sheet.getLastRowNum()+1;//获取行数
		 column=sheet.getRow(0).getPhysicalNumberOfCells();//获取列数



		 for(int i=1;i<row;i++){
			 ArrayList xlist=new ArrayList();
			 for(int j=0;j<column;j++){

				 XSSFRow row1=sheet.getRow(i);
				 XSSFCell cell1 = row1.getCell(j); // 获取对应元素
				 if(cell1==null){
					 break;
				 }
				 CellType str0=cell1.getCellType();

                 if(j==0||j==1){

					 switch (str0) {
						 case STRING: //字符串类型
							 String str = cell1.getStringCellValue();

							 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

							 Date date = format.parse(str);
							 xlist.add(date);
							 break;
						 case BOOLEAN:  //布尔类型
							 boolean str1 = cell1.getBooleanCellValue();
							 xlist.add(str1);
							 break;
						 case NUMERIC: //数值类型
							 Date val = cell1.getDateCellValue();
							 // 定义目标格式
							 SimpleDateFormat outputFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");

							 // 格式化Date对象为字符串
							 String formattedDate1 = outputFormat1.format(val);
							 Date date1 = outputFormat1.parse(formattedDate1);
							 xlist.add(date1);
							 break;
					 }


				 }else {
					 switch (str0) {
						 case STRING: //字符串类型
							 String str = cell1.getStringCellValue();
							 xlist.add(str);
							 break;
						 case BOOLEAN:  //布尔类型
							 boolean str1 = cell1.getBooleanCellValue();
							 xlist.add(str1);
							 break;
						 case NUMERIC: //数值类型
							 double str2 = cell1.getNumericCellValue();
							 xlist.add(str2);
							 break;
					 }
				 }

			 }
			 hjxlist.add(xlist);
		 }

		 workbook.close();
		 iStream.close();

		 } catch (Exception e) {
			 log.error("获取对象异常{}", e.getMessage());
		 }

		 return hjxlist;
	 }

	 public Date getDateFromStr(String str){

		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		 Date date=new Date();
		 try {
		  date = format.parse(str);
		 } catch (Exception e) {
			 log.error("获取对象异常{}", e.getMessage());
		 }
		 return date;

	 }

	 /**
	  *   添加
	  *
	  * @param parstr
	  * @return
	  */
	 @AutoLog(value = "事件库-添加")
	 @ApiOperation(value="事件库-添加", notes="事件库-添加")
	 //@RequiresPermissions("audit:audit_user_event:add")
	 @GetMapping(value = "/saveEvent")
	 public Result<String> saveEvent(@RequestParam(name="parstr",required=true) String parstr) {
		 //String parstr="name:ssss,age:sss";
		 AuditUserEvent auditUserEvent =new AuditUserEvent();
		 try {
		 String strary[]=parstr.split(",");
		 for(int i=0;i<strary.length;i++){
		 	String zdstr=strary[i];
		 	String zdary[]=zdstr.split(":");
		 	String zd=zdary[0];
		 	String zdval=zdary[1];

			 //发现时间
			 if(zd.equals("discTime")){
				 auditUserEvent.setDiscTime(getDateFromStr(zdval));
			 }
			 //事件解决时间
			 if(zd.equals("endTime")){
				 auditUserEvent.setEndTime(getDateFromStr(zdval));
			 }
			 //处置用时
			 if(zd.equals("checkTime")){
				 auditUserEvent.setCheckTime(zdval);
			 }
			 //事件系统名称
			 if(zd.equals("eventName")){
				 auditUserEvent.setEventName(zdval);
			 }

		 	//影响系统名称
		 	if(zd.equals("linkSystemName")){
				auditUserEvent.setLinkSystemName(zdval);
			}
		 	//事件类型
			 if(zd.equals("eventType")){
				 auditUserEvent.setEventType(zdval);
			 }
			 //发现事件渠道
			 if(zd.equals("discChannel")){
				 auditUserEvent.setDiscChannel(zdval);
			 }

			 //事件描述
			 if(zd.equals("eventDesc")){
				 auditUserEvent.setEventDesc(zdval);
			 }
			 //事件原因
			 if(zd.equals("eventCause")){
				 auditUserEvent.setEventCause(zdval);
			 }
			 //事件处理人/事件解决方法
			 if(zd.equals("checkUser")){
				 auditUserEvent.setCheckUser(zdval);
			 }
			 //经办人
			 if(zd.equals("dutyUser")){
				 auditUserEvent.setDutyUser(zdval);
			 }

			 //备注
			 if(zd.equals("remark")){
				 auditUserEvent.setRemark(zdval);
			 }

			 //影响等级
			 if(zd.equals("linkLevel")){
				 auditUserEvent.setLinkLevel(zdval);
			 }

			 //处置状态
			 if(zd.equals("checkStatus")){
				 auditUserEvent.setCheckStatus(zdval);
			 }
			 //影响范围
			 if(zd.equals("linkScope")){
				 auditUserEvent.setLinkScope(zdval);
			 }
			 //处置措施
			 if(zd.equals("checkMethod")){
				 auditUserEvent.setCheckMethod(zdval);
			 }

			 //处置结果
			 if(zd.equals("checkResult")){
				 auditUserEvent.setCheckResult(zdval);
			 }


			 //来源
			 if(zd.equals("discFrom")){
				 auditUserEvent.setDiscFrom(zdval);
			 }

			 //控制项
			 if(zd.equals("act")){
				 auditUserEvent.setAct(zdval);
			 }

		 }
		 auditUserEventService.save(auditUserEvent);
			 return Result.OK("保存事件库成功！");

		 } catch (Exception e) {
			 log.error("事件库接口保存异常", e.getMessage());
			 return Result.error("事件库接口保存异常！"+e.getMessage());
		 }


	 }



}
