package com.loan.system.controller.admin;

import com.loan.system.constant.JwtClaimsConstant;
import com.loan.system.domain.dto.UserDTO;
import com.loan.system.domain.dto.UserLoginDTO;
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.pojo.Result;
import com.loan.system.domain.vo.UserLoginVO;
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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Edwin
 * @date 2020/9/2 - 19:11
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "管理端用户接口")
public class AdminController {//包含内部人员、外部人员
    @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());
        }else{
            return ResultUtil.error(ExceptionEnum.USER_NOT_EXIST);
        }

        claims.put(JwtClaimsConstant.USER_ID,userLoginVO.getId());
        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){
//        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);
//        }
//    }

    @PutMapping("/{id}")
    @ApiOperation("更新用户角色")
    public Result updateRole(@PathVariable("id") Long id,@RequestBody String role){
        User user1 = userService.findByIdAndIsDelete(id);
        if(ObjectUtils.isEmpty(user1)){
            return ResultUtil.error(ExceptionEnum.USER_NOT_EXIST);
        }
        userService.updateUserRole(role,id);
        return ResultUtil.success("success");
    }

    @PostMapping
    @ApiOperation("新增用户")
    @PreAuthorize("@pms.hasRole('SYSTEM_ADMIN')")
    public Result addUser(@RequestBody UserDTO user){
        userService.addUser(user);

        return ResultUtil.success("success");
    }

    @PutMapping("/delete/{id}")
    @ApiOperation("删除用户")
    @PreAuthorize("@pms.hasRole('SYSTEM_ADMIN')")
    public Result deleteUser(@PathVariable Long id){
        User user = userService.findByIdAndIsDelete(id);
        if(ObjectUtils.isEmpty(user)){
            return ResultUtil.error(ExceptionEnum.USER_NOT_EXIST);
        }
        user.setIsDelete(true);
        userService.deleteUserByLogic(id);

        return ResultUtil.success("success");
    }

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

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

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

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

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

    @GetMapping("/users/sales")
    @ApiOperation("查询所有业务员")
    @PreAuthorize("@pms.hasAnyRoles('SYSTEM_ADMIN','APPROVER')")
    public Result findAllSales(){
        return ResultUtil.success("success", userService.getAllSalesByIsDelete(false));
    }


}
