package com.jsowell.api.uniapp.customer;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.ImmutableMap;
import com.jsowell.common.UserAgentUtils;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.pile.domain.AuthorizationEventResult;
import com.jsowell.pile.domain.agentDev.CategoryInfo;
import com.jsowell.pile.dto.agentDev.*;
import com.jsowell.pile.vo.agentDev.AuthInfoVO;
import com.jsowell.service.AgentDevService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 代开发小程序Controller
 *
 * @author Lemon
 * @Date 2023/7/27 15:09
 */
@Anonymous
@RestController
@RequestMapping("/agentDev")
public class AgentDevController extends BaseController {

    @Autowired
    private AgentDevService agentDevService;

    /**
     * 授权事件接收URL,验证票据、授权事件
     *
     * @param timestamp
     * @param nonce
     * @param msgSignature
     * @param postData
     * @return
     */
    @PostMapping("/platform/event")
    public ResponseEntity<AuthorizationEventResult> wechatPlatformEvent(@RequestParam("timestamp") String timestamp,
                                                                        @RequestParam("nonce") String nonce,
                                                                        @RequestParam("msg_signature") String msgSignature,
                                                                        @RequestBody String postData) {
        AuthorizationEventResult<String> resultBean = new AuthorizationEventResult<>();
        ResponseEntity<AuthorizationEventResult> responseEntity;
        logger.info("第三方平台授权事件接收URL params:{}", postData);
        try {
            resultBean.setData(agentDevService.parseRequest(timestamp, nonce, msgSignature, postData));
            responseEntity = new ResponseEntity<>(resultBean, HttpStatus.OK);
            logger.info("第三方平台授权事件接收URL success");
        } catch (Exception e) {
            logger.error("第三方平台授权事件接收URL error:{}", e.getMessage(), e);
            AuthorizationEventResult<String> errorResultBean = new AuthorizationEventResult<>();
            errorResultBean.setMsg("第三方平台授权事件接收URL error");
            errorResultBean.setErrorMsg(e.getMessage());
            errorResultBean.setCode(422);
            responseEntity = new ResponseEntity<>(errorResultBean, HttpStatus.UNPROCESSABLE_ENTITY);
        }
        logger.info("第三方平台授权事件接收URL result:{}", resultBean);
        return responseEntity;
    }


