package com.fs.app.controller;



import com.fs.app.annotation.Login;

import com.fs.app.param.LoginParam;
import com.fs.app.param.UpdateUserInfoParam;
import com.fs.app.vo.UserListVO;
import com.fs.app.vo.UserVO;

import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.SmsResponse;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.PinYinUtil;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.SmsVerifyCodeUtils;
import com.fs.common.utils.StringUtils;

import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyPost;
import com.fs.company.domain.CompanyProduct;
import com.fs.company.domain.CompanyUserPost;
import com.fs.company.param.SmsLoginParam;
import com.fs.company.service.ICompanyPostService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.service.ICompanyDeptService;
import com.fs.company.service.ICompanyProductService;
import com.fs.company.mapper.CompanyUserPostMapper;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value="/app/user")
public class UserController extends AppBaseController {
	@Autowired
	ICompanyPostService postService;

	@Autowired
	ICompanyUserService companyUserService;

	@Autowired
	ICompanyDeptService companyDeptService;

	@Autowired
	ICompanyProductService companyProductService;

	@Autowired
	CompanyUserPostMapper companyUserPostMapper;

	@Autowired
	private SmsVerifyCodeUtils smsVerifyCodeUtils;

	@Autowired
	RedisCache redisCache;
	@PostMapping("/login")
	public R login(@RequestBody LoginParam param)
	{
		CompanyUser user=companyUserService.selectUserByUserName(param.getAccount());
		if(user==null){
			return R.error("帐号不存在");
		}
		if(!user.getStatus().equals("0")){
			return R.error("帐号已被禁用");
		}
		if(!SecurityUtils.matchesPassword(param.getPassword(),user.getPassword())){
			return R.error("密码不正确");
		}
		String token = jwtUtils.generateToken(user.getUserId());
//		redisCache.setCacheObject("doctorToken:"+user.getUserId(),token,604800, TimeUnit.SECONDS);
		redisCache.setCacheObject("CompanyUserToken:"+user.getUserId(),token,604800, TimeUnit.SECONDS);

		Map<String,Object> map=new HashMap<>();
		map.put("token",token);
		map.put("user",user);

		return R.ok().put("data",map);
	}

	/**
	 * 短信验证码登录
	 *
	 * @param param 短信登录参数
	 * @return 登录结果
	 */
	@PostMapping("/smsLogin")
	public R smsLogin(@RequestBody @Validated SmsLoginParam param) {

		String redisKey = "sms:login:" + param.getPhone();
		String cacheCode = redisCache.getCacheObject(redisKey);

		if (cacheCode == null) {
			return R.error("验证码已过期，请重新获取");
		}

		if (!cacheCode.equals(param.getCode())) {
			return R.error("验证码不正确");
		}

		CompanyUser user = companyUserService.selectUserByPhone(param.getPhone());

		if (user == null) {
			return R.error("用户不存在");
		}

		if (!"0".equals(user.getStatus())) {
			return R.error("帐号已被禁用");
		}

		String token = jwtUtils.generateToken(user.getUserId());

		redisCache.setCacheObject("CompanyUserToken:" + user.getUserId(), token, 604800, TimeUnit.SECONDS);

		redisCache.deleteObject(redisKey);

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("user", user);

		return R.ok().put("data", map);
	}
	/**
	 * 发送短信登录验证码
	 *
	 * @param phone 手机号
	 * @return 发送结果
	 */
	@PostMapping("/sendSmsCode")
	public R sendSmsCode(@RequestParam("phone") String phone,
						 @RequestParam(name = "type", required = false,defaultValue = "0") String type) {

		if (phone == null || !phone.matches("^1[3-9]\\d{9}$")) {
			return R.error("手机号格式不正确");
		}

		CompanyUser user = companyUserService.selectUserByPhone(phone);
		if (user == null) {
			return R.error("该手机号未注册");
		}

		String redisKey = "";
		if("0".equals(type)){
			redisKey = "sms:login:" + phone;
		} else if("1".equals(type)){
			redisKey = "sms:reset_pwd:" + phone;
		}

		String existCode = redisCache.getCacheObject(redisKey);
		if (existCode != null) {
			Long expireTime = redisCache.getExpire(redisKey);
			if (expireTime != null && expireTime > 240) {
				return R.error("验证码已发送，请稍后再试");
			}
		}

		SmsResponse response = smsVerifyCodeUtils.sendVerifyCode(phone);
		if(!response.isSuccess()){
			return R.error("验证码发送失败！");
		}

		redisCache.setCacheObject(redisKey, response.getCode(), 300, TimeUnit.SECONDS);


		return R.ok("验证码发送成功");
	}

