package com.sky.ioc.service.system.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.ioc.config.RestTemplateConfig;
import com.sky.ioc.constant.Constant;
import com.sky.ioc.entity.domain.system.Menus;
import com.sky.ioc.entity.domain.system.Users;
import com.sky.ioc.entity.result.system.LoginUserVo;
import com.sky.ioc.mapper.job.TokenMapper;
import com.sky.ioc.mapper.system.MenuMapper;
import com.sky.ioc.mapper.system.UserMapper;
import com.sky.ioc.service.system.UserService;
import com.sky.ioc.tool.JwtUtil;
import com.sky.ioc.tool.Pbkdf2Sha256Digest;
import com.sky.ioc.tool.RedisUtil;
import com.sky.ioc.tool.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    RestTemplateConfig restTemplateConfig;

    final static  String USER_URL="/api/hr/HR/staff/list";

    @Override
    public ReturnMsg updateCommonMenusByUserIdAndMenuId(long userId, String menuIDs) {
        userMapper.updateCommonMenusByUserIdAndMenuId(userId,menuIDs);
       return ReturnMsg.ok();
    }

    @Override
    public ReturnMsg login(String username, String password) {
        Users users = userMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getUserName, username));
        if (Objects.isNull(users)){
            throw new RuntimeException("用户名或密码错误");
        }
        boolean verification = Pbkdf2Sha256Digest.verification(password, users.getPassword());
        if (!verification){
            throw new RuntimeException("用户名或密码错误");
        }

        // 认证成功
        LoginUserVo loginUser = new LoginUserVo();
        BeanUtils.copyProperties(users, loginUser);

        String token = JwtUtil.genJwtToken(users);

        // 将用户信息存入redis
        redisUtil.put("login:"+loginUser.getUserName(), loginUser);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userInfo", loginUser);
        jsonObject.put("token", token);
        return ReturnMsg.ok(jsonObject, "登录成功");
    }

    @Override
    public ReturnMsg logout() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        // 前端注销，后端暂不处理
        return ReturnMsg.ok("注销成功");
    }

    @Override
    public ReturnMsg validate() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        String username = JwtUtil.parseJWT(token);
        Users users = userMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getUserName, username));
        LoginUserVo loginUser = new LoginUserVo();
        BeanUtils.copyProperties(users, loginUser);
        return ReturnMsg.ok(loginUser);
    }

    @Override
    public ReturnMsg updatePassword(long userId, String oldPwd, String newPwd) {
        Users users = userMapper.selectById(userId);
        boolean verification = Pbkdf2Sha256Digest.verification(oldPwd, users.getPassword());
        if (!verification){
            return ReturnMsg.fail("旧密码错误");
        }else{
           String hashedPassword =Pbkdf2Sha256Digest.encode(newPwd);
           users.setPassword(hashedPassword);
           userMapper.update(users,new LambdaQueryWrapper<Users>().eq(Users::getId, userId));
            return ReturnMsg.ok();
        }

    }

    @Override
    public ReturnMsg phoneLogin(String phone, String code) {
        Users users = userMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getPhone, phone));
        if (Objects.isNull(users)){
            throw new RuntimeException("手机号不存在");
        }
        //校验验证码
        boolean verification = code==null?false:code.equals(Constant.PHONE_CODE);
                //Pbkdf2Sha256Digest.verification(password, users.getPassword());
        if (!verification){
            throw new RuntimeException("验证码错误");
        }

        // 认证成功
        LoginUserVo loginUser = new LoginUserVo();
        BeanUtils.copyProperties(users, loginUser);

        String token = JwtUtil.genJwtToken(users);

        // 将用户信息存入redis
        redisUtil.put("login:"+loginUser.getUserName(), loginUser);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userInfo", loginUser);
        jsonObject.put("token", token);
        return ReturnMsg.ok(jsonObject, "登录成功");
    }

    @Value("${sky.dataIp}")
    private String dataIp;

    @Autowired
    TokenMapper tokenMapper;

    @Override
    public ReturnMsg getUserData() {
        log.info(String.format("获取登录token!  时间:" + new Date()));
        // 1.请求URL
        String postUrl = "http://"+dataIp+"/api/auth/login";
        // 2.请求参数JSON格式
        Map<String,String> map = tokenMapper.getNewToken();
        if(map==null){
            map = new HashMap<>();
            map.put("username","admin");
            map.put("password","admin123");
            tokenMapper.addToken(1,"admin","admin123");
        }
        map.put("loginType","API-TOKEN");
        String json = JSON.toJSONString(map);
        // 3.创建RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        // 4.设置RestTemplate参数(请求头和body)
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(mediaType);
        headers.add("Accept", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        // 5.使用RestTemplate发起请求与接收返回值
        String resultData = restTemplate.postForObject(postUrl, entity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(resultData);
        Integer code = jsonObject.getInteger("code");
        String msg = jsonObject.getString("msg");
        if(code==200){
            JSONObject data = jsonObject.getJSONObject("data");
            String token = data.getString("access_token");
            String id = String.valueOf(map.get("id"));
            tokenMapper.updateToken(Integer.parseInt(id),token);
            log.info("token : "+token);
            //  System.out.println("data   "+data.getString(""));
        }else{
            log.info("登录接口失败："+msg);
        }
       return null;
    }

    @Override
    public ReturnMsg getUserList() {
        // 1.请求URL
        RestTemplate restTemplate = restTemplateConfig.build();
        String postUrl = "http://"+dataIp+"/api/hr/HR/staff/list?pageNum=1&pageSize=10000";
        String url = restTemplateConfig.addBaseUrl(postUrl);
        ResponseEntity<Map> responseEntity = restTemplate.getForEntity(url, Map.class);
        // 获取响应对象里的 body 对象
        Map<String, Object> body = responseEntity.getBody();
        // 获取状态码
        Integer code = (Integer)body.get("code");
        // 获取响应信息
        String message = (String)body.get("msg");
        if(code==200){
            ArrayList list = (ArrayList) body.get("rows");
            if(list!=null&&list.size()>0){
                for (int i=0;i<list.size();i++){
                    LinkedHashMap json = (LinkedHashMap) list.get(i);
                    String staffNo = json.get("staffNo").toString();
                    Users users = userMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getUserName,staffNo));
                    if(users==null){
                        users = new Users();
                        users.setUserName(staffNo);
                        users.setName(json.get("staffName").toString());
                        users.setPhone(json.get("phone").toString());
                        users.setCompany(json.get("departName").toString());
                        users.setEmail(json.get("email").toString());
                        String password = Pbkdf2Sha256Digest.encode("123456");
                        users.setPassword(password);
                        userMapper.insert(users);
                    }
                }
            }
            return ReturnMsg.ok();
            //  System.out.println("data   "+data.getString(""));
        }else{
            log.info("获取用户数据失败："+message);
            return ReturnMsg.fail(message);
        }
    }

}
