package cn.sikey.mcdisk.service;

import cn.hutool.json.JSONObject;
import cn.sikey.framework.common.exception.ServiceException;
import cn.sikey.framework.common.pojo.CommonResult;
import cn.sikey.mcdisk.controller.app.familycloud.vo.*;
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.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.*;

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

    @Resource
    private AuthorizeService authorizeService;

    @Resource
    private AuthorizePhotoService authorizePhotoService;

    /**
     * 确认邀请
     *
     * @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;
    }

    /**
     * 删除家庭云成员
     *
     * @param req 请求参数
     * @return
     */
    @Override
    public CommonResult<Void> delFamilyCloudMember(DelFamilyCloudMemberReqVO req) {
        String ticket = req.getTicket();
        // 设备是否认证
        AuthorizeRespVO authorizeRespVO = authorizeService.queryOauth(ticket);
        if (Objects.isNull(authorizeRespVO)) {
            throw new ServiceException(CodeStatusEnum.NOT_ACTIVATED.getCode(), CodeStatusEnum.NOT_ACTIVATED.getDescription());
        }
        Map<String, String> fFamilyMemberMap = new HashMap<>();
        List<String> userIdList = new ArrayList<>();
        for (DelFamilyCloudMemberReqVO.FamilyMember item: req.getMemberList()) {
            userIdList.add(item.getUserId());
            fFamilyMemberMap.put(item.getUserId(), item.getPhoneNumber());
        }
        // 用户是否认证
        InviteFamilyMemberListRespVO inviteFamilyMemberListRespVO = inviteFamilyMemberService.queryAppOauthList(userIdList, ticket);
        if (Objects.isNull(inviteFamilyMemberListRespVO)) {
            throw new ServiceException(CodeStatusEnum.USER_HAS_NOT_BEEN_AUTHENTICATED.getCode(), CodeStatusEnum.USER_HAS_NOT_BEEN_AUTHENTICATED.getDescription());
        }

        // 准备请求参数
        String apiUrl = mcdiskConfig.getPath() + ApiEndpointsEnum.DELETE_CLOUD_MEMBER.getPath();

        List<JSONObject> memberAccountInfos = new ArrayList<>();
        for (String userId: inviteFamilyMemberListRespVO.getUserIdList()) {
            if (fFamilyMemberMap.containsKey(userId)) {
                JSONObject memberAccountInfo = new JSONObject();
                memberAccountInfo.set("account", fFamilyMemberMap.get(userId));
                memberAccountInfo.set("accountType", "1");
                memberAccountInfos.add(memberAccountInfo);
            }

        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("cloudID", authorizeRespVO.getCloudId());
        jsonObject.set("memberAccountInfo", memberAccountInfos);
        String jsonBody = jsonObject.toString();

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

        // 发送请求
        McdiskResult mcdiskResult = getMcdiskResult(apiUrl, jsonBody, headers);
        log.info("[删除家庭云成员]返回数据：{}", mcdiskResult);

        if (mcdiskResult.getCode() == 0) {
            if (req.getIsAdmin() == 1) {// 是管理员，则删除二张关系表所有数据
                authorizeService.deleteAuthorize(ticket);
                authorizePhotoService.deleteAuthorizePhoto(ticket);
                inviteFamilyMemberService.deleteInviteFamilyMembers(userIdList, ticket);
            } else if (req.getIsAdmin() == 2) {//非管理员，则删除成员表中的自己
                inviteFamilyMemberService.deleteInviteFamilyMembers(userIdList, ticket);
            }
        }
        return CommonResult.success();
    }

}
