package com.loan.system.controller.wechat;

import com.loan.system.constant.JwtClaimsConstant;
import com.loan.system.domain.dto.UserLoginDTO;
import com.loan.system.domain.entity.Customer;
import com.loan.system.domain.entity.Role;
import com.loan.system.domain.entity.User;
import com.loan.system.domain.enums.ExceptionEnum;
import com.loan.system.domain.enums.RoleEnum;
import com.loan.system.domain.pojo.Result;
import com.loan.system.domain.vo.CustomerVO;
import com.loan.system.domain.vo.UserLoginVO;
import com.loan.system.exception.DescribeException;
import com.loan.system.properties.JwtProperties;
import com.loan.system.repository.RoleRepository;
import com.loan.system.service.CustomerService;
import com.loan.system.service.UserService;
import com.loan.system.utils.JwtUtil;
import com.loan.system.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Edwin
 * @date 2020/9/2 - 19:11
 */
@RestController
@RequestMapping("/wechat")
@Api(tags = "微信用户接口")
public class UserController {//包含内部人员、外部人员
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private CustomerService customerService;

    /*
    1.先查询user查看是否为内部人员
    2.若不是内部人员，查询外部人员
    3.外部人员也不存在，进行注册（因为小程序端直接获取手机号，任何用户都可以登录）
     */
    @PostMapping("/login")
    @ApiOperation("微信登陆")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){

        User user = userService.getUserByMobile(userLoginDTO.getTel());
        UserLoginVO userLoginVO = new UserLoginVO();

        //为微信用户生成jwt令牌
        Map<String ,Object> claims=new HashMap<>();
        Long userId = null;

        if (!ObjectUtils.isEmpty(user)){
            userLoginVO.setUserId(user.getId());
            userLoginVO.setRole(user.getRole());
            userLoginVO.setOpenid(user.getOpenid());
        }else{
            CustomerVO customer = customerService.getCustomerByMobile(userLoginDTO.getTel());
            if(ObjectUtils.isEmpty(customer)) {
                Customer customer1 = new Customer();
                customer1.setMobile(userLoginDTO.getTel());
                //补充
                customerService.addCustomer(customer1);

                customer = customerService.getCustomerByMobile(userLoginDTO.getTel());
            }
            userLoginVO.setUserId(customer.getId());
            userLoginVO.setRole(RoleEnum.EXTERNAL.getMsg());
            userLoginVO.setOpenid(customer.getOpenid());
        }

        claims.put(JwtClaimsConstant.USER_ID,userLoginVO.getUserId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        userLoginVO.setToken(token);

        return ResultUtil.success("success", userLoginVO);
    }

//    @PostMapping("/login")
//    @ApiOperation("微信登陆")
//    public Result login(@RequestBody UserLoginDTO userLoginDTO){
//        //微信登录
//        User user = userService.wxLogin(userLoginDTO);
//
//        //为微信用户生成jwt令牌
//        Map<String ,Object> claims=new HashMap<>();
//        claims.put(JwtClaimsConstant.USER_ID,user.getId());
//        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
//
//        UserLoginVO userLoginVO = new UserLoginVO();
//        userLoginVO.setUserId(user.getId());
//        userLoginVO.setOpenid(user.getOpenid());
//        userLoginVO.setRole(user.getRole());
//        userLoginVO.setToken(token);
//
//        return ResultUtil.success("success", userLoginVO);
//    }

    @PostMapping("/role")
    @ApiOperation("添加用户角色")
    public Result addRole(@RequestParam Long userId, @RequestBody Role role){
        roleRepository.save(role);
        return ResultUtil.success("success");
    }

    @GetMapping("/user/info")
    @ApiOperation("查询用户信息")
    public Result findUserInfo(){
        return ResultUtil.success("success");
    }

    @GetMapping("/customers")
    @ApiOperation("查询所有客户")
    public Result findAllCustomers(){
        return ResultUtil.success("success", customerService.getAllCustomers(false));
    }

    @GetMapping("/customers/{id}")
    @ApiOperation("按id选择客户")
    public Result findCustomerById(@PathVariable Long id){
        return ResultUtil.success("success", customerService.findByCustomerId( id));
    }

    @GetMapping("/customers/{key}")
    @ApiOperation("按关键字（姓名/手机号）选择客户")
    public Result findCustomerByKey(@PathVariable("key") String key){
        return ResultUtil.success("success", customerService.getCustomerByKey(key,false));
    }

    @GetMapping("/users")
    @ApiOperation("查询所有用户")
    public Result findAllUsers(Boolean isDelete){
        return ResultUtil.success("success", userService.getAllUsers(isDelete));
    }

    @GetMapping("/recommenders")
    @ApiOperation("查询所有推荐人")
    public Result findAllRecommenders(Boolean isDelete){
        return ResultUtil.success("success", userService.getAllRecommenders(isDelete));
    }
}
