package org.springblade.modules.sqjw.userInfo.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.utils.AESUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.JlrhJws.entity.JlrhJwsEntity;
import org.springblade.modules.JlrhJws.service.IJlrhJwsService;
import org.springblade.modules.csInfo.entity.CsInfoEntity;
import org.springblade.modules.csInfo.service.ICsInfoService;
import org.springblade.modules.csjcInfo.entity.CsjcInfoEntity;
import org.springblade.modules.csjcInfo.service.ICsjcInfoService;
import org.springblade.modules.log.logUser.entity.LogUserEntity;
import org.springblade.modules.log.logUser.service.ILogUserService;
import org.springblade.modules.log.zxLog.entity.ZxLogEntity;
import org.springblade.modules.log.zxLog.service.IZxLogService;
import org.springblade.modules.mdjfdj.entity.MdjfDjEntity;
import org.springblade.modules.mdjfdj.service.IMdjfDjService;
import org.springblade.modules.mdjfhf.entity.HfEntity;
import org.springblade.modules.mdjfhf.service.IHfService;
import org.springblade.modules.mdjfry.entity.MdjfRyEntity;
import org.springblade.modules.mdjfry.service.IMdjfRyService;
import org.springblade.modules.mdjftj.entity.MdjfTjEntity;
import org.springblade.modules.mdjftj.service.IMdjfTjService;
import org.springblade.modules.rhzf.fwFz.entity.FwFzEntity;
import org.springblade.modules.rhzf.fwFz.service.IFwFzService;
import org.springblade.modules.rhzf.fwInfo.entity.FwInfoEntity;
import org.springblade.modules.rhzf.fwInfo.service.IFwInfoService;
import org.springblade.modules.rhzf.fwInfo.vo.RkxxVO;
import org.springblade.modules.rhzf.fwRy.entity.FwRyEntity;
import org.springblade.modules.rhzf.fwRy.service.IFwRyService;
import org.springblade.modules.rhzf.ryCzrk.entity.RyCzrkEntity;
import org.springblade.modules.rhzf.ryCzrk.service.IRyCzrkService;
import org.springblade.modules.rhzf.ryJwrk.entity.RyJwrkEntity;
import org.springblade.modules.rhzf.ryJwrk.service.IRyJwrkService;
import org.springblade.modules.rhzf.ryJzrk.entity.RyJzrkEntity;
import org.springblade.modules.rhzf.ryJzrk.service.IRyJzrkService;
import org.springblade.modules.rhzf.ryWlrk.entity.RyWlrkEntity;
import org.springblade.modules.rhzf.ryWlrk.service.IRyWlrkService;
import org.springblade.modules.rhzf.ryZzrk.entity.RyZzrkEntity;
import org.springblade.modules.rhzf.ryZzrk.service.IRyZzrkService;
import org.springblade.modules.sqjw.pcsInfo.service.IPcsInfoService;
import org.springblade.modules.sqjw.userInfo.dto.HistoryDataDTO;
import org.springblade.modules.sqjw.userInfo.entity.UserInfoEntity;
import org.springblade.modules.sqjw.userInfo.excel.UserInfoExcel;
import org.springblade.modules.sqjw.userInfo.service.IUserInfoService;
import org.springblade.modules.sqjw.userInfo.vo.UserInfoVO;
import org.springblade.modules.sqjw.userInfo.vo.UserZdVO;
import org.springblade.modules.sqjw.userInfo.wrapper.UserInfoWrapper;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.ZdVO;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
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 BladeX
 * @since 2024-02-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-userInfo/userInfo")
@Api(value = "社区警务-警员信息", tags = "社区警务-警员信息接口")
public class UserInfoController extends BladeController {

	private final IUserInfoService userInfoService;

	private final ILogUserService userLogService;

	private final IPcsInfoService pcsInfoService;

	private final IUserService userService;

	private final IJlrhJwsService jwsService;

	private final ICsInfoService csInfoService;

	private final ICsjcInfoService jcInfoService;

	private final IMdjfDjService mdjfdjService;

	private final IMdjfRyService mdjfryService;

	private final IMdjfTjService mdjftjService;

	private final IHfService hfService;

	private final IFwInfoService fwInfoService;

	private final IFwFzService fwFzService;

	private final IFwRyService fwRyService;

	private final IRyCzrkService czrkService;

	private final IRyJwrkService jwrkService;

	private final IRyJzrkService jzrkService;

	private final IRyWlrkService wlrkService;

	private final IRyZzrkService zzrkService;

	private final IZxLogService zxLogService;