	/**
	 * 忘记密码 - 通过验证码重置密码
	 *
	 * @param param 包含手机号、验证码、新密码、确认密码
	 * @return 重置结果
	 */
	@ApiOperation("忘记密码")
	@PostMapping("/forgetPassword")
	public R forgetPassword(@RequestBody Map<String, String> param) {
		try {
			String phone = param.get("phone");
			String code = param.get("code");
			String newPassword = param.get("newPassword");
			String confirmPassword = param.get("confirmPassword");

			// 参数校验
			if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)
					|| StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(confirmPassword)) {
				return R.error("手机号、验证码、新密码和确认密码均不能为空");
			}

			// 手机号格式校验
			if (!phone.matches("^1[3-9]\\d{9}$")) {
				return R.error("手机号格式不正确");
			}

			// 密码一致性校验
			if (!newPassword.equals(confirmPassword)) {
				return R.error("两次输入的密码不一致");
			}

			// 密码规则校验（8-20位字母数字）
			if (!newPassword.matches("^[a-zA-Z0-9]{8,20}$")) {
				return R.error("新密码必须为8-20位字母和数字组合");
			}

			// 验证码校验
			String redisKey = "sms:reset_pwd:" + phone;
			String cacheCode = redisCache.getCacheObject(redisKey);

			if (cacheCode == null) {
				return R.error("验证码已过期，请重新获取");
			}

			if (!cacheCode.equals(code)) {
				return R.error("验证码不正确");
			}

			// 查询用户
			CompanyUser user = companyUserService.selectUserByPhone(phone);
			if (user == null) {
				return R.error("该手机号未注册");
			}

			if ("1".equals(user.getStatus())) {
				return R.error("用户已停用，无法修改密码");
			}

			// 加密新密码并更新
			String encryptedPassword = SecurityUtils.encryptPassword(newPassword);
			user.setPassword(encryptedPassword);
			companyUserService.updateCompanyUser(user);

			// 删除验证码
			redisCache.deleteObject(redisKey);

