package com.aiup.api.controller;

import com.aiup.service.domain.R;
import com.aiup.service.domain.WxCodeSessionResult;
import com.aiup.service.domain.openai.ChatResponse;
import com.aiup.service.domain.query.*;
import com.aiup.service.domain.response.GptChatResponse;
import com.aiup.service.domain.response.WeChatLoginResponse;
import com.aiup.service.domain.response.WeChatSessionKeyResponse;
import com.aiup.service.entity.UserInfo;
import com.aiup.service.entity.UserLoginLog;
import com.aiup.service.service.UserInfoService;
import com.aiup.service.service.UserLoginLogService;
import com.aiup.service.service.WeChatLoginService;
import com.aiup.service.utils.JwtUtils;
import com.aiup.service.utils.LoginUserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.Collator;
import java.util.*;

@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/v1/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private WeChatLoginService weChatLoginService;

    @Autowired
    private UserLoginLogService userLoginLogService;

    @ApiOperation(value = "微信用户登录")
    @PostMapping("/weChatLogin")
    public R<WeChatLoginResponse> weChatLogin(@Validated @RequestBody WeChatLoginQuery query) {
        //1.微信授权校验
        WxCodeSessionResult openIdByCode = weChatLoginService.getOpenIdByCode(query.getCode());
        if (openIdByCode.getErrcode() != null && openIdByCode.getErrcode() != 0) {
            return R.error(openIdByCode.getErrcode(), "授权登录失败");
        }

        //2.保存用户信息
        UserInfo qUser = new UserInfo();
        qUser.setOpenId(openIdByCode.getOpenid());
        qUser.setIsDeleted(0);
        PageRequest pq = PageRequest.of(0,100);
        List<UserInfo> content = userInfoService.queryByPage(qUser, pq).getContent();
        UserInfo userInfo = null;
        if(content != null && content.size() >0)
        {
            userInfo = content.get(0);
        }
        if (userInfo != null && userInfo.getStatus() != 1) {
            return R.error("该账号已被禁用，请联系管理员");
        }
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setOpenId(openIdByCode.getOpenid());
            userInfo.setCreateTime(new Date());
            userInfo.setStatus(1);
            userInfo.setIsDeleted(0);
            userInfo = userInfoService.insert(userInfo);
        } else {
            //修改用户信息
            userInfo.setUpdateTime(new Date());
            userInfo = userInfoService.update(userInfo);
        }
        //3.发放token
        String sign = JwtUtils.sign(userInfo);
        Date expireTime = JwtUtils.getExpireByToken(sign);
        WeChatLoginResponse response = new WeChatLoginResponse();
        response.setLoginUserInfo(userInfo);
        response.setToken(sign);
        response.setTokenExpireTime(expireTime.getTime());
        //添加登录日志
        UserLoginLog log = new UserLoginLog();
        log.setToken(sign);
        log.setUserId(userInfo.getUserId());
        log.setCreateTime(new Date());
        userLoginLogService.insert(log);
        return R.ok(response);
    }

    @ApiOperation(value = "微信登录第一步：获取openId和sessionKey")
    @PostMapping("/getSessionKey")
    public R<WeChatSessionKeyResponse> getSessionKey(@Validated @RequestBody WeChatLoginQuery query) {
        WeChatSessionKeyResponse response = weChatLoginService.getSessionKey(query);
        return R.ok(response);
    }
    @ApiOperation(value = "微信登录第二步：解密微信数据")
    @PostMapping("/sendWxGetUserInfo")
    public R<UserInfo> deCodeWxUserInfo(@Validated @RequestBody WeChatGetMobileQuery query) {
        query.setUserId(LoginUserUtils.getLoginUser().getUserId());
        UserInfo response = weChatLoginService.deCodeWxUserInfo(query);
        return R.ok(response);
    }



    @ApiOperation(value = "更新用户信息")
    @PostMapping("/updateUserInfo")
    public R<UserInfo> updateUserInfo(@Validated @RequestBody UpdateUserInfoQuery query) {
        query.setUserId(LoginUserUtils.getLoginUser().getUserId());
        UserInfo response = weChatLoginService.updateUserInfo(query);
        return R.ok(response);
    }

    @ApiOperation(value = "获取用户信息")
    @PostMapping("/getLoginUserInfo")
    public R<UserInfo> getLoginUserInfo(@Validated @RequestBody UserInfoQuery query) {
        return R.ok(LoginUserUtils.getLoginUser());
    }

}