	/**
	 * 社区警务-警员信息 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入userInfo")
	public R detail(@RequestParam Map<String, Object> params) {
		UserInfoVO detail = userInfoService.getDetail(params);
		return R.data(detail);
	}

	/**
	 * 社区警务-警员信息 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入userInfo")
	public R<IPage<UserInfoVO>> list(@ApiIgnore @RequestParam Map<String, Object> userInfo, Query query) {
		IPage<UserInfoEntity> pages = userInfoService.page(Condition.getPage(query), Condition.getQueryWrapper(userInfo, UserInfoEntity.class));
		return R.data(UserInfoWrapper.build().pageVO(pages));
	}

	/**
	 * 社区警务-警员信息 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入userInfo")
	public R<IPage<UserInfoVO>> page(@RequestParam Map<String, Object> params, Query query) {
		params.put("deptId", AuthUtil.getDeptId());
		IPage<UserInfoVO> pages = userInfoService.selectUserInfoPage(Condition.getPage(query), params);
		return R.data(pages);
	}

	/**
	 * 社区警务-警员信息 新增
	 */
	@Transactional
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入userInfo")
	public R save(@Valid @RequestBody UserInfoEntity userInfo) {
		if (StringUtils.isNotBlank(userInfo.getZwlb()) && userInfo.getZwlb().equals("1760218852527259650")) {
			// 判断这个派出所是否已经设置过所长
			int szNum = userInfoService.getSzNum(userInfo.getGzdwmc(), userInfo.getJh());
			if (szNum > 0) {
				return R.fail("同一个派出所无法设置多名所长");
			}
		}
		// 保存到 jdrh.blade_user
		CacheUtil.clear(USER_CACHE);
		User user = new User();
		user.setTenantId("000000");
		user.setUserType(1);
		user.setAccount(userInfo.getJh());
		user.setPassword("123456");
		user.setName(userInfo.getXm());
		user.setRealName(userInfo.getXm());
		user.setAvatar(userInfo.getZp());
		user.setPhone(userInfo.getLxdh());
		user.setSex(userInfo.getXb());
		if (StringUtils.isNotBlank(userInfo.getZwlb())) {
			if (userInfo.getZwlb().equals("1760218852527259650") || userInfo.getZwlb().equals("1760218852527259652")) {
				user.setRoleId("1677215117370056705");
			} else {
				user.setRoleId("1677215233615192065");
			}
		}
		user.setJh(userInfo.getJh());
//		user.setRoleId(userService.getRoleId(userExcel.getRoleName()));
		if (StringUtils.isNotBlank(userInfo.getSsjg())) {
			user.setDeptId(userInfo.getSsjg());
		} else if (StringUtils.isNotBlank(userInfo.getSszrq())) {
			user.setDeptId(userInfo.getSszrq());
		} else {
			user.setDeptId(userInfo.getGzdwmc());
		}
		user.setPostId("1123598817738675208");
		if (null != userInfo && StringUtils.isNotBlank(userInfo.getSfzh())) {
			user.setSfzh(AESUtil.encrypt(userInfo.getSfzh(), "2SexR1rfjZ8CD3M6"));
		}
		userService.submit(user);
		// 保存到 jdrh.blade_user_info
		userInfo.setUserId(user.getId());
		userInfoService.save(userInfo);
		// 保存日志到 log.log_user
		LogUserEntity userLogEntity = new LogUserEntity();
		BeanUtil.copy(userInfo, userLogEntity);
		return R.status(userLogService.save(userLogEntity));
	}

