package com.rf.psychological.api;

import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.api.key.dao.model.KeyEntity;
import com.rf.psychological.api.key.service.KeyService;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.enums.UserRole;
import com.rf.psychological.enums.UserStatus;
import com.rf.psychological.group.dao.model.GroupEntity;
import com.rf.psychological.group.service.GroupInfoService;
import com.rf.psychological.institution.model.InstitutionEntity;
import com.rf.psychological.institution.service.InstitutionService;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.RSAUtils;
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.Constant;
import com.rf.psychological.utils.JWTUtil;
import com.rf.psychological.utils.Result;
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.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Administrator
 */
@Slf4j
@RestController
@RequestMapping("/v1")
@Api(tags = "外部系统认证操作")
public class UserApi extends BaseController {

    @Autowired
    private InstitutionService institutionService;

    @Autowired
    private KeyService keyService;

    @Autowired
    private UserService userService;

    @Autowired
    private GroupInfoService groupInfoService;

    @ApiOperation(value = "外部系统获取token接口",notes = "data参数包括：userName:账号, password:密码,institutionNo:机构编号")
    @PostMapping("/getToken")
    public Result getToken(@RequestBody String params){
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            JSONObject jsonObject =JSONObject.parseObject( jsonParams);
            log.info("getToken===="+jsonParams);
            if (!jsonObject.containsKey("institutionNo") ||  StringUtils.isEmpty(jsonObject.getString("institutionNo")) ) {
                return fail("", "机构编号不能为空");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            if (!jsonObject.containsKey("userName") || StringUtils.isEmpty(jsonObject.getString("userName")) ) {
                return fail("", "账号不能为空");
            }
            String phone = jsonObject.getString("userName");
            log.info("phone: " + phone);
            //判断机构编号是否存在
            InstitutionEntity institutionEntity = this.institutionService.findByInstitutionNo(institutionNo);
            log.info("institutionEntity: " + institutionEntity);
            if (institutionEntity == null) {
                return fail("", "机构编号不存在！");
            }
            UserEntity userEntity = this.userService.findPhoneAndInstitutionNoAndRoleType(phone, institutionNo, Constant.DEFAULT_VALUE_ONE );
            log.info("userEntity: " + userEntity);
            if (!jsonObject.containsKey("password") || StringUtils.isEmpty(  jsonObject.getString("password") )) {
                return fail("", "密码不能为空");
            }
            String password = jsonObject.getString("password");
            if (userEntity == null) {

                return fail(null, "机构编号或账号错误");
            }
            if (userEntity.getPassword().equals(password)) {
                //生成token
                userEntity.setPassword(null);
                String token = JWTUtil.generateToken(userEntity);
                // 创建返回的json对象
                JSONObject resultJson = new JSONObject();
                resultJson.put("token", token);
                //获取该机构编号下公钥
                KeyEntity keyEntity = keyService.find(institutionNo);
                if (keyEntity == null){
                    return fail(null,"未获取到该机构下秘钥信息");
                }
                if(StringUtils.isEmpty(keyEntity.getPubKey())){
                    return fail(null,"未获取到该机构下秘钥信息");
                }
                String encryptStr = RSAUtils.encryptByPublicKey3(resultJson.toJSONString(),keyEntity.getPubKey());
                 return success(encryptStr);
            } else {
                return fail(null, "账号或密码错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    /**
     * 注册用户
     * @param params
     * @return
     */
    @PostMapping("/registerUser")
    @ApiOperation(value = "外部系统普通用户注册接口",notes = "json字符串形式传参（加密）,data参数包括:birthday：生日，gender:性别，password:密码，phone:账号或电话，petName:姓名")
    public Result registerUser(@RequestBody String params){
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            JSONObject jsonObject =JSONObject.parseObject(jsonParams);
            log.info("registerUser===="+jsonParams);
            if (!jsonObject.containsKey("phone") ||  StringUtils.isEmpty(jsonObject.getString("phone")) ) {
                return fail("", "账号不能为空");
            }
            String phone = jsonObject.getString("phone");
            log.info("phone: " + phone);
            if (!jsonObject.containsKey("petName") || StringUtils.isEmpty(jsonObject.getString("petName")) ) {
                return fail("", "姓名不能为空");
            }
            String petName = jsonObject.getString("petName");
            log.info("petName: " + petName);
            if (!jsonObject.containsKey("birthday") ||  StringUtils.isEmpty(jsonObject.getString("birthday")) ) {
                return fail("", "出生日期不能为空");
            }
            String birthday = jsonObject.getString("birthday");
            log.info("birthday: " + birthday);
            if (!jsonObject.containsKey("gender") || StringUtils.isEmpty(jsonObject.getString("gender")) ) {
                return fail("", "性别不能为空");
            }
            String gender = jsonObject.getString("gender");
            log.info("gender: " + gender);
            if (!jsonObject.containsKey("password") || StringUtils.isEmpty(jsonObject.getString("password")) ) {
                return fail("", "密码不能为空");
            }
            String password = jsonObject.getString("password");
            log.info("password: " + password);

            UserEntity userEntity = jsonObject.toJavaObject(UserEntity.class);
            userEntity.setModelPhone(Constant.DEFAULT_VALUE_ZERO);
            userEntity.setInstitutionNo(Constant.LAN_INSTITUTION_CODE);
            userEntity.setInstitutionName(Constant.LAN_INSTITUTION_NAME);
            userEntity.setRoleType(UserRole.COMMON.getType());
            userEntity.setUserStatus(UserStatus.PASS.getType());
            GroupEntity entity =this.groupInfoService.findGroupByInstitutionNoAndName(Constant.LAN_INSTITUTION_CODE,Constant.DEFAULT_GROUP_NAME);
            if (entity == null ){
                return fail("", "机构下无默认分组！");
            }
            userEntity.setGId(entity.getId());
            UserEntity userInfo = this.userService.findPhoneAndInstitutionNoAndRoleType(userEntity.getPhone(), userEntity.getInstitutionNo(),userEntity.getRoleType());
            if (userInfo == null) {
                this.userService.save(userEntity);
                return success();
            } else {
                return fail("", "账号已注册");
            }
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    /**
     * 删除用户
     * @param params
     * @return
     */
    @PostMapping("/deleteUser")
    @ApiOperation(value = "外部系统普通用户删除接口",notes = "json字符串形式传参（加密）,data参数包括:phone:账号或电话,institutionNo:机构编号")
    public Result deleteUser(@RequestBody String params){
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            JSONObject jsonObject =JSONObject.parseObject( jsonParams);
            log.info("deleteUser===="+jsonParams);
            if (!jsonObject.containsKey("phone") ||  StringUtils.isEmpty(jsonObject.getString("phone")) ) {
                return fail("", "账号不能为空");
            }
            String phone = jsonObject.getString("phone");
            log.info("phone: " + phone);
            if (!jsonObject.containsKey("institutionNo") || StringUtils.isEmpty(jsonObject.getString("institutionNo")) ) {
                return fail("", "机构编号");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            log.info("institutionNo: " + institutionNo);
            UserEntity user = this.userService.findPhoneAndInstitutionNoAndRoleType(phone,institutionNo,Constant.DEFAULT_VALUE_ONE);
            if (user != null) {
                this.userService.delete(user);
                return success();
            } else {
                return fail("", "账号不存在");
            }
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

}
