package io.hmit.controller;


import io.hmit.annotation.Login;
import io.hmit.common.utils.Result;
import io.hmit.common.validator.ValidatorUtils;
import io.hmit.config.ZhelibanUtils;
import io.hmit.dto.LoginDTO;
import io.hmit.entity.TokenEntity;
import io.hmit.entity.UserEntity;
import io.hmit.modules.user.dto.RoleDTO;
import io.hmit.modules.user.dto.UserRoleDTO;
import io.hmit.modules.user.service.RoleService;
import io.hmit.modules.user.service.UserRoleService;
import io.hmit.service.TokenService;
import io.hmit.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录接口
 *
 * @author zsh 408538940@qq.com
 */
@RestController
@RequestMapping("/api")
@Api(tags = "登录接口")
public class ApiLoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;


    @PostMapping("login")
    @ApiOperation("登录")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO dto) {

        //表单校验
        ValidatorUtils.validateEntity(dto);

        //用户登录
        Map<String, Object> map = userService.login(dto);

        return new Result().ok(map);
    }

    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public Result logout(@ApiIgnore @RequestAttribute("userId") Long userId) {

        tokenService.expireToken(userId);
        return new Result();
    }

    //个人登录 - 单点登陆
    @RequestMapping(value="/check_user")
    @ApiOperation("单点登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ticket", value = "票据", paramType = "query", required = true, dataType="String") ,
    })
    public Result checkUser(@ApiIgnore @RequestParam Map<String,Object> map , HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        // 获取到票据信息ticket
        System.out.println("开始进入这个checkuser了————————————————————");
        System.out.println(map);
        Long userId;
        Map<String, Object> userMap = new HashMap<>();

        if(map.get("ticket") != null){
            System.out.println("Ticket 是"+map.get("ticket")+"——————————————————————");
            Map<String,Object> user_map = ZhelibanUtils.getUserInfo(map);
            System.out.println("UserMap是——————————————————————————————");
            System.out.println(user_map);
            if ("6001".equals(user_map.get("result"))){
                return new Result().error("ticket失效");
            }
            if (user_map.get("idnum") !=null){
                //判断是否已经存在了这条信息
                UserEntity oldUser=userService.getByIdno(URLEncoder.encode(user_map.get("idnum").toString(), "UTF8"));

                List<UserRoleDTO> roleList= new ArrayList<>();
                if(oldUser==null){
                    //判断是否已经存在了这条信息
                    UserEntity oldUserMobile=userService.getByMobile(URLEncoder.encode(user_map.get("mobile").toString(), "UTF8"));

                    if(oldUserMobile == null){
                        return  new Result().error("系统中不存在，麻烦联系后台管理员进行添加后再试");

                    }else{

                        userId = oldUserMobile.getId();
                        roleList= userRoleService.getRoleByUsers(userId);
                        roleList.stream().forEach(item ->{
                            RoleDTO role = roleService.get(item.getRoleId());
                                    item.setRoleName(role.getName());
                                    item.setTempId(role.getTempId());
                                });

                        userMap.put("username", oldUserMobile.getUsername());
                        userMap.put("mobile", oldUserMobile.getMobile());
                        userMap.put("idnum",oldUserMobile.getUserIdno());
                        userMap.put("accountId",user_map.get("userid").toString());
                        userMap.put("userId",userId);
                        userMap.put("roleList",roleList);

                        TokenEntity tokenEntity = tokenService.createToken(userId);
                        userMap.put("token", tokenEntity.getToken());
                        userMap.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());
                        return new Result().ok(userMap);
                    }

                }

                userId = oldUser.getId();
                userMap.put("username", oldUser.getUsername());
                userMap.put("mobile", oldUser.getMobile());
                userMap.put("idnum",oldUser.getUserIdno());
                userMap.put("accountId",user_map.get("userid").toString());
                userMap.put("userId",userId);

                //添加用户权限列表(用户权限、权限名称、模版ID)
                roleList= userRoleService.getRoleByUsers(userId);
                roleList.stream().forEach(item ->{
                    RoleDTO role = roleService.get(item.getRoleId());
                    item.setRoleName(role.getName());
                    item.setTempId(role.getTempId());
                });
                userMap.put("roleList",roleList);

                TokenEntity tokenEntity = tokenService.createToken(userId);
                userMap.put("token", tokenEntity.getToken());
                userMap.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());
            }
            return new Result().ok(userMap);
        }else{
            return new Result().error("票据信息为空");
        }
    }

}
