package com.zzsn.modules.kgj.controller;

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 com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zzsn.common.api.vo.Result;
import com.zzsn.common.system.query.QueryGenerator;
import com.zzsn.common.util.oConvertUtils;
import com.zzsn.modules.kgj.entity.CesSysSecret;
import com.zzsn.modules.kgj.entity.MgSysSecret;
import com.zzsn.modules.kgj.entity.VO.CesSysSecretVo;
import com.zzsn.modules.kgj.service.IMgSysSecretService;

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.apache.commons.lang.StringUtils;
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 com.zzsn.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 com.zzsn.common.aspect.annotation.AutoLog;

 /**
 * @Description: MG_SYS_SECRET
 * @Author: zzsn-boot
 * @Date:   2021-03-15
 * @Version: V1.0
 */
@Api(tags="MG_SYS_SECRET")
@RestController
@RequestMapping("/kgj/mgSysSecret")
@Slf4j
public class MgSysSecretController extends JeecgController<MgSysSecret, IMgSysSecretService> {
	@Autowired
	private IMgSysSecretService mgSysSecretService;
	
	/**
	 * 分页列表查询
	 *
	 * @param mgSysSecret
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "MG_SYS_SECRET-分页查询")
	@ApiOperation(value = "MG_SYS_SECRET-分页查询", notes="MG_SYS_SECRET-根据参数传入的sysUser对象和分页控制参数，对数据进行数据库查询后，封装成page分页对象并返回")
	@GetMapping(value = "")
	public Result<?> queryPageList(MgSysSecret mgSysSecret,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
//		QueryWrapper<MgSysSecret> queryWrapper = QueryGenerator.initQueryWrapper(mgSysSecret, req.getParameterMap());
//		Page<MgSysSecret> page = new Page<MgSysSecret>(pageNo, pageSize);
//		IPage<MgSysSecret> pageList = mgSysSecretService.page(page, queryWrapper);
//		return Result.ok(pageList);
		Page<MgSysSecret> page = new Page<MgSysSecret>(pageNo, pageSize);
		IPage<MgSysSecret> pageList = mgSysSecretService.selectByPage1(page,mgSysSecret);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param mgSysSecret
	 * @return
	 */
	@AutoLog(value = "MG_SYS_SECRET-添加")
	@ApiOperation(value="MG_SYS_SECRET-添加", notes="MG_SYS_SECRET-通过参数传入json格式sysUser对象，在数据库中生成一条新的数据")
	@PostMapping(value = "")
	public Result<?> add(@RequestBody MgSysSecret mgSysSecret) {
		mgSysSecretService.save(mgSysSecret);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param mgSysSecret
	 * @return
	 */
	@AutoLog(value = "MG_SYS_SECRET-编辑")
	@ApiOperation(value="MG_SYS_SECRET-编辑", notes="MG_SYS_SECRET-编辑")
	@PutMapping(value = "")
	public Result<?> edit(@RequestBody MgSysSecret mgSysSecret) {
		mgSysSecretService.updateById(mgSysSecret);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "MG_SYS_SECRET-通过id删除")
	@ApiOperation(value="MG_SYS_SECRET-通过id删除", notes="MG_SYS_SECRET-通过id删除")
	@DeleteMapping(value = "/{id}")
	public Result<?> delete(@PathVariable("id") String id) {
		mgSysSecretService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "MG_SYS_SECRET-批量删除")
	@ApiOperation(value="MG_SYS_SECRET-批量删除", notes="MG_SYS_SECRET-批量删除")
	@DeleteMapping(value = "")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.mgSysSecretService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "MG_SYS_SECRET-通过id查询")
	@ApiOperation(value="MG_SYS_SECRET-通过id查询", notes="MG_SYS_SECRET-通过id查询")
	@GetMapping(value = "/{id}")
	public Result<?> queryById(@PathVariable("id")   String id) {
		MgSysSecret mgSysSecret = mgSysSecretService.getById(id);
		if(mgSysSecret==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(mgSysSecret);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param mgSysSecret
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MgSysSecret mgSysSecret) {
        return super.exportXls(request, mgSysSecret, MgSysSecret.class, "MG_SYS_SECRET");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<MgSysSecret> importList = ExcelImportUtil.importExcel(file.getInputStream(), MgSysSecret.class, params);
				if(CollectionUtils.isEmpty(importList)){
					return Result.error("文件内容不能为空");
				}
				//update-begin-author:taoyan date:20190528 for:批量插入数据
				//查询数据库中存在的所有密点
				List<MgSysSecret> dataList = mgSysSecretService.list();
				if(CollectionUtils.isEmpty(dataList)){
					//如果数据库中的密点内容为空，则不用比对，直接导入
					boolean b = mgSysSecretService.saveBatch(importList);
					if(!b){
						log.info("导入密点库失败");
						return Result.error("文件导入失败!");
					}
					return Result.ok("文件导入成功！数据行数：" + importList.size());
				}
				Map<String, MgSysSecret> map = dataList.stream().collect(Collectors.toMap(mgSysSecret -> {
					String content = mgSysSecret.getContent();
					if(StringUtils.isNotBlank(content)){
						return content.trim();
					}
					return content;
				}, mgSysSecret -> mgSysSecret,(k1,k2)->k2));
				//数据库中的密点不为空，则进行比较
				List<MgSysSecret> insertList = new ArrayList<>();
				//重复的数据
				List<String> repeatList = new ArrayList<>();
				for (MgSysSecret mgSysSecret : importList) {
					String content = mgSysSecret.getContent();
					if(StringUtils.isNotBlank(content)){
						//去除前后空格
						String trim = content.trim();
						if(map.get(trim) ==null){
							//等于空，说明数据库里边不存在
							insertList.add(mgSysSecret);
						}else{
							//不等于空，说明存在
							repeatList.add(trim);
						}
					}

				}
				long start = System.currentTimeMillis();
				if(!(insertList.size()>0)){
					//插入的数据为空，说明都是重复的，直接返回
					return Result.ok("文件导入成功！数据行数：" + insertList.size()+" 重复的密点内容行数："+repeatList.size());
				}
				boolean b = mgSysSecretService.saveBatch(insertList);
				if(!b){
					log.info("导入密点库失败");
					return Result.error("文件导入失败!");
				}
				//400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				//1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				//update-end-author:taoyan date:20190528 for:批量插入数据
				return Result.ok("文件导入成功！数据行数：" + insertList.size()+" 重复的密点内容行数："+repeatList.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
    }

}
