package cn.sikey.mcdisk.service;

import cn.hutool.json.JSONObject;
import cn.sikey.framework.common.exception.ServiceException;
import cn.sikey.mcdisk.controller.app.familycloud.vo.AppOauthReqVO;
import cn.sikey.mcdisk.controller.app.familycloud.vo.ConfirmInvitationReqVO;
import cn.sikey.mcdisk.controller.app.familycloud.vo.InviteFamilyMemberRespVO;
import cn.sikey.mcdisk.controller.app.familycloud.vo.QueryUserOauthRespVO;
import cn.sikey.mcdisk.controller.app.wristwatch.vo.AuthorizeRespVO;
import cn.sikey.mcdisk.dal.dataobject.InviteFamilyMemberDO;
import cn.sikey.mcdisk.enums.ApiEndpointsEnum;
import cn.sikey.mcdisk.enums.ChannelTypeEnum;
import cn.sikey.mcdisk.enums.CodeStatusEnum;
import cn.sikey.mcdisk.enums.IsAuthorizeEnum;
import cn.sikey.mcdisk.pojo.McdiskResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;

/**
 * @Author: nelson
 * @Date: 2025/5/29
 * @Description: 家庭云
 */
@Service
@Slf4j
public class AppFamilyCloudServiceImpl extends AbstractMcdiskService implements AppFamilyCloudService {

    @Resource
    private AuthorizeService authorizeService;

    /**
     * 确认邀请
     *
     * @param confirmInvitationReqVO 确认邀请
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public QueryUserOauthRespVO confirmInvitation(ConfirmInvitationReqVO confirmInvitationReqVO) {
        String ticket = confirmInvitationReqVO.getTicket();
        String userId = confirmInvitationReqVO.getUserId();

        // 校验app认证
        validateInviteFamilyMember(userId, ticket);

        // 准备请求参数
        String apiUrl = mcdiskConfig.getPath() + ApiEndpointsEnum.CONFIRM_INVITATION.getPath();
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("invitationCode", confirmInvitationReqVO.getInvitationCode());
        String jsonBody = jsonObject.toString();

        InviteFamilyMemberDO inviteFamilyMemberDO = new InviteFamilyMemberDO();
        inviteFamilyMemberDO.setDeviceId(ticket);
        inviteFamilyMemberDO.setUserId(userId);
        inviteFamilyMemberDO.setCreator(userId);
        inviteFamilyMemberDO.setUpdater(userId);
        inviteFamilyMemberService.saveInviteFamilyMember(inviteFamilyMemberDO);

        // 准备请求头
        Map<String, String> headers = getHeaders(userId, confirmInvitationReqVO.getAccessToken());

        // 发送请求
        McdiskResult mcdiskResult = getMcdiskResult(apiUrl, jsonBody, headers);

        log.info("[确认邀请]返回数据：{}", mcdiskResult);

        // 设备是否认证
        AuthorizeRespVO authorizeRespVO = authorizeService.queryOauth(ticket);
        if (Objects.isNull(authorizeRespVO)) {
            throw new ServiceException(CodeStatusEnum.NOT_ACTIVATED.getCode(), CodeStatusEnum.NOT_ACTIVATED.getDescription());
        }

        QueryUserOauthRespVO queryUserOauthRespVO = new QueryUserOauthRespVO();
        queryUserOauthRespVO.setTicket(ticket);
        queryUserOauthRespVO.setCloudId(authorizeRespVO.getCloudId());
        queryUserOauthRespVO.setPhotoId(authorizeRespVO.getPhotoId());
        return queryUserOauthRespVO;
    }

    /**
     * app认证
     *
     * @param appOauthReqVO app认证
     * @return
     */
    @Override
    public McdiskResult oauth(AppOauthReqVO appOauthReqVO) {
        String ticket = appOauthReqVO.getTicket();
        String userId = appOauthReqVO.getUserId();

        // 校验app认证
        validateInviteFamilyMember(userId, ticket);

        //  认证授权
        AuthorizeRespVO authorizeRespVO = authorizeService.queryOauth(ticket);

        return inviteFamilyMember(authorizeRespVO.getCloudId(), String.valueOf(ChannelTypeEnum.WE_CHAT.getValue()), ticket, authorizeRespVO.getAccessToken());
    }

    /**
     * 查询用户认证
     *
     * @param appOauthReqVO 查询用户认证
     * @return
     */
    @Override
    public QueryUserOauthRespVO queryUserOauth(AppOauthReqVO appOauthReqVO) {
        String ticket = appOauthReqVO.getTicket();
        // 设备是否认证
        AuthorizeRespVO authorizeRespVO = authorizeService.queryOauth(ticket);
        if (Objects.isNull(authorizeRespVO)) {
            throw new ServiceException(CodeStatusEnum.NOT_ACTIVATED.getCode(), CodeStatusEnum.NOT_ACTIVATED.getDescription());
        }

        // 用户是否认证
        InviteFamilyMemberRespVO inviteFamilyMemberRespVO = inviteFamilyMemberService.queryAppOauth(appOauthReqVO.getUserId(), appOauthReqVO.getTicket());
        if (Objects.isNull(inviteFamilyMemberRespVO)) {
            throw new ServiceException(CodeStatusEnum.USER_HAS_NOT_BEEN_AUTHENTICATED.getCode(), CodeStatusEnum.USER_HAS_NOT_BEEN_AUTHENTICATED.getDescription());
        }

        QueryUserOauthRespVO queryUserOauthRespVO = new QueryUserOauthRespVO();
        queryUserOauthRespVO.setTicket(authorizeRespVO.getTicket());
        queryUserOauthRespVO.setCloudId(authorizeRespVO.getCloudId());
        queryUserOauthRespVO.setPhotoId(authorizeRespVO.getPhotoId());
        return queryUserOauthRespVO;
    }

}
