package org.springblade.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.utils.AESUtil;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.secure.constant.AuthConstant;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.utils.*;
import org.springblade.modules.csInfo.excel.CsInfoExcel;
import org.springblade.modules.fjInfo.entity.FjInfoEntity;
import org.springblade.modules.fjInfo.service.IFjInfoService;
import org.springblade.modules.rhzf.fwRy.entity.FwRyEntity;
import org.springblade.modules.rhzf.fwRy.excel.FwRyExcel;
import org.springblade.modules.sqjw.userInfo.entity.UserInfoEntity;
import org.springblade.modules.sqjw.userInfo.service.IUserInfoService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.DictBiz;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.excel.FjxxExcel;
import org.springblade.modules.system.excel.UserExcel;
import org.springblade.modules.system.excel.UserYhExcel;
import org.springblade.modules.system.excel.ZxxdUserExcel;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IDictBizService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.*;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.springblade.core.cache.constant.CacheConstant.USER_CACHE;

/**
 * 控制器
 *
 * @author Chill
 */
@NonDS
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SYSTEM_NAME + "/user")
@Api(value = "用户", tags = "用户")
public class UserController {

	private final IUserService userService;
	private final BladeRedis bladeRedis;
	private final IDeptService deptService;
	private final IDictBizService dictBizService;
	private final IFjInfoService fjInfoService;
	private final IUserInfoService userInfoService;


	/**
	 * 查询单条
	 */
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "查看详情", notes = "传入id")
	@GetMapping("/detail")
//	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<User> detail(User user) {
		User detail = userService.getOne(Condition.getQueryWrapper(user));
		if (null != detail && StringUtils.isNotBlank(detail.getSfzh())) {
			detail.setSfzh(AESUtil.decrypt(detail.getSfzh(), "2SexR1rfjZ8CD3M6"));
		}
		return R.data(detail);
	}

	/**
	 * 查询单条
	 */
	@PreAuth(AuthConstant.PERMIT_ALL)
	@ApiOperationSupport(order = 1)

	@GetMapping("/detailByDhhm")
	public R<User> detailByDhhm(User user) {
		QueryWrapper<User> qe = new QueryWrapper<>();
		qe.eq("phone", user.getPhone());
		User detail = userService.getOne(qe);
		return R.data(detail);
	}

	@GetMapping("/detailByDhhm1")
	public R<User> detailByDhhm1(String account) {
		QueryWrapper<User> qe = new QueryWrapper<>();
		qe.eq("phone", account);
		User detail = userService.getOne(qe);
		return R.data(detail);
	}

	/**
	 * 查询单条
	 */
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "查看详情", notes = "传入id")
	@GetMapping("/info")
	public R<UserVO> info(BladeUser user) {
		User detail = userService.getById(user.getUserId());
		return R.data(UserWrapper.build().entityVO(detail));
	}

	/**
	 * 用户列表
	 */
	@GetMapping("/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "realName", value = "姓名", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "列表", notes = "传入account和realName")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<IPage<UserVO>> list(@ApiIgnore @RequestParam Map<String, Object> user, Query query, BladeUser bladeUser) {
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
		IPage<User> pages = userService.page(Condition.getPage(query), (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(User::getTenantId, bladeUser.getTenantId()) : queryWrapper);
		return R.data(UserWrapper.build().pageVO(pages));
	}

	/**
	 * 自定义用户列表
	 */
	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "realName", value = "姓名", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "列表", notes = "传入account和realName")
//	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<IPage<UserVO>> page(@ApiIgnore User user, Query query, String deptId, BladeUser bladeUser) {
		IPage<User> pages = userService.selectUserPage(Condition.getPage(query), user, deptId, (bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? StringPool.EMPTY : bladeUser.getTenantId()));
		return R.data(UserWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义用户列表
	 */
	@GetMapping("/page1")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "realName", value = "姓名", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "列表", notes = "传入account和realName")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<IPage<UserVO>> page1(@ApiIgnore User user, Query query, String deptId, BladeUser bladeUser) {
		IPage<User> pages = userService.selectUserPage1(Condition.getPage(query), user, deptId, (bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? StringPool.EMPTY : bladeUser.getTenantId()));
		return R.data(UserWrapper.build().pageVO(pages));
	}


	/**
	 * 新增或修改
	 */
	@Transactional
	@PostMapping("/submit")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增或修改", notes = "传入User")
