package com.microservices.zone.resource.domain.vo;

import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.utils.bean.BeanUtils;
import com.microservices.zone.resource.domain.ZoneResource;
import com.microservices.zone.resource.utils.ResourceExtendDataUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * Skill修改输入VO
 */
@Data
@ApiModel("Skill修改输入")
public class AiSkillUpdateVo {

    @ApiModelProperty(value = "资源Id", required = true)
    @NotNull(message = "资源Id不能为空")
    private Long id;

    @ApiModelProperty(value = "Skill名称")
    @Size(max = 100, message = "Skill名称不能超过100个字符")
    private String name;

    @ApiModelProperty(value = "Skill简介")
    @Size(max = 500, message = "Skill简介不能超过500个字符")
    private String summary;

    @ApiModelProperty(value = "Skill文件Id")
    private Long fileId;

    @ApiModelProperty(value = "SKILL.md内容")
    private String skillContent;

    @ApiModelProperty(value = "目录树JSON")
    private String fileTreeJson;

    /**
     * 转换为 ZoneResource（合并 extendData）
     *
     * @param existing 现有资源对象，用于获取原有 extendData
     * @return 合并后的 ZoneResource
     */
    public ZoneResourceUpdateVo toZoneResourceUpdateVo(ZoneResource existing) {
        ZoneResourceUpdateVo target = new ZoneResourceUpdateVo();
        BeanUtils.copyProperties(this, target);
        if (fileId == null) {
            target.setFileIds(existing.getFileIds());
        } else {
            target.setFileIds(String.valueOf(fileId));
        }

        // 获取现有 extendData 或创建新的
        JSONObject extendData = existing.getExtendData();
        if (extendData == null) {
            extendData = new JSONObject();
        }

        // 更新 skillContent
        if (skillContent != null) {
            extendData = ResourceExtendDataUtils.updateSkillContent(extendData, skillContent);
        }

        // 更新 fileTree
        if (fileTreeJson != null) {
            JSONObject fileTreeObj = JSONObject.parseObject(fileTreeJson);
            extendData = ResourceExtendDataUtils.updateSkillFileTree(extendData, fileTreeObj);
        }

        target.setExtendData(extendData.toJSONString());
        return target;
    }
}
