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

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.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.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, "登录成功");
    }



    @Override
    public ReturnMsg getUserData() {
        String url = restTemplateConfig.addBaseUrl(USER_URL)+"?pageNum=1&pageSize=1000";
        // 创建RestTemplate
        RestTemplate restTemplate = restTemplateConfig.build();
        // 发送GET请求
        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){
                userMapper.delete(new LambdaQueryWrapper<Users>().gt(Users::getId,2));
                for (int i=0;i<list.size();i++){
                    LinkedHashMap json = (LinkedHashMap) list.get(i);
                    Users users = new Users();
                    users.setId((Integer) json.get("id"));
                    users.setUserName(String.valueOf(json.get("staffNo")));
                    users.setName(String.valueOf(json.get("staffName")));
                    users.setPhone(String.valueOf(json.get("phone")));
                    users.setPassword(Pbkdf2Sha256Digest.encode("123456"));
                    userMapper.insert(users);

                }
            }
            return ReturnMsg.ok();

        }else{
            log.info("获取双碳通知数据："+message);
            return  ReturnMsg.fail(message);
        }
      //  return null;
    }
}