//	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R submit(@Valid @RequestBody User user) {
		if (user.getAccount().contains(" ")) {
			return R.fail("登陆账号含有空格，请重新填写");
		}
		Long idByAccount = userService.getIdByAccount(user.getAccount());
		if (idByAccount != null) {
			return R.fail("账号已存在，请重新填写");
		}
		CacheUtil.clear(USER_CACHE);
		user.setTenantId("000000");
		user.setUserType(1);
		user.setPostId("1123598817738675208");
		user.setJh(user.getAccount());
		//user.setStatus(2);
		Integer phone = userService.getPhoneXz(user.getPhone());
		UserInfoEntity userInfoEntity = new UserInfoEntity();
		userInfoEntity.setSfzh(user.getSfzh());
		if (null != user && StringUtils.isNotBlank(user.getSfzh())) {
			user.setSfzh(AESUtil.encrypt(user.getSfzh(), "2SexR1rfjZ8CD3M6"));
		}
		if (phone > 0 && StringUtils.isNotBlank(user.getPhone())) {
			return R.fail(user.getPhone() + "已经存在");
		}
		if (user.getPhone().length() < 11 || user.getPhone().length() >= 12) {
			return R.fail("手机号长度不到11位或超过11位，请重新填写手机号");
		}
		userService.submit(user);
		userInfoEntity.setUserId(user.getId());
		userInfoEntity.setXm(user.getName());
		userInfoEntity.setLxdh(user.getPhone());
		userInfoEntity.setJh(user.getAccount());
		int index;
		String deptId = "";
		if (user.getDeptId().contains(",")) {
			index = user.getDeptId().indexOf(",");
			deptId = user.getDeptId().substring(0, index);
		} else {
			deptId = user.getDeptId();
		}
		Dept dept = deptService.getById(Long.valueOf(deptId));
		if (dept.getDeptCategory() == 7){
			userInfoEntity.setGzdwmc(dept.getParentId().toString());
			userInfoEntity.setSszrq(user.getDeptId());
		}
		if (dept.getDeptCategory() == 6){
			userInfoEntity.setGzdwmc(user.getDeptId());
		}
		userInfoService.save(userInfoEntity);
		return R.success("操作成功");
	}

	/**
	 * 导入用户
	 */
	@PostMapping("/import-user")
	public R importUser(MultipartFile file) {
		int i = 0;
		List<UserExcel> userExcelList = ExcelUtil.read(file, UserExcel.class);
		for (UserExcel userExcel : userExcelList) {
			User user = new User();
			if (StringUtil.isNotBlank(userExcel.getSqName())) {
				user.setDeptId(userService.getSqId(userExcel.getSqName(), userExcel.getPcsName(), userExcel.getFjId()));
			} else if (StringUtil.isNotBlank(userExcel.getPcsName())) {
				user.setDeptId(userService.getPcsId(userExcel.getPcsName(), userExcel.getFjId()));
			} else {
				user.setDeptId(userExcel.getFjId().toString());
			}
			user.setName(userExcel.getRealName());
			user.setPassword("123456");
			user.setAccount(userExcel.getJh().toString());
			user.setPhone(userExcel.getPhone());
			user.setRealName(userExcel.getRealName());
			user.setRoleId(userService.getRoleId(userExcel.getRoleName()));
			user.setSfzh(userExcel.getSfzh());
			if (StringUtil.isBlank(user.getAccount())
				|| StringUtil.isBlank(user.getDeptId())
				|| StringUtil.isBlank(user.getName())
				|| StringUtil.isBlank(user.getPhone())
				|| StringUtil.isBlank(user.getRealName())
				|| StringUtil.isBlank(user.getRoleId())
				|| StringUtil.isBlank(user.getSfzh())) {
				System.out.println(user.getName() + "  丢失信息");
			} else {
				submit(user);
				System.out.println(user.getName() + "  完成");
				i++;
			}
		}
		return R.success("导入 " + i + " 条数据");
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入User")
	public R update(@Valid @RequestBody User user) {
		CacheUtil.clear(USER_CACHE);
		String phone = userService.getPhone(user.getId());
		Integer phones = userService.getPhoneXz(user.getPhone());
		user.setJh(user.getAccount());
		if (null != user && StringUtils.isNotBlank(user.getSfzh())) {
			user.setSfzh(AESUtil.encrypt(user.getSfzh(), "2SexR1rfjZ8CD3M6"));
		}
		if (!user.getPhone().equals(phone) && StringUtils.isNotBlank(user.getPhone()) && phones > 0){
			return R.fail(user.getPhone() + "已经存在");
		}
		if (user.getPhone().length() < 11 || user.getPhone().length() >= 12){
			return R.fail("手机号长度不到11位或超过11位，请重新填写手机号");
		}
		/*if (!phone.equals(user.getPhone())){
			user.setStatus(2);
		}*/
		return R.status(userService.updateUser(user));
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "删除", notes = "传入id集合")
	//@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R remove(@RequestParam String ids) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.removeUser(ids));
	}

	/**
	 * 设置菜单权限
	 */
	@PostMapping("/grant")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "权限设置", notes = "传入roleId集合以及menuId集合")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R grant(@ApiParam(value = "userId集合", required = true) @RequestParam String userIds,
				   @ApiParam(value = "roleId集合", required = true) @RequestParam String roleIds) {
		boolean temp = userService.grant(userIds, roleIds);
		return R.status(temp);
	}

	/**
	 * 重置密码
	 */
	@PostMapping("/reset-password")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "初始化密码", notes = "传入userId集合")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R resetPassword(@ApiParam(value = "userId集合", required = true) @RequestParam String userIds) {
		boolean temp = userService.resetPassword(userIds);
		return R.status(temp);
	}
	/**
	 * delCode
	 */
	@PostMapping("/delCode")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "初始化密码", notes = "传入userId集合")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R delCode(@ApiParam(value = "userId集合", required = true) @RequestParam String userIds) {
		QueryWrapper<User> qe = new QueryWrapper<>();
		qe.eq("id",Long.parseLong(userIds));
		qe.eq("code","");
		boolean temp = userService.update(qe);
		return R.status(temp);
	}
	/**
	 * 修改密码
	 */
	@PostMapping("/update-password")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "修改密码", notes = "传入密码")
	public R updatePassword(BladeUser user, @ApiParam(value = "旧密码", required = true) @RequestParam String oldPassword,
							@ApiParam(value = "新密码", required = true) @RequestParam String newPassword,
							@ApiParam(value = "新密码", required = true) @RequestParam String newPassword1) {
		boolean temp = userService.updatePassword(user.getUserId(), oldPassword, newPassword, newPassword1);
		return R.status(temp);
	}

	/**
	 * 修改基本信息
	 */
	@PostMapping("/update-info")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "修改基本信息", notes = "传入User")
	public R updateInfo(@Valid @RequestBody User user) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.updateUserInfo(user));
	}

	/**
	 * 用户列表
	 */
	@GetMapping("/user-list")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "用户列表", notes = "传入user")
	public R<List<User>> userList(User user, BladeUser bladeUser) {
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user);
		List<User> list = userService.list((!AuthUtil.isAdministrator()) ? queryWrapper.lambda().eq(User::getTenantId, bladeUser.getTenantId()) : queryWrapper);
		return R.data(list);
	}

