package com.ai.da.controller;

import com.ai.da.common.constant.CommonConstant;
import com.ai.da.common.response.Response;
import com.ai.da.common.utils.MinioUtil;
import com.ai.da.mapper.primary.entity.GoogleUser;
import com.ai.da.model.dto.*;
import com.ai.da.model.vo.AccountLoginVO;
import com.ai.da.model.vo.DesignCollectionVO;
import com.ai.da.service.AccountService;
import com.ai.da.service.DesignService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.security.cert.X509Certificate;


@Api(tags = "Third Party Modules")
@Slf4j
@RestController
@RequestMapping("/api/third/party")
public class ThirdPartyController {

    @Resource
    private AccountService accountService;

    @Resource
    private DesignService designService;

    @Resource
    private MinioUtil minioUtil;

    /*@ApiOperation(value = "Add user information")
    @PostMapping("/addUser")
    public Response<Boolean> addUser(@Valid @RequestBody AccountAddDTO accountAddDTO) {
        return Response.success(accountService.addUser(accountAddDTO));
    }*/

    @ApiOperation(value = "Edit user information")
    @PostMapping("/editUser")
    public Response<Boolean> editUser(@RequestBody AccountEditDTO accountEditDTO) {
        return Response.success(accountService.editUser(accountEditDTO));
    }

    @CrossOrigin
    @ApiOperation(value = "Add user information")
    @PostMapping("/addTrialUser")
    public Response<Boolean> addTrialUser(@RequestBody AccountTrialDTO accountTrialDTO, HttpServletRequest request) {
        return Response.success(accountService.addTrialUser(accountTrialDTO, request));
    }

    @CrossOrigin
    @ApiOperation(value = "add No Login Required")
    @PostMapping("/addNoLoginRequired")
    public Response<Boolean> addNoLoginRequired(@RequestBody NoLoginRequiredDTO noLoginRequiredDTO) {
        return Response.success(accountService.addNoLoginRequired(noLoginRequiredDTO));
    }

    @CrossOrigin
    @ApiOperation(value = "add No Login Required")
    @PostMapping("/deleteNoLoginRequired")
    public Response<Boolean> deleteNoLoginRequired(@RequestBody NoLoginRequiredDTO noLoginRequiredDTO) {
        return Response.success(accountService.deleteNoLoginRequired(noLoginRequiredDTO));
    }

    @CrossOrigin
    @ApiOperation(value = "add No Login Required")
    @PostMapping("/existNoLoginRequired")
    public Response<Boolean> existNoLoginRequired(@RequestBody NoLoginRequiredDTO noLoginRequiredDTO, HttpServletRequest request) {
        return Response.success(accountService.existNoLoginRequired(noLoginRequiredDTO, request));
    }

    @GetMapping("/your-secured-endpoint")
//    @PreAuthorize("hasRole('ROLE_USER')")
    public String securedEndpoint(HttpServletRequest request, @AuthenticationPrincipal PreAuthenticatedAuthenticationToken authenticationToken) {
        // 从请求属性中获取证书
        X509Certificate[] certificates = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
        if (certificates != null && certificates.length > 0) {
            X509Certificate clientCertificate = certificates[0];
            // 可以从 clientCertificate 中获取证书信息，例如主题、颁发者等
            String subject = clientCertificate.getSubjectX500Principal().getName();
            String issuer = clientCertificate.getIssuerX500Principal().getName();
            // 处理逻辑
            return "Secured Endpoint. Client Subject: " + subject + ", Issuer: " + issuer;
        } else {
            // 证书不存在或获取失败
            return "Failed to retrieve client certificate.";
        }
    }

    @CrossOrigin
    @ApiOperation(value = "add No Login Required")
    @PostMapping("/addNoLoginRequiredNew")
    public Response<String> addNoLoginRequiredNew(@RequestBody NoLoginRequiredDTO noLoginRequiredDTO, HttpServletRequest request) {
        return Response.success(accountService.addNoLoginRequiredNew(noLoginRequiredDTO, request));
    }

    @CrossOrigin
    @ApiOperation(value = "add No Login Required")
    @PostMapping("/deleteNoLoginRequiredNew")
    public Response<Boolean> deleteNoLoginRequiredNew(@RequestBody NoLoginRequiredDTO noLoginRequiredDTO, HttpServletRequest request) {
        return Response.success(accountService.deleteNoLoginRequiredNew(noLoginRequiredDTO, request));
    }

    @Value("${redirect_url}")
    private String REDIRECT_URL;
    @CrossOrigin
    @ApiOperation(value = "add No Login Required")
    @PostMapping("/getRedirectUrl")
    public Response<String> getRedirectUrl() {
        return Response.success(REDIRECT_URL);
    }

    @CrossOrigin
    @ApiOperation(value = "updateNoLoginRequiredNew")
    @PostMapping("/updateNoLoginRequiredNew")
    public Response<String> updateNoLoginRequiredNew(@RequestBody NoLoginRequiredDTO noLoginRequiredDTO, HttpServletRequest request) {
        return Response.success(accountService.updateNoLoginRequiredNew(noLoginRequiredDTO, request));
    }

    @CrossOrigin
    @GetMapping("/auth/google_callback")
    public Response<String> googleCallback(@RequestParam("code") String code, HttpSession session) {
        return Response.success(accountService.googleCallback(code, session));
    }
    @CrossOrigin
    @GetMapping("/parseGoogleCredential")
    public Response<AccountLoginVO> parseGoogleCredential(@RequestParam("credential") String credential, @RequestParam("type") Integer type) {
        return Response.success(accountService.parseGoogleCredential(credential, type));
    }

    @CrossOrigin
    @GetMapping("/parseWeChatCode")
    public Response<AccountLoginVO> parseWeChatCode(@RequestParam("code") String code, @RequestParam("type") Integer type) {
        return Response.success(accountService.parseWeChatCode(code, type));
    }

    @ApiOperation(value = "接收Design结果")
    @PostMapping("/receiveDesignResults")
    @CrossOrigin
    public Response<Boolean> receiveDesignResults(@Valid @RequestBody JSONObject responseObject) {
        return Response.success(designService.receiveDesignResults(responseObject));
    }

    @ApiOperation(value = "接收Design入参")
    @PostMapping("/receiveDesignParams")
    @CrossOrigin
    public Response<Boolean> receiveDesignParams(@Valid @RequestBody ReceiveDesignParam receiveDesignParam) {
        return Response.success(designService.receiveDesignParams(receiveDesignParam));
    }

    @ApiOperation(value = "刷新minio预签名地址")
    @GetMapping("/refreshMinioUrl")
    public Response<String> refreshMinioUrl(@RequestParam("path") String path){
        return Response.success(minioUtil.getPreSignedUrl(path, CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
    }
}