    /**
     * 授权回调 URI
     *
     * @param authCode
     * @param expiresIn
     * @return
     */
    @GetMapping("/getAuthCallback")
    public RestApiResponse<?> getAuthCallback(@RequestParam("auth_code") String authCode,
                                              @RequestParam("expires_in") String expiresIn) {
        logger.info("授权回调 URI, auth_code:{}, expires_in:{}", authCode, expiresIn);
        RestApiResponse<?> response = null;
        try {
            agentDevService.getAuthCallback(authCode, expiresIn);
            response = new RestApiResponse<>();
        } catch (Exception e) {
            logger.error("授权回调 URI error, ", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("授权回调 URI result:{}", response);
        return response;
    }


    /**
     * 获取微信第三方平台令牌
     *
     * @param dto
     * @return
     */
    @PostMapping("/getComponentToken")
    public RestApiResponse<?> getComponentToken(@RequestBody GetComponentTokenDTO dto) {
        logger.info("获取第三方平台令牌 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String componentToken = agentDevService.getComponentToken(dto);
            response = new RestApiResponse<>(componentToken);
        } catch (Exception e) {
            logger.error("获取第三方平台令牌 error", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("获取第三方平台令牌 result:{}", response);
        return response;

    }

    /**
     * 获取预授权码
     *
     * @return
     */
    @GetMapping("/getPreAuthorizerCode")
    public RestApiResponse<?> getPreAuthorizerCode() {
        logger.info("微信第三方平台 获取预授权码 start");
        RestApiResponse<?> response = null;
        try {
            String preAuthorizerCode = agentDevService.getPreAuthorizerCode();
            response = new RestApiResponse<>(preAuthorizerCode);
        } catch (Exception e) {
            logger.error("微信第三方平台 获取预授权码 error, ", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("微信第三方平台 获取预授权码 result:{}", response);
        return response;
    }

    /**
     * 拼接授权链接
     *
     * @param dto
     * @return
     */
    @PostMapping("/concatenateAuthLinks")
    public RestApiResponse<?> concatenateAuthLinks(@RequestBody ConcatenateAuthLinkDTO dto) {
        logger.info("第三方平台 拼接授权链接 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String url = agentDevService.concatenateAuthLinks(dto);
            response = new RestApiResponse<>(url);
        } catch (Exception e) {
            logger.error("第三方平台 拼接授权链接 error, ", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("第三方平台 拼接授权链接 result:{}", response);
        return response;
    }


    /**
     * 使用授权码获取授权信息
     *
     * @param authorizationCode
     * @return
     */
    @GetMapping("/getAuthInfo/{authorizationCode}")
    public RestApiResponse<?> getAuthInfo(@PathVariable("authorizationCode") String authorizationCode) {
        logger.info("使用授权码获取授权信息 params:{}", authorizationCode);
        RestApiResponse<?> response = null;
        try {
            AuthInfoVO authInfoVO = agentDevService.getAuthInfoByAuthCode(authorizationCode);
            response = new RestApiResponse<>(authInfoVO);
        } catch (Exception e) {
            logger.error("使用授权码获取授权信息 error,", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("使用授权码获取授权信息 result:{}", response);
        return response;
    }


    /**
     * 提交代码并生成体验版小程序
     *
     * @param dto
     * @return
     */
    @PostMapping("/commitCode")
    public RestApiResponse<?> commitCode(@RequestBody CommitCodeDTO dto) {
        logger.info("提交代码并生成体验版小程序 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String commitResult = agentDevService.commitCode(dto);
            response = new RestApiResponse<>(commitResult);
        } catch (Exception e) {
            logger.error("提交代码并生成体验版小程序 error,", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("提交代码并生成体验版小程序 result:{}", response);
        return response;
    }

    /**
     * 获取类目列表
     *
     * @param authorizerAppid 用户授权的appid
     * @return
     */
    @GetMapping("/getAllCategoryName/{authorizerAppid}")
    public RestApiResponse<?> getAllCategoryName(@PathVariable("authorizerAppid") String authorizerAppid) {
        logger.info("获取类目列表 params:{}", authorizerAppid);
        RestApiResponse<?> response = null;
        try {
            List<CategoryInfo> categoryInfos = agentDevService.getAllCategoryName(authorizerAppid);
            response = new RestApiResponse<>(categoryInfos);
        } catch (Exception e) {
            logger.error("获取类目列表 error,", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("获取类目列表 result:{}", response);
        return response;
    }

    /**
     * 提交代码审核
     *
     * @return
     */
    @PostMapping("/submitAudit")
    public RestApiResponse<?> submitAudit(@RequestBody SubmitAuditDTO dto) {
        logger.info("提交代码审核 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String result = agentDevService.submitAudit(dto);
            response = new RestApiResponse<>(result);
        } catch (Exception e) {
            logger.error("提交代码审核 error,", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("提交代码审核 result:{}", response);
        return response;
    }

    /**
     * 获取审核状态
     *
     * @param dto
     * @return
     */
    @PostMapping("/getAuditStatus")
    public RestApiResponse<?> getAuditStatus(@RequestBody GetAuditStatusDTO dto) {
        logger.info("获取审核状态 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String result = agentDevService.getAuditStatus(dto);
            response = new RestApiResponse<>(result);
        } catch (Exception e) {
            logger.error("获取审核状态 error, ", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("获取审核状态 result:{}", response);
        return response;
    }

    /**
     * 发布已通过审核的小程序
     *
     * @param authorizerAppid
     * @return
     */
    @GetMapping("/releaseProcedure/{authorizerAppid}")
    public RestApiResponse<?> releaseProcedure(@PathVariable("authorizerAppid") String authorizerAppid) {
        logger.info("发布已通过审核的小程序 params:{}", authorizerAppid);
        RestApiResponse<?> response = null;
        try {
            String result = agentDevService.releaseProcedure(authorizerAppid);
            response = new RestApiResponse<>(result);
        } catch (Exception e) {
            logger.error("发布已通过审核的小程序 error, ", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("发布已通过审核的小程序 result:{}", response);
        return response;
    }

    /**
     * 设置小程序用户隐私保护指引
     * @param dto
     * @return
     */
    @PostMapping("/setPrivacySetting")
    public RestApiResponse<?> setPrivacySetting (@RequestBody PrivacySettingDTO dto) {
        logger.info("设置小程序用户隐私保护指引 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String result = agentDevService.setPrivacySetting(dto);
            response = new RestApiResponse<>(result);
        } catch (Exception e) {
            logger.info("设置小程序用户隐私保护指引 error, ", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("设置小程序用户隐私保护指引 result:{}", response);
        return response;
    }

    /**
     * 代开发小程序 微信一键登录
     * @param dto
     * @return
     */
    @PostMapping("/wechatLogin")
    public RestApiResponse<?> wechatLogin(HttpServletRequest request, @RequestBody AgentWechatLoginDTO dto) {
        logger.info("第三方平台微信一键登录 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            // 设置请求来源
            dto.setRequestSource(UserAgentUtils.determineRequestSource(request));
            String memberToken = agentDevService.wechatLogin(dto);
            response = new RestApiResponse<>(ImmutableMap.of("memberToken", memberToken));
        } catch (Exception e) {
            logger.error("第三方平台微信一键登录 error, ", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("第三方平台微信一键登录 result:{}", response);
        return response;
    }
}
