package com.zhgd.xmgl.modules.basicdata.controller.admin;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhgd.annotation.OperLog;
import com.zhgd.jeecg.common.api.vo.Result;
import com.zhgd.jeecg.common.system.query.QueryGenerator;
import com.zhgd.jeecg.common.util.oConvertUtils;
import com.zhgd.xmgl.modules.basicdata.dto.SystemUserDto;
import com.zhgd.xmgl.modules.basicdata.entity.SystemUser;
import com.zhgd.xmgl.modules.basicdata.service.ISystemUserService;
import com.zhgd.xmgl.modules.basicdata.vo.SystemUserVo;
import com.zhgd.xmgl.security.JwtTokenProvider;
import com.zhgd.xmgl.security.SecurityUser;
import com.zhgd.xmgl.security.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
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.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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


 /**
 * @Title: Controller
 * @Description: 系统用户表
 * @author： pds
 * @date：   2023-02-08
 * @version： V1.0
 */
@RestController
@RequestMapping("/xmgl/systemUser")
@Slf4j
@Api(tags = "账号")
public class SystemUserController {
	@Autowired
	private ISystemUserService systemUserService;
	
	@Autowired
	private JwtTokenProvider jwtTokenProvider;
	
	/**
	  * 分页列表查询
	 * @return
	 */
	@OperLog(operModul = "用户管理", operType = "分页查询", operDesc = "分页列表查询系统用户表信息")
	@ApiOperation(value = " 分页列表查询系统用户表信息", notes = "分页列表查询系统用户表信息", httpMethod="POST")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "account", value = "用户名", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userTel", value = "手机号码", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "state", value = "状态(0:停用；1:启用)", paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "beginTime", value = "开始日期", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "endTime", value = "结束日期", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "pageNo", value = "页数", paramType = "query", required = true, defaultValue = "1", dataType = "Integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", required = true, defaultValue = "10", dataType = "Integer")
	})
	@PostMapping(value = "/page")
	public Result<IPage<SystemUserDto>> queryPageList(@RequestBody Map<String, Object> map) {
		Result<IPage<SystemUserDto>> result = new Result<IPage<SystemUserDto>>();
		IPage<SystemUserDto> pageList = systemUserService.getPageList(map);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	 /**
	  * 分页列表查询
	  * @param systemUser
	  * @param req
	  * @return
	  */
	 @OperLog(operModul = "用户管理", operType = "列表查询", operDesc = "列表查询系统用户表信息")
	 @ApiOperation(value = " 列表查询系统用户表信息", notes = "列表查询系统用户表信息", httpMethod="POST")
	 @PostMapping(value = "/list")
	 public Result<List<SystemUser>> queryList(@RequestBody SystemUser systemUser,
													   HttpServletRequest req) {
		 Result<List<SystemUser>> result = new Result<List<SystemUser>>();
		 SecurityUser user = SecurityUtil.getUser();
		 systemUser.setAccountType(user.getAccountType());
		 systemUser.setSn(user.getSn());
		 QueryWrapper<SystemUser> queryWrapper = QueryGenerator.initQueryWrapper(systemUser, req.getParameterMap());
		 List<SystemUser> list = systemUserService.list(queryWrapper);
		 result.setSuccess(true);
		 result.setResult(list);
		 return result;
	 }
	
	/**
	  *   添加
	 * @param systemUserVo
	 * @return
	 */
	@OperLog(operModul = "用户管理", operType = "新增", operDesc = "添加系统用户表信息")
	@ApiOperation(value = " 添加系统用户表信息", notes = "添加系统用户表信息" , httpMethod="POST")
	@PostMapping(value = "/add")
	public Result<SystemUser> add(@RequestBody SystemUserVo systemUserVo) {
		Result<SystemUser> result = new Result<SystemUser>();
		SystemUser systemUser1 = systemUserService.getOne(Wrappers.<SystemUser>lambdaQuery().eq(SystemUser::getAccount, systemUserVo.getAccount()));
		if (systemUser1 != null) {
			result.error500("用户名已被使用");
			return result;
		}
		systemUserService.saveInfo(systemUserVo);
		result.success("添加成功！");
		return result;
	}
	
	/**
	  *  编辑
	 * @param systemUser
	 * @return
	 */
//	@PreAuthorize("@pms.hasPermission('sys_user_edit')")
	@OperLog(operModul = "用户管理", operType = "修改", operDesc = "编辑系统用户表信息")
	@ApiOperation(value = "编辑系统用户表信息", notes = "编辑系统用户表信息" , httpMethod="POST")
	@PostMapping(value = "/edit")
	public Result<SystemUser> edit(@RequestBody SystemUser systemUser) {
		Result<SystemUser> result = new Result<SystemUser>();
		SystemUser systemUserEntity = systemUserService.getById(systemUser.getUserId());
		if(systemUserEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = systemUserService.updateById(systemUser);
			if(ok) {
				result.success("修改成功!");
			}
		}
		return result;
	}
	
	/**
	  *   通过id删除
	 * @return
	 */
	@OperLog(operModul = "用户管理", operType = "删除", operDesc = "删除系统用户表信息")
	@ApiOperation(value = "删除系统用户表信息", notes = "删除系统用户表信息" , httpMethod="POST")
	@ApiImplicitParam(name = "id", value = "系统用户表ID", paramType = "query", required = true, dataType = "Integer")
	@PostMapping(value = "/delete")
	public Result<SystemUser> delete(@RequestBody Map<String,Object> map) {
		Result<SystemUser> result = new Result<SystemUser>();
		SystemUser systemUser = systemUserService.getById(MapUtils.getString(map,"id"));
		 if(systemUser==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = systemUserService.removeById(MapUtils.getString(map,"id"));
			if(ok) {
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @return
	 */
	@OperLog(operModul = "用户管理", operType = "批量删除", operDesc = "批量删除系统用户表信息")
	@ApiOperation(value = "批量删除系统用户表信息", notes = "批量删除系统用户表信息",  httpMethod="POST")
    @ApiImplicitParam(name = "ids", value = "系统用户表ID字符串", paramType = "query", required = true, dataType = "String")
	@PostMapping(value = "/deleteBatch")
	public Result<SystemUser> deleteBatch(@RequestBody Map<String,Object> map) {
		String ids = MapUtils.getString(map,"ids");
		Result<SystemUser> result = new Result<SystemUser>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.systemUserService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @return
	 */
	@OperLog(operModul = "用户管理", operType = "查询", operDesc = "通过id查询系统用户表信息")
	@ApiOperation(value = "通过id查询系统用户表信息", notes = "通过id查询系统用户表信息" , httpMethod="POST")
    @ApiImplicitParam(name = "id", value = "系统用户表ID", paramType = "query", required = true, dataType = "Integer")
	@PostMapping(value = "/queryById")
	public Result<SystemUser> queryById(@RequestBody Map<String,Object> map) {
		Result<SystemUser> result = new Result<SystemUser>();
		SystemUser systemUser = systemUserService.getById(MapUtils.getString(map,"id"));
		if(systemUser==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(systemUser);
			result.setSuccess(true);
		}
		return result;
	}

	 /**
	  * 通过政务id查询系统用户表信息
	  * @return
	  */
	 @OperLog(operModul = "用户管理", operType = "查询", operDesc = "通过政务id查询系统用户表信息")
	 @ApiOperation(value = "通过政务id查询系统用户表信息", notes = "通过政务id查询系统用户表信息" , httpMethod="POST")
	 @ApiImplicitParam(name = "governmentId", value = "政务id", paramType = "query", required = true, dataType = "Integer")
	 @PostMapping(value = "/queryByGovernmentId")
	 public Result<SystemUser> queryByGovernmentId(@RequestBody Map<String,Object> map) {
		 Result<SystemUser> result = new Result<SystemUser>();
		 SystemUser systemUser = systemUserService.getOne(Wrappers.<SystemUser>lambdaQuery()
				 .eq(SystemUser::getSn, MapUtils.getString(map,"governmentId"))
				 .eq(SystemUser::getIsManager, true));
		 if(systemUser==null) {
			 result.error500("未找到对应实体");
		 }else {
			 result.setResult(systemUser);
			 result.setSuccess(true);
		 }
		 return result;
	 }

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @OperLog(operModul = "用户管理", operType = "导出", operDesc = "导出excel系统用户表信息")
  @ApiOperation(value = "导出excel系统用户表信息", notes = "导出excel系统用户表信息" , httpMethod="POST")
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<SystemUser> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              SystemUser systemUser = JSON.parseObject(deString, SystemUser.class);
              queryWrapper = QueryGenerator.initQueryWrapper(systemUser, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          throw new RuntimeException(e);
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<SystemUser> pageList = systemUserService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "系统用户表列表");
      mv.addObject(NormalExcelConstants.CLASS, SystemUser.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("系统用户表列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @OperLog(operModul = "用户管理", operType = "导入", operDesc = "通过excel导入系统用户表信息")
   @ApiOperation(value = "通过excel导入系统用户表信息", notes = "通过excel导入系统用户表信息", httpMethod="POST")
  @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<SystemUser> listSystemUsers = ExcelImportUtil.importExcel(file.getInputStream(), SystemUser.class, params);
              for (SystemUser systemUserExcel : listSystemUsers) {
                  systemUserService.save(systemUserExcel);
              }
              return Result.ok("文件导入成功！数据行数：" + listSystemUsers.size());
          } catch (Exception e) {
              log.error(e.getMessage());
              return Result.error("文件导入失败！");
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }


	 /**
	  * 用户登录
	  * @return
	  */
	 @OperLog(operModul = "用户账号", operType="登录", operDesc = "用户登录")
	 @ApiOperation(value = "用户登录", notes = "用户登录" , httpMethod="POST")
	 @PostMapping(value = "/login")
	 public Result<SystemUser> login(@RequestBody SystemUser systemUser) {
		 Result<SystemUser> result = new Result<SystemUser>();
		 SystemUser userInfo = systemUserService.getOne(Wrappers.<SystemUser>lambdaQuery()
				 .eq(SystemUser::getAccount, systemUser.getAccount())
				 .eq(SystemUser::getShowPassword, systemUser.getShowPassword()));
		 if(userInfo==null) {
			 result.error500("登录名或密码错误");
		 } else if(userInfo.getState() == 0) {
			 result.error500("账号已被禁用,请联系管理员");
		 } else {
			 String token = jwtTokenProvider.createToken(userInfo.getAccount(), 3600 * 24);
			 userInfo.setToken(token);
			 result.setResult(userInfo);
			 result.setSuccess(true);
		 }
		 return result;
	 }

	 /**
	  * 用户登出
	  * @return
	  */
	 @OperLog(operModul = "用户账号", operType="登出", operDesc = "用户登出")
	 @ApiOperation(value = "用户登出", notes = "用户登出" , httpMethod="POST")
	 @PostMapping(value = "/logout")
	 public Result<SystemUser> logout() {
		 Result<SystemUser> result = new Result<SystemUser>();
		 SecurityUser user = SecurityUtil.getUser();
		 jwtTokenProvider.removeToken(user.getUsername());
		 result.setSuccess(true);
		 return result;
	 }

//	 @Autowired
//	 private MqttCustomerClient mqttCustomerClient;
//	 @ApiOperation(value = "test", notes = "test" , httpMethod="POST")
//	 @PostMapping(value = "/test")
//	 public void test() {
//		 for (int i = 0; i < 10; i++) {
//			 mqttCustomerClient.pushlish("test-topic", "hello mqtt............" + i);
//			 try {
//				 Thread.sleep(3000);
//			 } catch (InterruptedException e) {
//				 e.printStackTrace();
//			 }
//		 }
//	 }
}
