package com.fdkankan.scene.factory.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.scene.entity.SceneEditInfo;
import com.fdkankan.scene.entity.ScenePlus;
import com.fdkankan.scene.entity.ScenePro;
import com.fdkankan.scene.service.ISceneEditInfoService;
import com.fdkankan.scene.service.IScenePlusExtService;
import com.fdkankan.scene.service.IScenePlusService;
import com.fdkankan.scene.service.ISceneProService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 背景音乐保存业务处理器
 * </p>
 *
 * @author dengsixing
 * @since 2022/1/20
 **/
@Component
public class MusicHandler implements ISaveUploadHandler {

    @Autowired
    private ISceneEditInfoService sceneEditInfoService;
    @Autowired
    private ISceneProService sceneProService;
    @Autowired
    IScenePlusService scenePlusService;
    @Autowired
    IScenePlusExtService scenePlusExtService;

    @Override
    public ResultData save(String num, String fileInfo) {

//        ScenePro scenePro = sceneProService.findBySceneNum(num);
        ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
        if(Objects.isNull(scenePlus))
            throw new BusinessException(ErrorCode.FAILURE_CODE_5005);

        JSONObject fileInfoJson = JSON.parseObject(fileInfo);
        String music = fileInfoJson.getString("music");

        SceneEditInfo sceneEditInfoDb = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
        if(Objects.nonNull(sceneEditInfoDb)){
            sceneEditInfoService.update(new LambdaUpdateWrapper<SceneEditInfo>()
                    .set(SceneEditInfo::getMusic, music)
                    .eq(SceneEditInfo::getId, sceneEditInfoDb.getId()));
        }else{
            sceneEditInfoDb = new SceneEditInfo();
            sceneEditInfoDb.setScenePlusId(scenePlus.getId());
            sceneEditInfoDb.setMusic(music);
            sceneEditInfoService.save(sceneEditInfoDb);
        }

        return ResultData.ok();
    }
}
