package com.dji.sample.manage.controller;

import com.aliyun.oss.internal.SignUtils;
import com.dji.sample.common.error.CommonErrorEnum;
import com.dji.sample.common.util.IPUtils;
import com.dji.sample.manage.model.dto.UserDTO;
import com.dji.sample.manage.model.dto.UserLoginDTO;
import com.dji.sample.manage.service.IUserService;
import com.dji.sdk.common.HttpResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

import static com.dji.sample.component.AuthInterceptor.PARAM_TOKEN;

@RestController
@RequestMapping("${url.manage.prefix}${url.manage.version}")
public class LoginController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public HttpResultResponse login(@RequestBody UserLoginDTO loginDTO, HttpServletRequest request) {


        // Get request info for logging
        String ipAddress = IPUtils.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        loginDTO.setIpAddress(ipAddress);
        loginDTO.setUserAgent(userAgent);

        return userService.userLogin(loginDTO);
    }

    @PostMapping("/token/refresh")
    public HttpResultResponse refreshToken(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(PARAM_TOKEN);
        Optional<UserDTO> user = userService.refreshToken(token);

        if (user.isEmpty()) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return HttpResultResponse.error(CommonErrorEnum.NO_TOKEN.getMessage());
        }

        return HttpResultResponse.success(user.get());
    }

    @PostMapping("/token/changeOrg")
    public HttpResultResponse changeOrg(HttpServletRequest request, HttpServletResponse response,
                                        @RequestParam(name = "org_id") String orgId) {
        String token = request.getHeader(PARAM_TOKEN);
        Optional<UserDTO> user = userService.changeOrgRefreshToken(token, orgId);

        if (user.isEmpty()) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return HttpResultResponse.error(CommonErrorEnum.NO_TOKEN.getMessage());
        }

        return HttpResultResponse.success(user.get());
    }

    /**
     * 游客登录
     * @param loginDTO
     * @return
     */
    @PostMapping("/visitorLogin")
    public HttpResultResponse visitorLogin(@RequestBody UserLoginDTO loginDTO) {

        String timestamp = loginDTO.getTimestamp();
        String sign = loginDTO.getSign();
        String nonce = loginDTO.getNonce();
        String appKey = loginDTO.getAppKey();

        // 验证不通过
//        if (ObjectUtils.isEmpty(loginDTO)) {
//            return new HttpResultResponse()
//                    .setCode(HttpStatus.UNAUTHORIZED.value())
//                    .setMessage("invalid visitor login");
//        }
        // 2️⃣ 时间戳校验
        // response.sendError(401, "Timestamp expired");

        // 3️⃣ nonce 防重放
         // response.sendError(401, "Duplicate nonce");

        // 4️⃣ 获取 secret（你自己实现）

        // 5️⃣ 服务端重新算 sign


        // 目前默认游客登录账号为admin
        loginDTO.setUsername("admin");
        loginDTO.setPassword("Geoair#123");

        return userService.userLogin(loginDTO);
    }

}
