package com.fdkankan.scene.factory.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fdkankan.common.constant.ConstantFilePath;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.UploadFilePath;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.fyun.oss.UploadToOssUtil;
import com.fdkankan.scene.entity.SceneEditInfo;
import com.fdkankan.scene.entity.ScenePlus;
import com.fdkankan.scene.entity.ScenePlusExt;
import com.fdkankan.scene.entity.ScenePro;
import com.fdkankan.scene.entity.SceneProExt;
import com.fdkankan.scene.service.ISceneEditInfoService;
import com.fdkankan.scene.service.IScenePlusExtService;
import com.fdkankan.scene.service.IScenePlusService;
import com.fdkankan.scene.service.ISceneProExtService;
import com.fdkankan.scene.service.ISceneProService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * logo图片保存业务处理器
 * </p>
 *
 * @author dengsixing
 * @since 2022/1/20
 **/
@Component
public class FloorPlanHandler implements ISaveUploadHandler {

    @Autowired
    private ISceneEditInfoService sceneEditInfoService;
    @Autowired
    private ISceneProService sceneProService;
    @Autowired
    private ISceneProExtService sceneProExtService;
    @Autowired
    UploadToOssUtil uploadToOssUtil;
    @Autowired
    IScenePlusService scenePlusService;
    @Autowired
    IScenePlusExtService scenePlusExtService;

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

//        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 cadInfo = fileInfoJson.getString("cadInfo");
        String floorJsonData = fileInfoJson.getString("floorJsonData");

//        String filePaths = fileInfoJson.getString("filePaths");
//        JSONArray filePathsArrs = JSONUtil.parseArray(filePaths);
//        List<String> filePathsList = filePathsArrs.toList(String.class);
//        StringBuilder filePathBuilder = new StringBuilder();
//        filePathsList.parallelStream().forEach(path -> {
//            filePathBuilder.append(",").append(path);
//        });


        //写入数据库
        SceneEditInfo sceneEditInfoDb = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
        if(Objects.nonNull(sceneEditInfoDb)){
            sceneEditInfoService.update(new LambdaUpdateWrapper<SceneEditInfo>()
                    .setSql("version=version+"+1)
//                    .set(SceneEditInfo::getFloorPlanPath, filePathBuilder.substring(1))
//                    .set(SceneEditInfo::getCadInfo, cadInfo)
                    .eq(SceneEditInfo::getId, sceneEditInfoDb.getId()));
        }else{
            sceneEditInfoDb = new SceneEditInfo();
            sceneEditInfoDb.setScenePlusId(scenePlus.getId());
//            sceneEditInfoDb.setFloorPlanPath(filePaths);
//            sceneEditInfoDb.setCadInfo(cadInfo);
            sceneEditInfoService.save(sceneEditInfoDb);
        }

        //上传houst_floor.json文件
        String localDataPath = String.format(ConstantFilePath.DATABUFFER_FORMAT, num);
        String dataPath = String.format(UploadFilePath.DATA_VIEW_PATH, num);

        // TODO: 2022/1/27 旧版本目录，待删除
        String oldDataPath = String.format(ConstantFilePath.DATA_PATH_FORMAT, num);

        if(StrUtil.isEmpty(floorJsonData)){
//            SceneProExt sceneProExt = sceneProExtService.findBySceneProId(scenePro.getId());
            ScenePlusExt scenePlusExt= scenePlusExtService
                .getScenePlusExtByPlusId(scenePlus.getId());
            // TODO: 2022/1/27 老版本数据目录挂在nas，新版本目前流程尚不清楚，先暂时按照老版本写，以后再调整
            FileUtils.copyFile(scenePlusExt.getDataSource() + "/results/floor.json", localDataPath + "houst_floor.json", true);
            uploadToOssUtil.upload(localDataPath + "houst_floor.json", dataPath + "houst_floor.json");

            // TODO: 2022/1/27 老版本上传目录 待删除
            uploadToOssUtil.upload(localDataPath + "houst_floor.json", oldDataPath + "houst_floor.json");

            String result = FileUtils.readFile(localDataPath + "houst_floor.json");
            return ResultData.ok(result);
        }

        FileUtils.writeFile(localDataPath + "houst_floor.json", floorJsonData);
        uploadToOssUtil.upload(localDataPath + "houst_floor.json", dataPath + "houst_floor.json");

        // TODO: 2022/1/27 老版本上传目录 待删除
        uploadToOssUtil.upload(localDataPath + "houst_floor.json", oldDataPath + "houst_floor.json");

        return ResultData.ok();
    }

}