			return R.ok("密码重置成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("密码重置失败");
		}
	}



	@ApiOperation("已登录用户修改密码（含校验原密码）")
	@Login
	@PostMapping("/changePwd")
	public R changePassword(@RequestBody Map<String, String> param) {
		try {
			String oldPassword = param.get("oldPassword");
			String newPassword = param.get("newPassword");
			String confirmPassword = param.get("confirmPassword");

			if (StringUtils.isEmpty(oldPassword)
					|| StringUtils.isEmpty(newPassword)
					|| StringUtils.isEmpty(confirmPassword)) {
				return R.error("原密码、新密码和确认密码均不能为空");
			}

			if (!newPassword.equals(confirmPassword)) {
				return R.error("新密码和确认密码不一致");
			}

			// 密码规则校验（8-20位字母数字）
			if (!newPassword.matches("^[a-zA-Z0-9]{8,20}$")) {
				return R.error("新密码必须为8-20位字母和数字组合");
			}

			Long userId = Long.parseLong(getUserId());
			CompanyUser user = companyUserService.selectCompanyUserById(userId);
			if (user == null) {
				return R.error("用户不存在");
			}
			if ("1".equals(user.getStatus())) {
				return R.error("用户已停用，无法修改密码");
			}

			// 校验旧密码是否正确（假设用SecurityUtils进行加密和验证）
			if (!SecurityUtils.matchesPassword(oldPassword, user.getPassword())) {
				return R.error("原密码错误");
			}

			// 加密新密码，更新数据库
			String encryptedNewPassword = SecurityUtils.encryptPassword(newPassword);
			user.setPassword(encryptedNewPassword);
			companyUserService.updateCompanyUser(user);

			return R.ok("密码修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("密码修改失败");
		}
	}

 	@Login
	@GetMapping("getCompanyUser")
	public R getCompanyUser()
	{
		CompanyUser user = companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
		return R.ok().put("data",user);
	}

	@ApiOperation("检测是否登录")
	@GetMapping("/checkLogin")
	public R checkLogin(HttpServletRequest request){
		if(StringUtils.isEmpty(getUserId())){
			//未登录
			return R.error("未登录");
		}
		else{
			//登录
			String token = jwtUtils.generateToken(Long.parseLong(getUserId()));
			Map<String,Object> map=new HashMap<>();
			map.put("token",token);
			return R.ok("认证成功").put("userId",getUserId()).put("token",token);
		}
	}



	/**
	 * 获取用户信息
	 * @param request
	 * @return
	 */
	@Login
	@ApiOperation("获取用户信息")
	@GetMapping("/getUserInfo")
	public R getUserInfo(HttpServletRequest request){
		try {
			CompanyUser companyUser=companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
			List<String> postList=postService.selectPostNameListByUserId(Long.parseLong(getUserId()));
			if(companyUser==null){
				return R.error(40001,"用户不存在");
			}
			if(companyUser.getStatus().equals("1")){
				return R.error(40002,"用户已停用");
			}

			// 查询岗位ID列表
			List<Integer> postIdList = postService.selectPostListByUserId(Long.parseLong(getUserId()));
			if (postIdList != null && !postIdList.isEmpty()) {
				Long[] postIds = postIdList.stream()
						.map(Integer::longValue)
						.toArray(Long[]::new);
				companyUser.setPostIds(postIds);
			}

			// 性别文本
			if (StringUtils.isNotEmpty(companyUser.getSex())) {
				String sexStr = "";
				switch (companyUser.getSex()) {
					case "0":
						sexStr = "男";
						break;
					case "1":
						sexStr = "女";
						break;
					case "2":
						sexStr = "未知";
						break;
				}
				companyUser.setSexStr(sexStr);
			}

			// 部门名称
			if (companyUser.getDeptId() != null && StringUtils.isEmpty(companyUser.getDeptName())) {
				CompanyDept dept = companyDeptService.selectCompanyDeptById(companyUser.getDeptId());
				if (dept != null) {
					companyUser.setDeptName(dept.getDeptName());
				}
			}

			// 直属上级姓名
			if (companyUser.getSupervisorId() != null) {
				CompanyUser supervisor = companyUserService.selectCompanyUserById(companyUser.getSupervisorId());
				if (supervisor != null) {
					companyUser.setSupervisorName(supervisor.getNickName());
				}
			}

			// 解析产品列表
			if (StringUtils.isNotEmpty(companyUser.getProductCode())) {
				String[] productCodes = companyUser.getProductCode().split(",");
				List<Map<String, String>> productList = new ArrayList<>();

				// 查询所有产品
				List<CompanyProduct> allProducts = companyProductService.queryAllProduct(companyUser.getCompanyId());
				Map<String, String> productMap = new HashMap<>();
				for (CompanyProduct product : allProducts) {
					productMap.put(product.getProductCode(), product.getProductName());
				}

				// 构建产品列表
				for (String code : productCodes) {
					String trimmedCode = code.trim();
					if (StringUtils.isNotEmpty(trimmedCode)) {
						Map<String, String> product = new HashMap<>();
						product.put("code", trimmedCode);
						product.put("name", productMap.getOrDefault(trimmedCode, trimmedCode));
						productList.add(product);
					}
				}
				companyUser.setProductList(productList);
			}

			return R.ok().put("user",companyUser).put("post",postList);
		} catch (Exception e){
			e.printStackTrace();
			return R.error("操作异常");
		}
	}
	@Login
	@ApiOperation("获取用户信息ByUserId")
	@GetMapping("/getUserInfoByUserId")
	public R getUserInfoByUserId(
			@ApiParam(required = true, name = "userId", value = "用户ID") @RequestParam(value = "userId", required = false) Long userId,
			HttpServletRequest request){
		try {
			CompanyUser user=companyUserService.selectCompanyUserById(userId);
			List<String> postList=postService.selectPostNameListByUserId(userId);
			if(user==null){
				return R.error(40001,"用户不存在");
			}
			if(user.getStatus().equals("1")){
				return R.error(40002,"用户已停用");
			}
			return R.ok().put("user",user).put("post",postList);
		} catch (Exception e){

			return R.error("操作异常");
		}
	}

	/**
	 * 更新业务员个人信息
	 *
	 * @param param 更新个人信息参数
	 * @return 更新结果
	 */
	@Login
	@ApiOperation("更新业务员个人信息")
	@PostMapping("/updateUserInfo")
	public R updateUserInfo(@RequestBody @Validated UpdateUserInfoParam param) {
		try {
			Long userId = Long.parseLong(getUserId());
			CompanyUser user = companyUserService.selectCompanyUserById(userId);

			if (user == null) {
				return R.error("用户不存在");
			}

			if ("1".equals(user.getStatus())) {
				return R.error("用户已停用，无法修改信息");
			}

			// 更新头像
			if (StringUtils.isNotEmpty(param.getAvatar())) {
				user.setAvatar(param.getAvatar());
			}

			// 更新姓名
			if (StringUtils.isNotEmpty(param.getNickName())) {
				user.setNickName(param.getNickName().trim());
			}

			// 更新性别
			if (StringUtils.isNotEmpty(param.getSex())) {
				user.setSex(param.getSex());
			}

			// 更新部门
			if (param.getDeptId() != null) {
				user.setDeptId(param.getDeptId());
			}

			// 更新产品
			if (StringUtils.isNotEmpty(param.getProductCode())) {
				user.setProductCode(param.getProductCode());
			}

			// 更新岗位关联
			if (param.getPostIds() != null && param.getPostIds().length > 0) {
				// 删除用户旧的岗位关联
				companyUserPostMapper.deleteUserPostByUserId(userId);

				// 新增用户岗位关联
				List<CompanyUserPost> postList = new ArrayList<>();
				for (Long postId : param.getPostIds()) {
					CompanyUserPost userPost = new CompanyUserPost();
					userPost.setUserId(userId);
					userPost.setPostId(postId);
					postList.add(userPost);
				}
				if (!postList.isEmpty()) {
					companyUserPostMapper.batchUserPost(postList);
				}
			}

			 if (param.getSupervisorId() != null) {
			     user.setSupervisorId(param.getSupervisorId());
			 }
			 if (StringUtils.isNotEmpty(param.getCertificationMaterials())) {
			     user.setCertificationMaterials(param.getCertificationMaterials());
			 }

			// 执行更新
			int result = companyUserService.updateCompanyUser(user);

			if (result > 0) {
				return R.ok("个人信息更新成功").put("data", user);
			} else {
				return R.error("个人信息更新失败");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return R.error("个人信息更新失败");
		}
	}

	/**
	 * 获取当前公司所有部门列表
	 *
	 * @return 部门列表
	 */
	@Login
	@ApiOperation("获取当前公司所有部门列表")
	@GetMapping("/getDeptList")
	public R getDeptList() {
		try {
			Long userId = Long.parseLong(getUserId());
			CompanyUser user = companyUserService.selectCompanyUserById(userId);

			if (user == null) {
				return R.error("用户不存在");
			}

			if (user.getCompanyId() == null) {
				return R.error("用户未关联公司");
			}

			// 查询当前公司的所有部门
			CompanyDept query = new CompanyDept();
			query.setCompanyId(user.getCompanyId());
			query.setStatus("0"); // 只查询正常状态的部门

			List<CompanyDept> deptList = companyDeptService.selectCompanyDeptList(query);

			return R.ok().put("data", deptList);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("获取部门列表失败");
		}
	}

	/**
	 * 获取当前公司所有岗位列表
	 *
	 * @return 岗位列表
	 */
	@Login
	@ApiOperation("获取当前公司所有岗位列表")
	@GetMapping("/getPostList")
	public R getPostList() {
		try {
			Long userId = Long.parseLong(getUserId());
			CompanyUser user = companyUserService.selectCompanyUserById(userId);

			if (user == null) {
				return R.error("用户不存在");
			}

			if (user.getCompanyId() == null) {
				return R.error("用户未关联公司");
			}

			// 查询当前公司的所有岗位
			CompanyPost query = new CompanyPost();
			query.setCompanyId(user.getCompanyId());
			query.setStatus("0"); // 只查询正常状态的岗位

			List<CompanyPost> postList = postService.selectCompanyPostList(query);

			return R.ok().put("data", postList);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("获取岗位列表失败");
		}
	}

	/**
	 * 获取当前公司所有产品列表
	 *
	 * @return 产品列表
	 */
	@Login
	@ApiOperation("获取当前公司所有产品列表")
	@GetMapping("/getProductList")
	public R getProductList() {
		try {
			Long userId = Long.parseLong(getUserId());
			CompanyUser user = companyUserService.selectCompanyUserById(userId);

			if (user == null) {
				return R.error("用户不存在");
			}

			if (user.getCompanyId() == null) {
				return R.error("用户未关联公司");
			}

			// 查询当前公司的所有产品
			List<CompanyProduct> productList = companyProductService.queryAllProduct(user.getCompanyId());

			return R.ok().put("data", productList);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("获取产品列表失败");
		}
	}

	/**
	 * 获取当前公司所有业务员列表
	 *
	 * @return 业务员列表
	 */
	@Login
	@ApiOperation("获取当前公司所有业务员列表")
	@GetMapping("/getCompanyUserList")
	public R getCompanyUserList() {
		try {
			Long userId = Long.parseLong(getUserId());
			CompanyUser currentUser = companyUserService.selectCompanyUserById(userId);

			if (currentUser == null) {
				return R.error("用户不存在");
			}

			if (currentUser.getCompanyId() == null) {
				return R.error("用户未关联公司");
			}

			// 查询当前公司的所有业务员
			CompanyUser query = new CompanyUser();
			query.setCompanyId(currentUser.getCompanyId());
			query.setStatus("0"); // 只查询正常状态的用户

			List<CompanyUser> userList = companyUserService.selectCompanyUserList(query);

			return R.ok().put("data", userList);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("获取业务员列表失败");
		}
	}


}
