package com.tykj.dev.device.user.subject.controller;

import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.user.base.req.*;
import com.tykj.dev.device.user.base.ret.UserUpdatePw;
import com.tykj.dev.device.user.config.MyFilter;
import com.tykj.dev.device.user.config.MyUserDetailsServiceImpl;
import com.tykj.dev.device.user.subject.entity.SecurityUser;
import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.service.*;
import com.tykj.dev.device.user.util.LogoutUtil;
import com.tykj.dev.socket.MyWebSocket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName UserController.java
 * @Description TODO
 * @createTime 2020年07月28日 09:02:00
 */
@RestController
@AutoDocument
@Api(tags = "用户模块", description = "提供用户相关的接口")
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    UnitsService unitsService;

    @Autowired
    VenitalisService venitalisService;

    @Autowired
    MyUserDetailsServiceImpl myUserDetailsService;
    @Autowired
    LogoutUtil logout;

    @Autowired
    MyWebSocket myWebSocket;
//    @PostMapping(value = "/login")
//    @ApiOperation(value = "用户新增接口", notes = "添加成功返回用户对象")
//    public ResponseEntity loginUser(@RequestBody LoginUser loginUser){
//        User user=userService.findByUserName(loginUser.getUserName());
//        if (user==null){
//            return ResponseEntity.status(201).body(null);
//        }else if (!user.getMPassWord().equals(loginUser.getUserName())){
//            return ResponseEntity.status(202).body(null);
//        }
//        Units units=  unitsService.findById(user.getUnitsId());
//        //查询权限的步骤
//        UserRe userRe=new UserRe(user.getUserId(),user.getUserName(),user.getName(),units,new Permissions());
//
//        return ResponseEntity.ok(userRe);
//    }

    @ApiOperation(value = "用户登出")
    @GetMapping("/userLogout")
    public void logout(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser) {
        log.info("调用登出接口");
        myWebSocket.Close(String.valueOf(securityUser.getCurrentUserInfo().getUserId()));
        logout.logout();
    }

    @Autowired
    MyFilter myFilter;

    private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();
    @ApiOperation(value = "用户登出")
    @PostMapping("/s")
    private ResponseEntity login(@RequestBody LoginUser loginUser, HttpServletRequest request, HttpServletResponse response){
        UserDetails userDetails = myUserDetailsService.loadUserByUsername(loginUser.getUsername());
        myFilter.attemptAuthentication(request,response);
        return ResponseEntity.ok(userDetails);
    }

    @PostMapping(value = "/save")
    @ApiOperation(value = "用户新增接口", notes = "添加成功返回用户对象")
    public ResponseEntity saveUser(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser,@RequestBody User user) {
        return ResponseEntity.ok(userService.save(user,securityUser));
    }

    @GetMapping(value = "/delete/{userId}")
    @ApiOperation(value = "用户删除接口", notes = "删除返回true，false")
    public ResponseEntity deleteUser(@PathVariable Integer userId) {
        return ResponseEntity.ok(userService.delete(userId));
    }

    @PostMapping(value = "/update")
    @ApiOperation(value = "用户更新接口", notes = "更新成功返回用户对象")
    public ResponseEntity updateUser(@RequestBody User user) {
        return ResponseEntity.ok(userService.update(user));
    }

    @GetMapping(value = "/findAll")
    @ApiOperation(value = "所有用户查询接口", notes = "成功返回用户对象集合")
    public ResponseEntity findAllUser(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser) {
        return ResponseEntity.ok(userService.findAll());
    }

    @GetMapping(value = "/findAll/{unitsId}")
    @ApiOperation(value = "根据单位查询用户(下拉)", notes = "成功返回用户对象集合")
    public ResponseEntity findAll2(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser, @PathVariable Integer unitsId) {
        return ResponseEntity.ok(userService.findByUniteId(unitsId));
    }

    @GetMapping(value = "/find/user")
    @ApiOperation(value = "查询当前登入用户信息", notes = "成功返回用户对象")
    public ResponseEntity findUserId(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser) {
        return ResponseEntity.ok(securityUser.getCurrentUserInfo());
    }

    @GetMapping(value = "/findAll/units/{userId}")
    @ApiOperation(value = "根据用户id查询同级用户接口(下拉)", notes = "成功返回用户对象集合")
    public ResponseEntity findAll1(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser, @PathVariable Integer userId) {

        return ResponseEntity.ok(userService.findByUserId(userId));
    }

    @PostMapping(value = "/archives/update/password")
    @ApiOperation(value = "修改用户密码", notes = "返回修改结果")
    public ResponseEntity updatePassword(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser, @RequestBody UserUpdatePw userUpdatePw) {

        Integer core = userService.updatePw(userUpdatePw);
        switch (core) {
            case -1:
                return ResponseEntity.ok("原密码不对，请重新修改");
            case -2:
                return ResponseEntity.ok("没有查询的对应的用户");
        }
        return ResponseEntity.ok("修改密码成功");
    }

    @GetMapping(value = "/get/trainUnits/{userId}")
    @ApiOperation(value = "根据用户id查询下级单位列表", notes = "成功返回UnitsTrainVo对象集合")
    public ResponseEntity getFindTrainVo(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser, @PathVariable Integer userId) {

        return ResponseEntity.ok(userService.findByIdUnitsTrainVo(userId));
    }

    @GetMapping(value = "/detail/{userId}")
    @ApiOperation(value = "根据用户id查询用户详情", notes = "成功返回UnitsTrainVo对象集合")
    public ResponseEntity getFindMemberThatVo(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser, @PathVariable Integer userId) {

        return ResponseEntity.ok(userService.findById(userId));
    }

    @GetMapping("/findAll/superiorList")
    @ApiOperation(value = "根据用户ID查询上级单位用户", notes = "List<UserSuperiorVo>")
    public ResponseEntity getFindMemberThatVo(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser) {

        return ResponseEntity.ok(userService.findUserSuperiorVo(securityUser.getCurrentUserInfo().getUserId()));
    }

    @GetMapping("/uuid")
    @ApiOperation(value = "获取uuid电子签章使用", notes = "uuid")
    public ResponseEntity getUuid(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser) {

        return ResponseEntity.ok(UUID.randomUUID().toString());
    }

    @PostMapping("/save/ven")
    @ApiOperation(value = "指静脉注册接口", notes = "List<UserSuperiorVo>")
    public ResponseEntity saveVen(@RequestBody VenitalisVo venitalisVo) {

        return ResponseEntity.ok(venitalisService.registeredRet(venitalisVo));
    }


    @GetMapping("/test")
    @ApiOperation(value = "1111111111111", notes = "uuid")
    public ResponseEntity getUuid1(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser) {

        return ResponseEntity.ok(userService.findAllLastUserids(securityUser.getCurrentUserInfo().getUserId()));
    }

    @GetMapping("/up/date")
    @ApiOperation(value = "重新设置密码", notes = "重新设置密码")
    public ResponseEntity date() {
        userService.updateUserPass();
        return ResponseEntity.ok("ok");
    }

    @PostMapping("/notIs/add")
    @ApiOperation(value = "下拉列表添加用户接口（用户不能登入）")
    public ResponseEntity addNotIsUser(@RequestBody NotIsUser notIsUser){
        return ResponseEntity.ok(userService.addNoIsUser(notIsUser));
    }


    @PostMapping("/replaceOptFor")
    @ApiOperation(value = "下拉列表选择用户换位置的接口")
    public ResponseEntity replaceOptFor(@RequestBody DropDownUserLocation dropDownUserLocation){
        userService.replaceOptFor(dropDownUserLocation);
        return ResponseEntity.ok("替换完成");
    }

    @PostMapping("/list/unitName")
    @ApiOperation(value = "根据单位名称查询单位用户")
    public ResponseEntity findUnitName(@RequestBody UnitNameVo unitNameVo){
        return ResponseEntity.ok(userService.findUnitNameListUser(unitNameVo));
    }

    @PostMapping("/specialManager/list/{unitId}")
    @ApiOperation(value = "根据单位id查询单位专管员")
    public ResponseEntity findUnitName( @PathVariable Integer unitId){
        return ResponseEntity.ok(userService.findUnitIdListUser(unitId));
    }

}
