package com.fdkankan.scene.factory.handler;

import cn.hutool.core.util.StrUtil;
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.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>
 * logo图片保存业务处理器
 * </p>
 *
 * @author dengsixing
 * @since 2022/1/20
 **/
@Component
public class FloorLogoHandler implements ISaveUploadHandler {

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

    @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 floorLogo = fileInfoJson.getString("floorLogo");
        //如果传过来的文件路径是空，则置为系统默认
        floorLogo = StrUtil.isBlank(floorLogo) ? "0" : floorLogo;
        Integer floorLogoSize = fileInfoJson.getInteger("floorLogoSize");

        SceneEditInfo sceneEditInfoDb = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
        if(Objects.nonNull(sceneEditInfoDb)){
            sceneEditInfoService.update(new LambdaUpdateWrapper<SceneEditInfo>()
                    .set(SceneEditInfo::getFloorLogo, floorLogo)
                    .set(SceneEditInfo::getFloorLogoSize, floorLogoSize)
                    .eq(SceneEditInfo::getId, sceneEditInfoDb.getId()));
        }else{
            sceneEditInfoDb = new SceneEditInfo();
            sceneEditInfoDb.setScenePlusId(scenePlus.getId());
            sceneEditInfoDb.setFloorLogo(floorLogo);
            sceneEditInfoDb.setFloorLogoSize(floorLogoSize);
            sceneEditInfoService.save(sceneEditInfoDb);
        }


        return ResultData.ok();
    }
}