	/**
	 * 社区警务-警员信息 修改
	 */
	@Transactional
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入userInfo")
	public R update(@Valid @RequestBody UserInfoEntity userInfo) {
		if (StringUtils.isNotBlank(userInfo.getZwlb()) && userInfo.getZwlb().equals("1760218852527259650")) {
			// 判断这个派出所是否已经设置过所长
			int szNum = userInfoService.getSzNum(userInfo.getGzdwmc(), userInfo.getJh());
			if (szNum > 0) {
				return R.fail("同一个派出所无法设置多名所长");
			}
		}
		// 保存到 jdrh.blade_user
		CacheUtil.clear(USER_CACHE);
		User user = new User();
		user.setId(userInfo.getUserId());
		user.setAccount(userInfo.getJh());
		user.setName(userInfo.getXm());
		user.setRealName(userInfo.getXm());
		user.setAvatar(userInfo.getZp());
		user.setPhone(userInfo.getLxdh());
		user.setSex(userInfo.getXb());
		if (StringUtils.isNotBlank(userInfo.getZwlb())) {
			if (userInfo.getZwlb().equals("1760218852527259650") || userInfo.getZwlb().equals("1760218852527259652")) {
				user.setRoleId("1677215117370056705");
			} else {
				user.setRoleId("1677215233615192065");
			}
		}
		user.setJh(userInfo.getJh());
		if (StringUtils.isNotBlank(userInfo.getSsjg())) {
			user.setDeptId(userInfo.getSsjg());
		} else if (StringUtils.isNotBlank(userInfo.getSszrq())) {
			user.setDeptId(userInfo.getSszrq());
		} else {
			user.setDeptId(userInfo.getGzdwmc());
		}
		if (null != userInfo && StringUtils.isNotBlank(userInfo.getSfzh())) {
			user.setSfzh(AESUtil.encrypt(userInfo.getSfzh(), "2SexR1rfjZ8CD3M6"));
		}
		userService.updateUser(user);
		// 保存到 jdrh.blade_user_info
		userInfoService.updateById(userInfo);
		// 保存日志到 log.log_user
		LogUserEntity userLogEntity = new LogUserEntity();
		BeanUtil.copy(userInfo, userLogEntity);
		return R.status(userLogService.save(userLogEntity));
	}

	/**
	 * 社区警务-警员信息 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入userInfo")
	public R submit(@Valid @RequestBody UserInfoEntity userInfo) {
		return R.status(userInfoService.saveOrUpdate(userInfo));
	}

	/**
	 * 社区警务-警员信息 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(userInfoService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 导出数据
	 */
	@GetMapping("/export-userInfo")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出数据", notes = "传入userInfo")
	public void exportUserInfo(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) {
		params.put("deptId", AuthUtil.getDeptId());
		List<UserInfoExcel> list = userInfoService.exportUserInfo(params);
		ExcelUtil.export(response, "社区警务-派出所信息数据" + DateUtil.time(), "社区警务-派出所信息数据表", list, UserInfoExcel.class);
	}

	/**
	 * 获取字典
	 */
	@GetMapping("/dictionary")
	@Cacheable(cacheNames = "blade:getUserglZd")
	public R dictionary() {
		UserZdVO data = new UserZdVO();

		String code = "";

		code = "mz"; // 民族
		List<ZdVO> mz = pcsInfoService.getDictList(code);
		data.setMz(mz);

		code = "whcd"; // 文化程度(学历)
		List<ZdVO> whcd = pcsInfoService.getDictList(code);
		data.setWhcd(whcd);

		code = "hyzk"; // 婚姻状况
		List<ZdVO> hyzk = pcsInfoService.getDictList(code);
		data.setHyzk(hyzk);

		code = "zzmm"; // 政治面貌
		List<ZdVO> zzmm = pcsInfoService.getDictList(code);
		data.setZzmm(zzmm);

		code = "zwlb"; // 职务类别
		List<ZdVO> zwlb = pcsInfoService.getDictList(code);
		data.setZwlb(zwlb);

		code = "gwzz"; // 岗位职责
		List<ZdVO> gwzz = pcsInfoService.getDictList(code);
		data.setGwzz(gwzz);

		code = "zj"; // 职级
		List<ZdVO> zj = pcsInfoService.getDictList(code);
		data.setZj(zj);

		code = "jbzzw"; // 进班子职务
		List<ZdVO> jbzzw = pcsInfoService.getDictList(code);
		data.setJbzzw(jbzzw);

		code = "jlwzw"; // 进班子职务
		List<ZdVO> jlwzw = pcsInfoService.getDictList(code);
		data.setJlwzw(jlwzw);

		return R.data(data);
	}

	/**
	 * 查询当前注销人员的所有办理的业务数据展示
	 * userId
	 */
	@GetMapping("/getHistoryData")
	public R getHistoryData(@RequestParam Map<String, String> params) {
		List<HistoryDataDTO> data = new ArrayList<>();
		int jwsSl = jwsService.getJwsSl(Long.valueOf(params.get("userId")));
		data.add(new HistoryDataDTO("警务室(站)数量", jwsSl));
		int jxcsSl = csInfoService.getJxcsSl(Long.valueOf(params.get("userId")));
		data.add(new HistoryDataDTO("九小场所数量", jxcsSl));
		int mdjfSl = mdjfdjService.getMdjfSl(Long.valueOf(params.get("userId")));
		data.add(new HistoryDataDTO("矛盾纠纷数量", mdjfSl));
		int fwSl = fwInfoService.getFwSl(Long.valueOf(params.get("userId")));
		data.add(new HistoryDataDTO("入户走访房屋数量", fwSl));
		return R.data(data);
	}