//	/**
//	 * 导入用户
//	 */
//	@PostMapping("import-user")
//	@ApiOperationSupport(order = 12)
//	@ApiOperation(value = "导入用户", notes = "传入excel")
//	public R importUser(MultipartFile file, Integer isCovered) {
//		UserImporter userImporter = new UserImporter(userService, isCovered == 1);
//		ExcelUtil.save(file, userImporter, UserExcel.class);
//		return R.success("操作成功");
//	}

	/**
	 * 导出用户
	 */
	@GetMapping("export-user")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "导出用户", notes = "传入user")
	public void exportUser(@ApiIgnore @RequestParam Map<String, Object> user, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
		if (!AuthUtil.isAdministrator()) {
			queryWrapper.lambda().eq(User::getTenantId, bladeUser.getTenantId());
		}
		queryWrapper.lambda().eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<UserExcel> list = userService.exportUser(queryWrapper);
		ExcelUtil.export(response, "用户数据" + DateUtil.time(), "用户数据表", list, UserExcel.class);
	}

	/**
	 * 导出模板
	 */
	@GetMapping("export-template")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<UserExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "用户数据模板", "用户数据表", list, UserExcel.class);
	}


	/**
	 * 第三方注册用户
	 */
	@PostMapping("/register-guest")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "第三方注册用户", notes = "传入user")
	public R registerGuest(User user, Long oauthId) {
		return R.status(userService.registerGuest(user, oauthId));
	}

	/**
	 * 配置用户平台信息
	 */
	@PostMapping("/update-platform")
	@ApiOperationSupport(order = 16)
	@ApiOperation(value = "配置用户平台信息", notes = "传入user")
	public R updatePlatform(Long userId, Integer userType, String userExt) {
		return R.status(userService.updatePlatform(userId, userType, userExt));
	}

	/**
	 * 查看平台详情
	 */
	@ApiOperationSupport(order = 17)
	@ApiOperation(value = "查看平台详情", notes = "传入id")
	@GetMapping("/platform-detail")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<UserVO> platformDetail(User user) {
		return R.data(userService.platformDetail(user));
	}

	/**
	 * 用户解锁
	 */
	@PostMapping("/unlock")
	@ApiOperationSupport(order = 18)
	@ApiOperation(value = "账号解锁", notes = "传入id")
	public R unlock(String userIds) {
		if (StringUtil.isBlank(userIds)) {
			return R.fail("请至少选择一个用户");
		}
		List<User> userList = userService.list(Wrappers.<User>lambdaQuery().in(User::getId, Func.toLongList(userIds)));
		userList.forEach(user -> bladeRedis.del(CacheNames.tenantKey(user.getTenantId(), CacheNames.USER_FAIL_KEY, user.getAccount())));
		return R.success("操作成功");
	}

	/**
	 * 身份证号加密
	 */
	@GetMapping("/sfzhEncrypt")
	public R sfzhEncrypt() {
		List<User> userList = userService.getUserList();
		for (User user : userList) {
			user.setSfzh(AESUtil.encrypt(user.getSfzh(), "2SexR1rfjZ8CD3M6"));
			userService.updateSfzh(user);
		}
		return R.success("操作成功");
	}

	/**
	 * 导入用户
	 */
	@PostMapping("/import-zxxdUser")
	public R importZxxdUser(MultipartFile file) {
		List<ZxxdUserExcel> userExcelList = ExcelUtil.read(file, ZxxdUserExcel.class);
		int update = 0;
		int insert = 0;
		for (ZxxdUserExcel userExcel : userExcelList) {
			User user = new User();
			user.setAccount(userExcel.getJh());
			String[] sszzjg = userExcel.getSszzjg().split("/");
			if (userExcel.getRoleName().equals("民警")) {
				user.setRoleId("1677215233615192065");
				user.setDeptId(userService.getPcsIdByPcsName(sszzjg[sszzjg.length-1], 6));
			} else if (userExcel.getRoleName().equals("辅警")) {
				user.setRoleId("1694608532769734657");
				user.setDeptId(userService.getPcsIdByPcsName(sszzjg[sszzjg.length-1], 6));
			} else if (userExcel.getRoleName().equals("派出所管理员")) {
				user.setRoleId("1677215117370056705");
				user.setDeptId(userService.getPcsIdByPcsName(sszzjg[sszzjg.length-1], 6));
			} else if (userExcel.getRoleName().equals("户政管理员")) {
				user.setRoleId("1685514703810543617");
				user.setDeptId(userService.getPcsIdByPcsName(sszzjg[sszzjg.length-1], sszzjg.length == 1 ? 4 : 5));
			}
			user.setName(userExcel.getXm());
			user.setPassword("123456");
			user.setPhone(userExcel.getLxdh());
			user.setRealName(userExcel.getXm());
//			user.setSfzh(userExcel.getGmsfhm());
			if (StringUtil.isBlank(user.getAccount())
				|| StringUtil.isBlank(user.getDeptId())
				|| StringUtil.isBlank(user.getName())
				|| StringUtil.isBlank(user.getRealName())
				|| StringUtil.isBlank(user.getRoleId())) {
				System.out.println(user.getName() + "  丢失信息");
			} else {
				try {
					Long id = userService.getIdByAccount(user.getAccount());
					if (null == id) {
						submit(user);
						insert++;
					} else {
						if (null != user && StringUtils.isNotBlank(user.getSfzh())) {
							user.setSfzh(AESUtil.encrypt(user.getSfzh(), "2SexR1rfjZ8CD3M6"));
						}
						user.setId(id);
						userService.updateUser(user);
						update++;
					}
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
			}
		}
		return R.success("插入" + insert + "条 || " + "更新" + update + "条");
	}

	/**
	 * 首页底部数据
	 */
	@GetMapping("getSyBottom")
	public R getSyBottom(){
		String deptId = AuthUtil.getDeptId();
		String[] split = deptId.split(",");
		SyBottomVO syBottomVO = new SyBottomVO();
		int jxcs = 0;
		int csjc = 0;
		int mdjf = 0;
		for (int i = 0; i < split.length; i++) {
			String dept = split[i];
			SyBottomVO syButton = userService.getSyBottom(dept);
			jxcs += syButton.getJxcs();
			csjc += syButton.getCsjc();
			mdjf += syButton.getMdjf();
		}
		syBottomVO.setJxcs(jxcs);
		syBottomVO.setCsjc(csjc);
		syBottomVO.setMdjf(mdjf);
		return R.data(syBottomVO);
	}

	/**
	 * 首页中间数据
	 */
	@GetMapping("getSyCenter")
	public R getSyCenter(){
		SyCenterVO syCenterVO = new SyCenterVO();
		SyCenterVO syCenter = userService.getSyCenter(AuthUtil.getDeptId());
		SyCenterVO syCenterZs = userService.getSyCenterzs();
		syCenterVO.setFwinfo(syCenter.getFwinfo());
		syCenterVO.setFwry(syCenter.getFwry());
		syCenterVO.setJxcs(syCenter.getJxcs());
		syCenterVO.setCsjc(syCenter.getCsjc());
		syCenterVO.setMdjf(syCenter.getMdjf());
		syCenterVO.setYjjy(syCenter.getYjjy());
		syCenterVO.setFwinfozs(syCenterZs.getFwinfozs());
		syCenterVO.setFwryzs(syCenterZs.getFwryzs());
		syCenterVO.setJxcszs(syCenterZs.getJxcszs());
		syCenterVO.setCsjczs(syCenterZs.getCsjczs());
		syCenterVO.setMdjfzs(syCenterZs.getMdjfzs());
		syCenterVO.setYjjyzs(syCenterZs.getYjjyzs());
		syCenterVO.setFwinfozb((Double.valueOf(syCenter.getFwinfo())/Double.valueOf(syCenterZs.getFwinfozs())) * 100);
		syCenterVO.setFwryzb((Double.valueOf(syCenter.getFwry())/Double.valueOf(syCenterZs.getFwryzs())) * 100);
		syCenterVO.setJxcszb((Double.valueOf(syCenter.getJxcs())/Double.valueOf(syCenterZs.getJxcszs())) * 100);
		syCenterVO.setCsjczb((Double.valueOf(syCenter.getCsjc())/Double.valueOf(syCenterZs.getCsjczs())) * 100);
		syCenterVO.setMdjfzb((Double.valueOf(syCenter.getMdjf())/Double.valueOf(syCenterZs.getMdjfzs())) * 100);
		syCenterVO.setYjjyzb((Double.valueOf(syCenter.getYjjy())/Double.valueOf(syCenterZs.getYjjyzs())) * 100);
		return R.data(syCenterVO);
	}

	/**
	 * 首页上方数据
	 */
	@GetMapping("getSyTop")
	public R getSyTop(){
		String deptId = AuthUtil.getDeptId();
		String[] split = deptId.split(",");
		SyTopVO syTopVO = new SyTopVO();
		int xqzs = 0;
		int jdzs = 0;
		int sqzs = 0;
		int jwszs = 0;
		for (int i = 0; i < split.length; i++) {
			String dept = split[i];
			SyTopVO syTop = userService.getSyTop(dept);
			xqzs += syTop.getXqzs();
			jdzs += syTop.getJdzs();
			sqzs += syTop.getSqzs();
			jwszs += syTop.getJwszs();
		}
		syTopVO.setXqzs(xqzs);
		syTopVO.setJdzs(jdzs);
		syTopVO.setSqzs(sqzs);
		syTopVO.setJwszs(jwszs);
		return R.data(syTopVO);
	}

	/**
	 * 首页获取当前登陆人的下级部门
	 */
	@GetMapping("getBmByDept")
	public R getBmByDept(){
		return R.data(deptService.getBmByDept(AuthUtil.getDeptId()));
	}

	@PostMapping("updateByZp")
	public R updateByZp(User user){
		return R.data(userService.updateById(user));
	}

	@GetMapping("getSyCenterPh")
	public R getSyCenterPh(){
		List<PhVO> list = new ArrayList<>();
		Dept byId = deptService.getDeptCategory(AuthUtil.getDeptId().split(",")[0]);
		List<ZdVO> deptName = deptService.getDeptNameById(AuthUtil.getDeptId(), byId);
		for (ZdVO zdVO:deptName) {
			PhVO phVO = new PhVO();
			PhVO syCenterPh = userService.getSyCenterPh(zdVO.getValue(), AuthUtil.getDeptId());
			phVO.setDeptname(zdVO.getLabel());
			phVO.setSl(syCenterPh.getSl());
			list.add(phVO);
		}
		return R.data(list);
	}

	@GetMapping("getGsdrsjb")
	public R getGsdrsjb( @RequestBody GsdrsjbVO gsdrsjbVO){
		String replace = "";
		if(gsdrsjbVO.getQyMc() !=null){
			replace = gsdrsjbVO.getQyMc().replace(" ", "");
		}
		gsdrsjbVO.setQyMc(replace);
		List<GsdrsjbVO> list = userService.getGsdrsjb(gsdrsjbVO);
		return R.data(list);
	}

	/**
	 * 按照创建时间导出用户数据提供给基座
	 */
	@PostMapping("getYhByCreateTime")
	public void getYhByCreateTime(HttpServletResponse response, User user){
		user.setDeptId(AuthUtil.getDeptId());
		List<UserYhExcel> list = userService.getYhByCreateTime(user);
		for (UserYhExcel userYhExcel:list) {
			userYhExcel.setAccount("'" + userYhExcel.getAccount() + "'");
		}
		ExcelUtil.export(response, "新增用户数据" + DateUtil.time(), "用户表", list, UserYhExcel.class);
		//userService.updateStatus();
	}

	/**
	 * 清除code
	 */
	@PostMapping("qcCode")
	public R qcCode(String id){
		return R.data(userService.qcCode(id));
	}

	/**
	 * 辅警管理
	 */
	@GetMapping("getFjgl")
	public R getFjgl(Query query, User user){
		user.setId(AuthUtil.getUserId());
		user.setDeptId(AuthUtil.getDeptId());
		user.setRealName(AuthUtil.getUserRole());
		if (user.getFjsfzh() != null){
			user.setFjsfzh(AESUtil.encrypt(user.getFjsfzh(), "2SexR1rfjZ8CD3M6"));
		}
		IPage<User> page = userService.getFjgl(Condition.getPage(query), user);
		for (User users:page.getRecords()){
			users.setFjsfzh(AESUtil.decrypt(users.getFjsfzh(), "2SexR1rfjZ8CD3M6"));
		}
		return R.data(page);
	}

	/**
	 * 获取民警启用数量
	 */
	@GetMapping("getMjqysl")
	public R getMjqysl(){
		MjfjVo mjfjVo = new MjfjVo();
		// 获取规定的辅警数量
		int total = dictBizService.getFjsl();
		// 获取当前警号已绑定的辅警数量
		int fjsl = userService.getFjsl(AuthUtil.getUserId());
		// 获取当前警号已绑定的民警
		List<FjInfoEntity> list = userService.getFj(AuthUtil.getUserId());
		mjfjVo.setMjqysl(total);
		mjfjVo.setFjsl(fjsl);
		mjfjVo.setFjInfo(list);
		return R.data(mjfjVo);
	}

	/**
	 * 查看当前派出所下的民警
	 */
	@GetMapping("getPcsFj")
	public R getPcsFj(){
		Dept dept = deptService.getById(Long.valueOf(AuthUtil.getDeptId()));
		return R.data(userService.getPcsFj(dept));
	}

	/**
	 * 编辑辅警
	 */
	@PostMapping("updateFj")
	public R updateFj(@RequestBody User user){
		String phone = userService.getPhone(user.getId());
		Integer phones = userService.getPhoneXz(user.getFjlxdh());
		if (null != user && StringUtils.isNotBlank(user.getFjsfzh())) {
			user.setSfzh(AESUtil.encrypt(user.getFjsfzh(), "2SexR1rfjZ8CD3M6"));
		}
		if (!user.getFjlxdh().equals(phone) && StringUtils.isNotBlank(user.getFjlxdh()) && phones > 0){
			return R.fail(user.getPhone() + "已经存在");
		}
		if (user.getFjlxdh().length() < 11 || user.getFjlxdh().length() > 12){
			return R.fail("手机号长度不到11位或超过11位，请重新填写手机号");
		}
		userService.updateUserFj(user);
		FjInfoEntity fjInfo = new FjInfoEntity();
		Long mjid = userService.getIdByAccount(user.getSsmjjh());
		FjInfoEntity fj = fjInfoService.selectMjFj(mjid, user.getId());
		if (fj != null){
			fjInfo.setMjId(mjid);
			fjInfo.setFjId(user.getId());
			userService.updateFj(fjInfo, user.getMjId());
		} else {
			fjInfo.setMjId(mjid);
			fjInfo.setFjId(user.getId());
			fjInfoService.save(fjInfo);
		}
		return R.success("编辑成功后，第二天才会生效，到时侯需要重新登陆app");
	}

	/**
	 * 启用辅警
	 */
	@PostMapping("getQyfj")
	public R getQyfj(@RequestBody FjInfoEntity fjInfo){
		fjInfo.setMjId(fjInfo.getUserId());
		fjInfo.setFjId(fjInfo.getFjId());
		return R.data(fjInfoService.updateStatusQy(fjInfo));
	}

	/**
	 * 停用辅警
	 */
	@PostMapping("getTyfj")
	public R getTyfj(@RequestBody FjInfoEntity fjInfo){
		fjInfo.setMjId(AuthUtil.getUserId());
		return R.data(fjInfoService.updateStatusTy(fjInfo));
	}

	/**
	 * 新增辅警
	 */
	@PostMapping("saveFj")
	public R saveFj(@RequestBody User user){
		Integer phone = userService.getPhoneXz(user.getFjlxdh());
		Long mjids = userService.getIdByAccount(user.getAccount());
		if (null != user && StringUtils.isNotBlank(user.getFjsfzh())) {
			user.setSfzh(AESUtil.encrypt(user.getFjsfzh(), "2SexR1rfjZ8CD3M6"));
		}
		if (phone > 0 && StringUtils.isNotBlank(user.getFjlxdh())) {
			return R.fail(user.getFjlxdh() + "已经存在");
		}
		if (user.getFjlxdh().length() < 11 || user.getFjlxdh().length() > 12) {
			return R.fail("手机号长度不到11位或超过11位，请重新填写手机号");
		}
		if (mjids != null) {
			return R.fail("当前账号已存在");
		}
		user.setTenantId("000000");
		user.setUserType(1);
		user.setPassword("10470c3b4b1fed12c3baac014be15fac67c6e815");
		user.setName(user.getFjxm());
		user.setRealName(user.getFjxm());
		user.setPhone(user.getFjlxdh());
		user.setRoleId("1694608532769734657");
		user.setPostId("1123598817738675208");
		user.setDeptId(user.getGzdw());
		userService.save(user);
		FjInfoEntity fjInfo = new FjInfoEntity();
		Long mjid = userService.getIdByAccount(user.getSsmjjh());
		fjInfo.setMjId(mjid);
		fjInfo.setFjId(user.getId());
		fjInfoService.save(fjInfo);
		return R.success("新增成功");
	}

	/**
	 * 删除辅警
	 */
	@PostMapping("deleteFj")
	public R deleteFj(@RequestBody User user){
		userService.deleteFj(user.getId());
		fjInfoService.deleteFj(user.getId());
		return R.success("删除成功");
	}

	/**
	 * 导出数据
	 */
	@GetMapping("/export-fjxx")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出数据", notes = "传入fwRy")
	public void exportFwRy(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) {
		User user = userService.getById(AuthUtil.getUserId());
		params.put("id", AuthUtil.getUserId());
		params.put("deptId", AuthUtil.getDeptId());
		params.put("roleId", user.getRoleId());
		if (params.get("fjsfzh") != null){
			params.put("fjsfzh",AESUtil.encrypt(params.get("fjsfzh").toString(), "2SexR1rfjZ8CD3M6"));
		}
		List<FjxxExcel> list = userService.exportFjxx(params);
		ExcelUtil.export(response, "辅警信息" + DateUtil.time(), "辅警信息", list, FjxxExcel.class);
	}

	/**
	 * 根据分局id查询分局下的派出所
	 */
	@GetMapping("getPcsByFjId")
	public R getPcsByFjId(){
		return R.data(deptService.getPcsByFjId(AuthUtil.getDeptId()));
	}

	/**
	 * 重置密码
	 */
	@PostMapping("czmm")
	public R czmm(User user){
		user.setPassword("10470c3b4b1fed12c3baac014be15fac67c6e815");
		return R.data(userService.updateById(user));
	}

	/**
	 * 修改密码
	 */
	@PostMapping("getXgmm")
	public R getXgmm(User user){
		user.setPassword(DigestUtil.encrypt(user.getPassword()));
		return R.data(userService.updateById(user));
	}

	/**
	 * 辖区概况
	 */
	@GetMapping("getXqgk")
	public R getXqgk() {
		XqgkVO xqgkVO = new XqgkVO();
		// 房屋总数
		Integer fwzs = userService.getFwzs(AuthUtil.getDeptId());
		xqgkVO.setFwzs(fwzs);
		// 实有单位总数
		Integer sydwzs = userService.getSydwzs(AuthUtil.getDeptId());
		xqgkVO.setSydwzs(sydwzs);
		// 常住人口数
		Integer czrk = userService.getCzrk(AuthUtil.getDeptId());
		xqgkVO.setCzrk(czrk);
		// 寄住人口数
		Integer jzrk = userService.getJzrk(AuthUtil.getDeptId());
		xqgkVO.setJzrk(jzrk);
		// 暂住人口数
		Integer zzrk = userService.getZzrk(AuthUtil.getDeptId());
		xqgkVO.setZzrk(zzrk);
		// 境外人口数
		Integer jwrk = userService.getJwrk(AuthUtil.getDeptId());
		xqgkVO.setJwrk(jwrk);
		// 未落人口数
		Integer wlrk = userService.getWlrk(AuthUtil.getDeptId());
		xqgkVO.setWlrk(wlrk);
		// 实有人口总数
		xqgkVO.setSyrkzs(czrk + jzrk + zzrk + jwrk + wlrk);
		// 重点人口总数(需对接广立)
		xqgkVO.setZdrkzs(0);
		// 涉稳重点人总数
		Integer swzdrzs = userService.getSwzdrzs(AuthUtil.getDeptId());
		xqgkVO.setSwzdrzs(swzdrzs);
		// 特定对象总数
		Integer tddxzs = userService.getTddxzs(AuthUtil.getDeptId());
		xqgkVO.setTddxzs(tddxzs);
		// 矛盾纠纷总数
		Integer mdjfzs = userService.getMdjfzs(AuthUtil.getDeptId());
		xqgkVO.setMdjfzs(mdjfzs);
		// 九小场所总数
		Integer jxcszs = userService.getJxcszs(AuthUtil.getDeptId());
		xqgkVO.setJxcszs(jxcszs);
		return R.data(xqgkVO);
	}

	/**
	 * 根据身份证号查询人员
	 */
	@GetMapping("selectRyxxBySfzh")
	public R selectRyxxBySfzh(String sfzh) {
		return R.data(userService.selectRyxxBySfzh(sfzh));
	}
}
