package com.rf.psychological.user.rest;

import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.group.dao.dto.GroupAuthSubjectNameDto;
import com.rf.psychological.enums.UserStatus;
import com.rf.psychological.group.rest.GroupInfoController;
import com.rf.psychological.group.dao.model.GroupAuthEntity;
import com.rf.psychological.group.dao.model.GroupEntity;
import com.rf.psychological.group.service.GroupAuthService;
import com.rf.psychological.group.service.GroupInfoService;
import com.rf.psychological.institution.model.InstitutionAuthEntity;
import com.rf.psychological.institution.model.InstitutionEntity;
import com.rf.psychological.institution.service.InstitutionAuthService;
import com.rf.psychological.institution.service.InstitutionService;
import com.rf.psychological.opLog.annotation.OperationLogAnnotation;
import com.rf.psychological.plan.service.PlanGroupService;
import com.rf.psychological.plan.service.TestPlanUserService;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author zsy
 * @description:登录认证
 * @date 2021/6/17 15:55
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户操作")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private GroupInfoService groupInfoService;
    @Autowired
    private PlanGroupService planGroupService;
    @Autowired
    private TestPlanUserService planUserService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @SafetyProcess
    @GetMapping("/authCode")
    @ApiOperation(value = "向手机发送验证码")
    public Result authCode(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return failBadRequest();
        } else {
            SendMessageUtil sendMessageUtil = new SendMessageUtil();
            String authCode = sendMessageUtil.sendMessage(phone);
            String beginTime = DateUtil.getNowTime(DateUtil.DEFAULT_FILE_DATE);
            // 创建返回的json对象
            JSONObject resultJson = new JSONObject(true);
            resultJson.put("beginTime", beginTime);
            resultJson.put("authCode", authCode);
            resultJson.put("phone", phone);
            String redisKey = "AUTH_CODE_"+phone;
            redisTemplate.opsForValue().set(redisKey,authCode,5, TimeUnit.MINUTES);
            return success(resultJson);
        }
    }


    /**
     * 重置密码
     * @return
     */
    @SafetyProcess
    @PostMapping("/resetPassword/{userId}")
    @OperationLogAnnotation
    @ApiOperation("用户重置密码")
    public Result resetPassword( @PathVariable String userId) throws Exception {

        if (StringUtils.isEmpty(userId) ) {
            return fail("", "用户id不能为空");
        }
        UserEntity userEntity = this.userService.findOne(userId);
        if (userEntity == null) {
            return fail("", "请先注册");
        } else {
            //this.userService.updatePassword(phone, DigestUtils.md5DigestAsHex(Constant.DEFAULT_PASSWORD.getBytes(StandardCharsets.UTF_8)), institutionNo);
            userEntity.setPassword(DigestUtils.md5DigestAsHex(Constant.DEFAULT_PASSWORD.getBytes(StandardCharsets.UTF_8)));
            //userEntity.setUserStatus(UserStatus.UPDATE.getType());
            userService.save(userEntity);

            return success();
        }
    }

    /**
     * 获取机构下的用户列表
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("/getUserListByInstitutionNo")
    @ApiOperation(value = "获取机构下的用户列表")
    public Result getSubjectListByName(int pageNum, int pageSize, String institutionNo, String searchKey, String status, String groupId) {
        if (pageSize == 0) {
            pageSize = 20;
        }
        int num;
//添加分组过滤
        List<UserEntity> userList = this.userService.getUserListByInstitutionNo(pageNum, pageSize, searchKey, institutionNo, status, groupId);
        num = this.userService.allNum(searchKey, institutionNo, status, groupId);
        System.out.println("subjectEntityList:" + userList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", userList);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }

    /**
     * 修改用户状态
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("/updateStatus")
    @OperationLogAnnotation
    @ApiOperation(value = "修改用户状态")
    public Result updateStatus(String bid, String status) {
        UserEntity user = this.userService.getOne(bid);
        //审核 通过
        if(status.equals(Constant.USER_STATUS_NORMAL)){
            //查看用户分组是否有测试计划
            String groupId = user.getGId();
            createPlanUserInfo(groupId,bid);
        }
        user.setUserStatus(status);
        this.userService.save(user);
        return success();
    }

    @SafetyProcess
    @GetMapping("/updateMobile")
    @OperationLogAnnotation
    @ApiOperation(value = "修改手机号")
    public Result updateMobile(String id, String mobile, String authCode) {
        try {
            String redisKey = "AUTH_CODE_"+mobile;
            String code = redisTemplate.opsForValue().get(redisKey);
            if (StringUtils.isEmpty(authCode) || !
                    authCode.equals(code)){
                return fail("验证码已失效");
            }
            UserEntity user = this.userService.getOne(id);
            user.setModelPhone(mobile);
            this.userService.save(user);
            return success();
        }catch (Exception e){
            log.error(e.getMessage());
            return fail();
        }

    }


    /**
     * 一键审核
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("/updateStatusAll")
    @OperationLogAnnotation
    @ApiOperation(value = "一键审核")
    public Result updateStatusAll(String institutionNo) {
        List<UserEntity> userEntityList = this.userService.findByStatus(institutionNo,Constant.USER_STATUS_UNAUDITED);
        if (userEntityList.size() == 0){
            return success();
        }
        for(int i = 0; i < userEntityList.size(); i++) {
            //查看用户分组是否有测试计划
            String groupId = userEntityList.get(i).getGId();
            createPlanUserInfo(groupId,userEntityList.get(i).getId());
            userEntityList.get(i).setUserStatus(Constant.USER_STATUS_NORMAL);
            this.userService.save(userEntityList.get(i));
        }
        return success();
    }
    private void createPlanUserInfo( String groupId, String userId) {
        GroupInfoController.createPlanUserInfo(groupId, userId, this.planGroupService, this.planUserService);
    }
    /**
     * 根据账号获取用户信息
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("/getUser")
    @ApiOperation(value = "根据账号获取用户信息")
    public Result getUserByPhone(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return fail("", "账号不能为空");
        }
        UserEntity user = userService.findPhone(phone);
        return success(user);
    }

    @SafetyProcess
    @GetMapping("/institutionTest")
    @ApiOperation(value = "获取拥有测试记录机构下员工列表")
    public Result institutionTest(int pageNum, int pageSize, String institutionNo, String searchKey, String groupId) {
        if (pageSize == 0) {
            pageSize = 20;
        }
        int num;
        //添加分组过滤
        List<UserEntity> userRecordEntityList = this.userService.getTestListByInstitutionNo(pageNum, pageSize, institutionNo, searchKey, groupId);
        num = this.userService.allNumByInstitutionNo(institutionNo, searchKey, groupId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userRecordEntityList", userRecordEntityList);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }

    @SafetyProcess
    @PostMapping("/delete/{userId}")
    @OperationLogAnnotation
    @ApiOperation("删除用户")
    public Result deleteUser(@PathVariable String userId) throws Exception {
        UserEntity user = this.userService.findOne(userId);
        if (user != null) {
            this.userService.delete(user);
            return success();
        } else {
            return fail("", "该机构下的登录账号不存在");
        }
    }

    @SafetyProcess
    @GetMapping("/findAuth")
    @ApiOperation("查找用户拥有的数据的权限")
    public Result findSubAuth(@RequestParam("uId") String uId, int pageNum, int pageSize, String scaleName) throws Exception {
        if (StringUtils.isEmpty(uId)) {
            return fail("请输入用户id");
        }
        try {
            return success(this.userService.findUserAuth(uId, pageNum, pageSize, scaleName));
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("", "find error，" + exception.toString());
        }
    }

    @SafetyProcess
    @GetMapping("/findNoGroup")
    @ApiOperation("查找没有分组的用户")
    public Result findNoGroup(@RequestParam("institutionNo") String institutionNo,
                              @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize, @RequestParam("searchKey") String searchKey) throws Exception {
        if (StringUtils.isEmpty(institutionNo)) {
            return fail("机构编号为空");
        }

            GroupEntity groupEntity = this.groupInfoService.findGroupByInstitutionNoAndName(institutionNo, Constant.DEFAULT_GROUP_NAME);
            return success(this.userService.findUserNoGroup(pageNum, pageSize, institutionNo, groupEntity.getId(), searchKey));
    }

    /**
     * 校验用户是否已注册
     *
     * @param phone
     * @return
     */
    @GetMapping("{phone}/checkUser")
    public String checkUser(@PathVariable String phone) {
        UserEntity user = this.userService.findPhone(phone);
        JSONObject jsonObject = new JSONObject();
        if (user.getRoleType().equals("1")){
            jsonObject.put("userName",user.getPetName());
            //身份证号
            jsonObject.put("ID",user.getProfession());
        }else {
            jsonObject.put("userName","");
            //身份证号
            jsonObject.put("ID","");
        }
        return jsonObject.toJSONString();
    }

    @SafetyProcess
    @PostMapping("/update")
    @OperationLogAnnotation
    @ApiOperation("更新用户信息")
    public Result updateUser(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonData = JSONObject.parseObject(data);
        String phone = jsonData.getString("phone");
        String institutionNo = jsonData.getString("institutionNo");
        String petName = jsonData.getString("petName");
        String gender = jsonData.getString("gender");
        String birthday = jsonData.getString("birthday");
        String profession = jsonData.getString("profession");
        String newModelPhone = jsonData.getString("newModelPhone");
        String roleType = jsonData.getString("roleType");
        //UserEntity userEntity = userService.updateUserInfo(phone, institutionNo, newModelPhone, petName, gender, birthday, profession);
        UserEntity userEntity = userService.findPhoneAndInstitutionNoAndRoleType(phone,institutionNo,roleType);
        if (userEntity == null){
            return fail("用户不存在");
        }
        if (newModelPhone != null && !newModelPhone.equals("")){
            userEntity.setModelPhone(newModelPhone);
        }
        if (petName != null && !petName.equals("")){
            userEntity.setPetName(petName);
        }
        if (gender != null && !gender.equals("")){
            userEntity.setGender(gender);
        }
        if (birthday != null && !birthday.equals("")){
            userEntity.setBirthday(birthday);
        }
        if (profession != null && !profession.equals("")){
            userEntity.setProfession(profession);
        }
        if (userEntity.getUserStatus().equals("4")){
            userEntity.setUserStatus("2");
        }
        userEntity = userService.save(userEntity);
        if (userEntity != null) {
            return success(userEntity, "修改成功");
        } else {
            return fail("", "用户不存在");
        }
    }

    @SafetyProcess
    @GetMapping("/getModelPhone")
    @ApiOperation("获取手机号")
    public Result getModelPhone(String institutionNo, String phone,String roleType) throws Exception {

        if (StringUtils.isEmpty(institutionNo) || StringUtils.isEmpty(phone)|| StringUtils.isEmpty(phone)) {
            return fail("", "参数为空");
        }
        UserEntity userEntity = userService.findPhoneAndInstitutionNoAndRoleType(phone, institutionNo,roleType);
        if (userEntity != null) {
            return success(userEntity);
        } else {
            return fail("", "账号不存在");
        }
    }


    @SafetyProcess
    @GetMapping("/updateModelPhone/{userId}/{modelPhone}")
    @ApiOperation("绑定手机号")
    public Result updateModelPhone(@PathVariable String modelPhone, @PathVariable String userId){
        try {
            UserEntity userEntity = userService.findUserById(userId);
            userEntity.setModelPhone(modelPhone);
            userEntity = userService.save(userEntity);
            return success(userEntity,"操作成功");
        }catch (Exception e){
            e.printStackTrace();
            return fail(null,"操作失败");
        }
    }

}
