package me.zhengjie.modules.thirdparty.v1;

import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousGetMapping;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.base.BaseResponse;
import me.zhengjie.base.QueryPageParams;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.dm.user.domain.DmUser;
import me.zhengjie.modules.dm.user.service.DmUserService;
import me.zhengjie.modules.dm.user.service.dto.DmUserDto;
import me.zhengjie.modules.dm.user.service.dto.DmUserQueryCriteria;
import me.zhengjie.modules.security.config.bean.LoginProperties;
import me.zhengjie.modules.security.config.bean.SecurityProperties;
import me.zhengjie.modules.security.security.TokenProvider;
import me.zhengjie.modules.security.service.OnlineUserService;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.utils.EncryptUtils;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.hibernate.Criteria;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "用户接口")
@RequestMapping("/api/thirdparty/v1/user")
public class UserApiController {
    private final DmUserService dmUserService;
    private final UserService userService;
    private final DeptService deptService;
    private final JobService jobService;
    private final RoleService roleService;
    private final TokenProvider tokenProvider;
    private final AuthenticationManagerBuilder authenticationManagerBuilder;
    private final OnlineUserService onlineUserService;
    private final SecurityProperties properties;
    @Resource
    private LoginProperties loginProperties;

    private final PasswordEncoder passwordEncoder;

    private final String erpapiUrl = "http://222.84.157.37:30170";

    private final String key = "DMERPYT!@#$QWER2021+{:>";

    @Log("获取ERP用户数据")
    @ApiOperation("获取ERP用户数据")
    @AnonymousGetMapping(value = "/busi/comm/usky/queryUser")
    public ResponseEntity<Object> getusers(HttpServletRequest request, String formData) throws IOException {
//        SecurityUtils.CheckApiAuth(request);
//        List<DmUserDto> list = dmUserService.queryAll(criteria);
        String url = "/api-third-party/busi/comm/usky/queryUser";
        String res = HttpRequest.get(erpapiUrl+url)
                .header("X_AUTO_USER_INFO_HEAD", "{\"id\":\"anonymous\",\"tenantId\":\"caih\"}")
                .body("{\n" +
                        "    \"formData\":{\n" +
                        "        \"pageNum\":1,\n" +
                        "        \"pageSize\":100\n" +
                        "    },\n" +
                        "    \"product\":\"17\",\n" +
                        "    \"sign\":\"e34b2f59-0e9d-45ed-a32a-f4abd4381000\"\n" +
                        "}").execute().body();
        JSONObject json = JSONObject.parseObject(res);
        return new ResponseEntity<>(json, HttpStatus.OK);
    }

//    @Log("单点登录")
//    @ApiOperation("单点登录")
//    @AnonymousGetMapping(value = "/sso")
//    public ResponseEntity<Object> sso(HttpServletRequest request) {
//        String token = request.getParameter("token");
//        String url = request.getParameter("url");
//
//        if (StringUtils.isBlank(token) || StringUtils.isBlank(url)) {
//            throw new BadRequestException("参数错误");
//        }
//
//        String res = HttpRequest.get(erpapiUrl + "/api-third-party/busi/comm/authLogin/api/verifyToken?token=" + token).execute().body();
//        JSONObject json = JSONObject.parseObject(res);
//
//        if (json != null) {
//            JSONObject data = json.getJSONObject("data");
//
//            if (data != null) {
//
//                UserDto userDto = userService.findByName(data.getString("username"));
//
//                if (userDto != null) {
//                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(data.getString("username"), userDto.getPassword());
//                    Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
//                    SecurityContextHolder.getContext().setAuthentication(authentication);
//                    // 生成令牌
//                    String n_token = tokenProvider.createToken(authentication);
//                    final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal();
//                    // 保存在线信息
//                    onlineUserService.save(jwtUserDto, n_token, request);
//                    // 返回 token 与 用户信息
//                    Map<String, Object> authInfo = new HashMap<String, Object>(2) {{
//                        put("token", properties.getTokenStartWith() + n_token);
//                        put("user", jwtUserDto);
//                    }};
//                    if (loginProperties.isSingleLogin()) {
//                        //踢掉之前已经登录的token
//                        onlineUserService.checkLoginOnUser(data.getString("username"), n_token);
//                    }
//                    return ResponseEntity.ok(authInfo);
//                }
//            }
//        }
//        throw new BadRequestException("认证失败");
//    }

    @Log("单点登录")
    @ApiOperation("单点登录")
    @AnonymousGetMapping(value = "/sso11")
    public BaseResponse<Object> sso11(String token) throws Exception {
        Map<String,Object> newToken = SecurityUtils.getToken(key);
        UserDto userDto = userService.findByName("chaoshengqin");
        //组装返回值
        JSONObject returnData = new JSONObject();
        returnData.put("nonce",newToken.get("nonce"));
        returnData.put("timestamp",newToken.get("timestamp"));
        returnData.put("token",newToken.get("token"));
        returnData.put("userId",userDto.getId());
        String cipher = EncryptUtils.desEncrypt(returnData.toJSONString());
        returnData.put("cipher", cipher);
        returnData.put("user", userDto);
        Map<String, Object> authInfo = new HashMap<String, Object>(1) {{
            put("data", returnData);
        }};
        return new BaseResponse<>(authInfo);
    }

