package cn.sikey.mcdisk.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.sikey.framework.common.exception.ServiceException;
import cn.sikey.mcdisk.controller.app.wristwatch.vo.DeleteContentsReqVO;
import cn.sikey.mcdisk.controller.app.wristwatch.vo.GetFileUploadURLReqVO;
import cn.sikey.mcdisk.enums.ApiEndpointsEnum;
import cn.sikey.mcdisk.enums.CatalogTypeEnum;
import cn.sikey.mcdisk.enums.PhotoThemeEnum;
import cn.sikey.mcdisk.pojo.McdiskResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

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

    /**
     * 创建家庭云
     *
     * @param cloudName   家庭云名称
     * @param accountType 用户类型
     * @param ticket      ticket
     * @param accessToken accessToken
     * @return
     */
    @Override
    public McdiskResult createFamilyCloud(String cloudName, Integer accountType, String ticket, String accessToken) {

        // 校验家庭云名称
        validateCloudNameUniqueness(cloudName, accountType, ticket, accessToken);

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

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

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

    /**
     * 创建家庭云相册
     *
     * @param cloudID     家庭云ID
     * @param theme       相册主题
     * @param ticket      ticket
     * @param accessToken accessToken
     * @return
     */
    @Override
    public McdiskResult createCloudPhoto(String cloudID, Integer theme, String photoName, String ticket, String accessToken) {

        // 校验家庭云下的相册唯一性
        validateCloudPhotoNameUniqueness(photoName, cloudID, ticket, accessToken);

        // 准备请求参数
        String apiUrl = mcdiskConfig.getPath() + ApiEndpointsEnum.CREATE_CLOUD_PHOTO.getPath();
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("photoName", photoName);
        jsonObject.set("cloudID", cloudID);
        if (Objects.nonNull(theme) && theme.intValue() == PhotoThemeEnum.FAMILY_PHOTO_ALBUM.getValue()) {
            // 当theme为1：亲子相册时 必传
            jsonObject.set("themeDate", DateUtil.formatDate(DateUtil.date()));
        }
        jsonObject.set("theme", theme);
        String jsonBody = jsonObject.toString();

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

        // 发送请求
        McdiskResult mcdiskResult = getMcdiskResult(apiUrl, jsonBody, headers);
        log.info("[创建家庭云相册]返回数据：{}", mcdiskResult);
        return mcdiskResult;
    }

    /**
     * 上传文件到家庭云
     *
     * @param getFileUploadURLReqVO 上传文件到家庭云
     * @param accessToken           accessToken
     * @return
     */
    @Override
    public McdiskResult getFileUploadURL(GetFileUploadURLReqVO getFileUploadURLReqVO, String accessToken) {
        // 准备请求参数
        String apiUrl = mcdiskConfig.getPath() + ApiEndpointsEnum.GET_FILE_UPLOAD_URL.getPath();

        boolean catalogTypeFlag = false;
        if (getFileUploadURLReqVO.getCatalogType().intValue() != CatalogTypeEnum.AVATAR_DIRECTORY.getValue()) {
            Optional.ofNullable(getFileUploadURLReqVO.getCloudType()).orElseThrow(() -> new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, "云类型是空"));
            if (StringUtils.isBlank(getFileUploadURLReqVO.getCloudID())) {
                throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, "家庭云ID是空");
            }

            catalogTypeFlag = true;
        }

        // 创建根 JSON 对象
        JSONObject jsonObject = new JSONObject();

        // 添加 commonAccountInfo 对象
        JSONObject commonAccountInfo = new JSONObject();
        commonAccountInfo.set("accountType", getFileUploadURLReqVO.getCommonAccountInfo().getAccountType());
        jsonObject.set("commonAccountInfo", commonAccountInfo);

        jsonObject.set("path", getFileUploadURLReqVO.getPath());

        if (catalogTypeFlag) {
            jsonObject.set("cloudID", getFileUploadURLReqVO.getCloudID());
            jsonObject.set("cloudType", getFileUploadURLReqVO.getCloudType());
        }

        jsonObject.set("catalogType", getFileUploadURLReqVO.getCatalogType());
        jsonObject.set("fileCount", getFileUploadURLReqVO.getFileCount());
        jsonObject.set("totalSize", getFileUploadURLReqVO.getTotalSize());

        List<GetFileUploadURLReqVO.UploadContent> uploadContentList = getFileUploadURLReqVO.getUploadContentList();

        JSONArray jsonArray = new JSONArray();
        uploadContentList.forEach(uploadContent -> {
            JSONObject js = new JSONObject();
            js.set("comlexFlag", uploadContent.getComlexFlag());
            js.set("contentDesc", uploadContent.getContentDesc());
            js.set("contentName", uploadContent.getContentName());
            js.set("contentSize", uploadContent.getContentSize());
            js.set("fileEtag", uploadContent.getFileEtag());
            js.set("fileVersion", uploadContent.getFileVersion());

            if (Objects.nonNull(uploadContent.getManualRename())) {
                js.set("manualRename", uploadContent.getManualRename());

            } else if (StringUtils.isNotBlank(uploadContent.getSeqNo())) {
                js.set("seqNo", uploadContent.getSeqNo());
            }

            jsonArray.add(js);
        });

        jsonObject.set("uploadContentList", jsonArray);

        String jsonBody = jsonObject.toString();

        // 准备请求头
        Map<String, String> headers = getHeaders(getFileUploadURLReqVO.getTicket(),accessToken);

        // 发送请求
        McdiskResult mcdiskResult = getMcdiskResult(apiUrl, jsonBody, headers);
        log.info("[上传文件到家庭云]返回数据：{}", mcdiskResult);
        return mcdiskResult;
    }

    /**
     * 删除家庭云文件
     *
     * @param deleteContentsReqVO 家庭云文件
     * @param accessToken           accessToken
     * @return
     */
    @Override
    public McdiskResult deleteContents(DeleteContentsReqVO deleteContentsReqVO, String accessToken) {
        boolean catalogTypeFlag = false;
        if (deleteContentsReqVO.getCatalogType().intValue() != CatalogTypeEnum.AVATAR_DIRECTORY.getValue()) {
            Optional.ofNullable(deleteContentsReqVO.getCloudType()).orElseThrow(() -> new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, "云类型是空"));
            if (StringUtils.isBlank(deleteContentsReqVO.getCloudID())) {
                throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, "家庭云ID是空");
            }

            catalogTypeFlag = true;
        }

        // 准备请求参数
        String apiUrl = mcdiskConfig.getPath() + ApiEndpointsEnum.DELETE_CONTENTS.getPath();
        JSONObject jsonObject = new JSONObject();
        JSONObject accountType = new JSONObject();
        accountType.set("accountType", deleteContentsReqVO.getCommonAccountInfo().getAccountType());
        jsonObject.set("commonAccountInfo", accountType);
        jsonObject.set("contentIDList", deleteContentsReqVO.getContentIDList());
        jsonObject.set("path", deleteContentsReqVO.getPath());
        jsonObject.set("catalogType", deleteContentsReqVO.getCatalogType());

        if (catalogTypeFlag) {
            jsonObject.set("cloudID", deleteContentsReqVO.getCloudID());
            jsonObject.set("cloudType", deleteContentsReqVO.getCloudType());
        }

        String jsonBody = jsonObject.toString();

        // 准备请求头
        Map<String, String> headers = getHeaders(deleteContentsReqVO.getTicket(),accessToken);

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

}
