package com.loan.system.controller.wechat;

import com.loan.system.constant.JwtClaimsConstant;
import com.loan.system.domain.dto.UserLoginDTO;
import com.loan.system.domain.dto.WeChatLoginDTO;
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.CustomerLoginVO;
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.Impl.UserServiceImpl;
import com.loan.system.service.UserService;
import com.loan.system.service.WxService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
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;

    @Autowired
    private WxService wxService;

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    /*
    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.setId(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.setId(customer.getId());
//            userLoginVO.setRole(RoleEnum.EXTERNAL.getMsg());
//            userLoginVO.setOpenid(customer.getOpenid());
//        }
//
//        claims.put(JwtClaimsConstant.USER_ID,userLoginVO.getId());
//        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
//        userLoginVO.setToken(token);
//
//        return ResultUtil.success("success", userLoginVO);
//    }
    @GetMapping("/get_sessionId")
    @ApiOperation("获取微信openid")
    public Result get_sessionId(String code){
        return userService.get_sessionId(code);
    }
    public Result customer_login(Customer customer){
        customer=customerService.findBymobileAndIsDelete(customer.getMobile());
        if (ObjectUtils.isEmpty(customer))
            throw new IllegalArgumentException("Customer object is null");
        //为微信用户生成jwt令牌
        Map<String ,Object> claims=new HashMap<>();
        //用openid还是id?
        //claims.put(JwtClaimsConstant.CUSTOMER_ID,customer.getOpenid());
        claims.put(JwtClaimsConstant.USER_ID,customer.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        log.info("手机号码：{}",customer.getMobile());
        CustomerLoginVO customerLoginVO = CustomerLoginVO.builder()
                .id(customer.getId())
                .openid(customer.getOpenid())
                .token(token)
                .name(customer.getName())
                .is_customer(1)
                .build();

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

    /**
     * 用户登陆
     * @param userLoginDTO
     * @return
     */
    public Result user_login(UserLoginDTO userLoginDTO){
        User user= userService.findByPhoneNumberAndIsDelete(userLoginDTO.getTel());
        if (ObjectUtils.isEmpty(user))
            throw new IllegalArgumentException("User object is null");
        //为微信用户生成jwt令牌
        Map<String ,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        log.info("手机号码：{}",userLoginDTO.getTel());
        log.info("用户ID：{}",user.getId());
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .role(user.getRole())
                .is_customer(0)
                .userName(user.getUsername())
                .build();

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

    /**
     * 注册客户
     * @param customer
     * @return
     */
    public Result register(Customer customer){
        customer.setCreateTime(LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        customer.setUpdateTime(LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        customer.setIsDelete(false);
        customerService.addCustomer(customer);
        return this.customer_login(customer);
    }

    @PostMapping("/login_wechat")
    @ApiOperation("微信手机号登陆")
    public Result login(@RequestBody WeChatLoginDTO weChatLoginDTO){
        String access_token=wxService.getAccessToken();
        String phoneNumber=wxService.getUserPhoneNumber(access_token,weChatLoginDTO.getCode());
        boolean user_is_exist = userService.existsByMobileAndIsDelete(phoneNumber);
        boolean customer_is_exist=customerService.existsBymobileAndIsDelete(phoneNumber);
        log.info("code:{}",phoneNumber);
        log.info("用户是否存在:{}",user_is_exist);
        if(!customer_is_exist&&!user_is_exist){
            Customer customer = new Customer();
            customer.setMobile(phoneNumber);
            customer.setOpenid(weChatLoginDTO.getOpenid());
            return this.register(customer);
        }else if(customer_is_exist){   //存在客户
            Customer customer=customerService.findBymobileAndIsDelete(phoneNumber);
            return this.customer_login(customer);
        }else { //存在用户
            UserLoginDTO userLoginDTO = new UserLoginDTO();
            userLoginDTO.setTel(phoneNumber);
            return this.user_login(userLoginDTO);
        }
    }
    @PostMapping("/login")
    @ApiOperation("账号登陆")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        String phoneNumber=userLoginDTO.getTel();
        boolean user_is_exist = userService.existsByMobileAndIsDelete(phoneNumber);
        boolean customer_is_exist=customerService.existsBymobileAndIsDelete(phoneNumber);
        if(!customer_is_exist&&!user_is_exist){
            Customer customer = new Customer();
            customer.setMobile(phoneNumber);
            customer.setOpenid(userLoginDTO.getOpenid());
            return this.register(customer);
        }else if(customer_is_exist){
            Customer customer=customerService.findBymobileAndIsDelete(phoneNumber);
            return this.customer_login(customer);
        }else{
            return this.user_login(userLoginDTO);
        }
    }


    @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.findByCustomerIdAndIsDelete( id, false));
    }

    @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));
    }
}