    @Log("单点登录")
    @ApiOperation("单点登录")
    @AnonymousGetMapping(value = "/sso")
    public BaseResponse<Object> sso(String token) throws Exception {
        if (StringUtils.isBlank(token)) {
            throw new BadRequestException("参数错误");
        }
        String res = HttpRequest.get(erpapiUrl + "/api-third-party/busi/comm/authLogin/api/verifyToken?token=" + token).method(Method.POST).execute().body();
        JSONObject json = JSONObject.parseObject(res);
        if (json != null) {
            JSONObject data = json.getJSONObject("data");
            if (data != null) {
                UserDto userDto = userService.findByName(data.getString("username"));
                if (userDto != null) {
                    Map<String,Object> newToken = SecurityUtils.getToken(key);
                    //组装返回值
                    JSONObject returnData = new JSONObject();
                    returnData.put("nonce",newToken.get("nonce"));
                    returnData.put("timestamp",newToken.get("timestamp"));
                    returnData.put("token",newToken.get("token"));
                    returnData.put("userId",userDto.getId());
                    String cipher = EncryptUtils.desEncrypt(returnData.toJSONString());
                    returnData.put("cipher", cipher);
                    returnData.put("user", userDto);
                    Map<String, Object> authInfo = new HashMap<String, Object>(1) {{
                        put("data", returnData);
                    }};
                    return new BaseResponse<>(authInfo);
                }
            }
        }
        throw new BadRequestException("认证失败");
    }

    @Log("获取用户数据")
    @ApiOperation("获取用户数据")
    @AnonymousPostMapping(value = "/getzkusers")
    public BaseResponse<Object> getzkusers(@RequestBody QueryPageParams<DmUserQueryCriteria> params, Pageable pageable) {
        SecurityUtils.CheckApiAuth(params);
        Map<String, Object> list = dmUserService.queryAll(params.getQuery(), pageable);

        return new BaseResponse<>(list);
    }

    @Log("根据密文获取用户信息")
    @ApiOperation("根据密文获取用户信息")
    @AnonymousGetMapping(value = "/getZkUserByCipher")
    public BaseResponse<Object> getZkUserByCipher(String cipher) throws Exception {
        String dataStr = EncryptUtils.desDecrypt(cipher);
        JSONObject data = JSONObject.parseObject(dataStr);
        String token = data.getString("token");
        log.info("token:"+token);
        String timestamp = data.getString("timestamp");
        log.info("timestamp:"+timestamp);
        String nonce = data.getString("nonce");
        log.info("nonce:"+nonce);
        String userId = data.getString("userId");
        log.info("userId:"+userId);
        String[] arr = {"DMERPYT!@#$QWER2021+{:>", timestamp,nonce};
        Arrays.sort(arr);
        String str = "";
        for (int i = 0; i < arr.length; i++) {
            str += arr[i];
        }
        String newtoken = EncryptUtils.sha1(str);
        if (!token.equals(newtoken)) {
            throw new BadRequestException(HttpStatus.UNAUTHORIZED, "认证失败");
        }
        DmUserDto dmUser = dmUserService.findById(userId);
        return new BaseResponse<>(dmUser);
    }

    @Log("获取部门数据")
    @ApiOperation("获取部门数据")
    @AnonymousPostMapping(value = "/getzkdeps")
    public BaseResponse<Object> getzkdeps(@RequestBody QueryPageParams<DeptQueryNoAuthCriteria> params, Pageable pageable) {
        SecurityUtils.CheckApiAuth(params);
        Map<String, Object> list = deptService.queryAll(params.getQuery(), pageable);

        return new BaseResponse<>(list);
    }

    @Log("获取岗位数据")
    @ApiOperation("获取岗位数据")
    @AnonymousPostMapping(value = "/getzkjobs")
    public BaseResponse<Object> getzkjobs(@RequestBody QueryPageParams<JobQueryCriteria> params, Pageable pageable) {
        SecurityUtils.CheckApiAuth(params);
        Map<String, Object> list = jobService.queryAll(params.getQuery(), pageable);

        return new BaseResponse<>(list);
    }

    @Log("获取角色数据")
    @ApiOperation("获取角色数据")
    @AnonymousPostMapping(value = "/getzkroles")
    public BaseResponse<Object> getzkroles(@RequestBody QueryPageParams<RoleQueryCriteria> params, Pageable pageable) {
        SecurityUtils.CheckApiAuth(params);
        Map<String, Object> list = roleService.queryAll(params.getQuery(), pageable);

        return new BaseResponse<>(list);
    }

    @Log("修改人员数据")
    @ApiOperation("修改人员数据")
    @AnonymousPostMapping(value = "/updateZkUsers")
    public BaseResponse<Object> updateZkUsers(@RequestBody QueryPageParams<DmUser> params) {
        SecurityUtils.CheckApiAuth(params);
        System.out.println("params:"+params.getQuery().getId());
        dmUserService.update(params.getQuery());
        return new BaseResponse<>(null);
    }

    @Log("获取系统用户数据")
    @ApiOperation("获取系统用户数据")
    @AnonymousPostMapping(value = "/getZkSysUsers")
    public BaseResponse<Object> getZkSysUsers(@RequestBody QueryPageParams<UserQueryCriteria> params, Pageable pageable) {
        SecurityUtils.CheckApiAuth(params);
        return new BaseResponse<>(userService.queryAll(params.getQuery(), pageable));
    }
}