	/**
	 * 工作移交
	 * oldUserId newUserId zxyy ywlb
	 */
	@Transactional
	@PostMapping("/gzyj")
	public R gzyj(@RequestParam Map<String, String> params) {
		User oldUser = userService.getById(Long.valueOf(params.get("oldUserId")));
		User newUser = userService.getById(Long.valueOf(params.get("newUserId")));
		String[] oldDeptIds = oldUser.getDeptId().split(",");
		String newDeptId = newUser.getDeptId();
		for (String deptId : oldDeptIds) {
			if (!newUser.getDeptId().contains(deptId)) {
				newDeptId = newDeptId + "," + deptId;
			}
		}
		// 更改旧user的 is_deleted=2
		if (params.get("type").equals("2")) {
			oldUser.setZxyy(params.get("zxyy"));
			userService.zx(oldUser);
		}
		// 更改新 blade_user 的 deptId
		userService.updateDeptId(Long.valueOf(params.get("newUserId")), newDeptId);
		// 更改 blade_user_info 的 sszrq
		userInfoService.updateSszrqByUserId(Long.valueOf(params.get("newUserId")), newDeptId);
		// 更改各业务的create_user
		if (null != params.get("ywlb")) {
			if (params.get("ywlb").equals("all") || params.get("ywlb").equals("jws")) {
				jwsService.update(new UpdateWrapper<JlrhJwsEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId")))
				);
			}
			if (params.get("ywlb").equals("all") || params.get("ywlb").equals("xfjc")) {
				csInfoService.update(new UpdateWrapper<CsInfoEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId")))
				);
				jcInfoService.update(new UpdateWrapper<CsjcInfoEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
			}
			if (params.get("ywlb").equals("all") || params.get("ywlb").equals("mdjf")) {
				mdjfdjService.update(new UpdateWrapper<MdjfDjEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				mdjfryService.update(new UpdateWrapper<MdjfRyEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				mdjftjService.update(new UpdateWrapper<MdjfTjEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				hfService.update(new UpdateWrapper<HfEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
			}
			if (params.get("ywlb").equals("all") || params.get("ywlb").equals("rhzf")) {
				fwInfoService.update(new UpdateWrapper<FwInfoEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				fwFzService.update(new UpdateWrapper<FwFzEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				fwRyService.update(new UpdateWrapper<FwRyEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				czrkService.update(new UpdateWrapper<RyCzrkEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				jzrkService.update(new UpdateWrapper<RyJzrkEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				zzrkService.update(new UpdateWrapper<RyZzrkEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				wlrkService.update(new UpdateWrapper<RyWlrkEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
				jwrkService.update(new UpdateWrapper<RyJwrkEntity>()
					.eq("create_user", Long.valueOf(params.get("oldUserId")))
					.set("create_user", Long.valueOf(params.get("newUserId"))));
			}
		}
		// 保存日志
		ZxLogEntity zxLogEntity = new ZxLogEntity();
		zxLogEntity.setType(Integer.parseInt(params.get("type")));
		zxLogEntity.setYwlb(params.get("ywlb"));
		zxLogEntity.setSm(params.get("sm"));
		zxLogEntity.setOldUserId(Long.valueOf(params.get("oldUserId")));
		zxLogEntity.setNewUserId(Long.valueOf(params.get("newUserId")));
		zxLogService.save(zxLogEntity);
		return R.status(true);
	}

	/**
	 * 根据身份证号查询人员信息
	 * sfzh
	 */
	@GetMapping("/getRyxxBySfzh")
	public R getRyxxBySfzh(@RequestParam Map<String, String> params) {
		RkxxVO rkxxVO = fwInfoService.getRyxxBySfzh(params);
		return R.data(rkxxVO);
	}

	/**
	 * 民警绑定辅警
	 * params fjZh
	 */
	/*@PostMapping("/mfjgl")
	public R mfjgl(@RequestParam Map<String, Object> params) {
		Long userId = AuthUtil.getUserId();
		if (null == userId) {
			return R.fail("登录失效，请重新登录");
		}
		params.put("userId", AuthUtil.getUserId());
		// 获取规定的辅警数量
		int total = dictService.getFjsl();
		// 获取当前警号已绑定的辅警数量
		int fjsl = userService.getFjsl(params);
		if (fjsl >= total) {
			return R.fail("该民警已绑定的辅警账号 超出上限");
		}
		return R.status(userInfoService.mfjgl(params));
	}*/
}
