package com.fdkankan.ucenter.controller;


import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.internal.OSSUtils;
import com.fdkankan.common.util.JwtUtil;
import com.fdkankan.fyun.face.FYunFileServiceInterface;
import com.fdkankan.ucenter.common.BaseController;
import com.fdkankan.ucenter.common.DownloadStatusEnum;
import com.fdkankan.ucenter.common.Result;
import com.fdkankan.ucenter.common.constants.ConstantFilePath;
import com.fdkankan.ucenter.common.constants.NacosProperty;
import com.fdkankan.ucenter.common.constants.ResultCode;
import com.fdkankan.ucenter.common.constants.ResultCodeMsg;
import com.fdkankan.ucenter.config.FyunConfig;
import com.fdkankan.ucenter.entity.ScenePlus;
import com.fdkankan.ucenter.entity.User;
import com.fdkankan.ucenter.exception.BusinessException;
import com.fdkankan.ucenter.httpClient.client.FdKKClient;
import com.fdkankan.ucenter.httpClient.param.FdRoomVo;
import com.fdkankan.ucenter.httpClient.param.UploadEditSceneParam;
import com.fdkankan.ucenter.service.*;
import com.fdkankan.ucenter.service.impl.TakeLookService;
import com.fdkankan.ucenter.vo.request.RequestScene;
import com.fdkankan.ucenter.vo.request.SceneParam;
import com.fdkankan.ucenter.vo.response.DownloadProcessVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.language.Nysiis;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 场景表 前端控制器
 * </p>
 *
 * @author
 * @since 2022-07-04
 */
@RestController
@RequestMapping("/ucenter/user/scene")
@Slf4j
public class SceneController extends BaseController {

    @Autowired
    ISceneProService sceneProService;
    @Autowired
    IUserService userService;
    @Autowired
    IDownService downService;
    @Autowired
    ISceneUpgradeToV4Service sceneUpgradeToV4Service;
    @Autowired
    ISceneCooperationService sceneCooperationService;
    @Autowired
    ISceneService sceneService;
    @Autowired
    IScenePlusService scenePlusService;
    @Autowired
    TakeLookService takeLookService;

    @PostMapping("/findSceneNumber")
    public Result findSceneNumber() {
        return Result.success(sceneProService.findSceneNumber(getToken()));
    }

    @PostMapping("/getOldSceneList")
    public Result getOldSceneList(@RequestBody SceneParam param) {
        User user = userService.getByToken(getToken());
        param.setUserId(user.getId());
        return Result.success(sceneService.pageList(param));
    }

    @PostMapping(value = "/list")
    public Result getScenes(@RequestBody RequestScene param) throws Exception {
        return Result.success(sceneProService.getScenes(getUserName(), param));

    }

    @PostMapping("/newList")
    public Result newList(@RequestBody SceneParam param) {
        return Result.success(sceneProService.newList(param, getUserName()));
    }

    @PostMapping("/getOnlySceneList")
    public Result getOnlySceneList(@RequestBody SceneParam param) {
        param.setHasFolder(0);
        JSONObject jsonObject = sceneProService.newList(param, getUserName());
        JSONObject pageInfo = jsonObject.getJSONObject("pageInfo");
        pageInfo.put("endRow", 0);
        pageInfo.put("firstPage", param.getPageNum());
        pageInfo.put("hasNextPage", false);
        pageInfo.put("isLastPage", 0);
        pageInfo.put("size", pageInfo.get("total"));
        Integer pages = pageInfo.getInteger("total") / param.getPageSize();
        pageInfo.put("pages", pageInfo.getInteger("total") % param.getPageSize() == 0 ? pages : pages + 1);
        return Result.success(pageInfo);
    }

    /**
     * 获取场景详情
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public Result getSceneDetail(@RequestBody SceneParam param) throws Exception {
        return Result.success(sceneProService.getSceneDetail(param.getSceneNum()));
    }

    @PostMapping("/copyScene")
    public Result copyScene(@RequestBody SceneParam param) throws Exception {
        sceneProService.copyScene(param.getSceneNum(), getUserName());
        return Result.success();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody SceneParam param) throws Exception {
        sceneProService.delete(param.getSceneNum(), getUserId(), param.getPlatform());
        return Result.success();
    }

    /**
     * 校验该场景有无下载资格
     */
    @PostMapping("/checkDownload")
    public Result checkDownload(@RequestBody SceneParam param) throws Exception {
        return Result.success(downService.checkDownLoad(param.getSceneNum(), param.getIsObj()));
    }

    /**
     * 校验该场景有无下载资格
     *
     * @param param
     * @return
     */
    @PostMapping("/downloadScene")
    public Result downloadScene(@RequestBody SceneParam param) throws Exception {
        return Result.success(downService.down(param.getSceneNum(), getUserName(), param.getIsObj()));
    }

    /**
     * 获取下载进度
     *
     * @param param
     * @return
     */
    @PostMapping("/downloadProcess")
    public Result downloadProcess(@RequestBody SceneParam param) throws Exception {
        User user = getUser();
        DownloadProcessVo downloadProcessVo = downService.downloadProcess(user.getId(), param.getSceneNum(), param.getIsObj());
        if (downloadProcessVo.getStatus() == DownloadStatusEnum.DOWNLOAD_FAILED_CODE) {
            return Result.failure("下载失败！");
        }
        return Result.success(downloadProcessVo);
    }


    /**
     * 检查下载
     * num      场景码
     */
    @GetMapping("/checkDownLoadE57")
    public Result checkDownLoadE57(@RequestParam(required = false) String num,
                                   @RequestParam(required = false) String splitType) {
        return Result.success(downService.checkDownLoadE57(num,splitType, getUserName()));
    }

    /**
     * 下载场景
     * num      场景码
     */
    @GetMapping("/downSceneE57")
    public Result downSceneE57(@RequestParam(required = false) String num,
                               @RequestParam(required = false) String splitType) {
        return Result.success(downService.downE57(num,splitType, getUserName()));
    }

    /**
     * 下载场景进度条
     * num      场景码
     */
    @GetMapping("/downloadProcessE57")
    public Result downloadProcessE57(@RequestParam(required = false) String num,
                                     @RequestParam(required = false) String splitType) {
        return Result.success(downService.downloadProcessE57(num, splitType,getUserName()));
    }


    /**
     * 场景升级V4接口
     */
    @GetMapping("/upgradeToV4")
    public Result upgradeToV4(String num) throws Exception {
        return sceneUpgradeToV4Service.upgrade(num);
    }


    /**
     * 场景升级进度查询接口
     */
    @GetMapping("/getUpgradeToV4Progress")
    public Result getUpgradeToV4Progress(String num) throws Exception {
        return sceneUpgradeToV4Service.getUpgradeToV4Progress(num);
    }

    /**
     * 分页查询存在houseType文件的场景
     */
    @PostMapping("/pageSceneWithHouseType")
    public Result pageSceneWithHouseType(@RequestBody RequestScene param) {
        return scenePlusService.pageSceneWithHouseType(param, this.getToken());
    }

    /**
     * 根据场景码返回ar路径
     */
    @GetMapping("/getArPathByNum")
    public Result getArPathByNum(@RequestParam(value = "num") String num) {
        return scenePlusService.getArPathByNum(num);
    }


    /**
     * 发起带看获取带看房间号
     */
    @GetMapping("/getTakeLookRoomId")
    public Result getTakeLookRoomId(@RequestParam(value = "num") String num) {
        ScenePlus scenePlus = scenePlusService.getByNum(num);
        if (scenePlus == null) {
            throw new BusinessException(ResultCodeMsg.FAILURE_CODE_400002, ResultCodeMsg.FAILURE_MSG_400002);
        }
        if (scenePlus.getSceneStatus() != -2) {
            throw new BusinessException(ResultCodeMsg.FAILURE_CODE_400009, ResultCodeMsg.FAILURE_MSG_400009);
        }
        FdRoomVo fdRoomVo = takeLookService.getRoomIdByNum(num, scenePlus.getTitle(), getToken());
        takeLookService.openRoom(fdRoomVo.getRoomId(), getToken());
        return Result.success(fdRoomVo);
    }

    @GetMapping("/removePortrait")
    public Result removePortrait(@RequestParam(value = "num") String num) {
        sceneProService.removePortrait(num);
        return Result.success();
    }

    @Autowired
    FYunFileServiceInterface fYunFileServiceInterface;
    @Autowired
    FdKKClient fdKKClient;

    @PostMapping("/uploadE57")
    public Result uploadE57(@RequestParam("file") MultipartFile file,
                            @RequestParam(value = "isObj", required = false) Integer isObj,
                            @RequestParam(value = "title", required = false) String title) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!suffix.equals(".e57")) {
            throw new BusinessException(ResultCode.UPLOAD_ERROR2);
        }
        File targetFile = null;
        try {
            String newFileName = UUID.randomUUID().toString().replace("-", "");
            String filePath = ConstantFilePath.MANAGE_PATH + "e57" + File.separator + newFileName + suffix;
            targetFile = new File(filePath);
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);

            fYunFileServiceInterface.uploadFile(filePath, filePath.replace(ConstantFilePath.MANAGE_PATH, "ucenter/"));

            UploadEditSceneParam editSceneParam = new UploadEditSceneParam();
            editSceneParam.setTitle(title);
            editSceneParam.setUserId(getUser().getId());
            editSceneParam.setPath(filePath.replace(ConstantFilePath.MANAGE_PATH, "ucenter/"));
            editSceneParam.setIsObj(isObj);
            editSceneParam.setOtherType("E57_V4");

            JSONObject jsonObject = fdKKClient.reverseScene(editSceneParam);
            Integer code = jsonObject.getInteger("code");
            if (code != 0) {
                log.info("调用失败-toFdCreateScene:{}", jsonObject);
                throw new BusinessException(ResultCode.UPLOAD_ERROR);
            }
        } catch (Exception e) {
            log.info("调用失败-toFdCreateScene:", e);
            throw new BusinessException(ResultCode.UPLOAD_ERROR);
        } finally {
            if (targetFile != null) {
                try {
                    FileUtil.del(targetFile);
                } catch (Exception e) {
                    log.info("删除文件失败:{}", targetFile.getPath());
                }
            }
        }


        return Result.success();
    }

    @Autowired
    FyunConfig fyunConfig;

    @PostMapping("/getUploadUrl")
    public Result getUploadUrl(@RequestParam(value = "fileName", required = false) String fileName) {
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        URL presignedUrl = fyunConfig.getPresignedUrl("ucenter/e57/" + newFileName + suffix);
        HashMap<String, Object> map = new HashMap<>();
        map.put("newFileName", newFileName + suffix);
        map.put("url", presignedUrl.toString());
        return Result.success(map);
    }

    @PostMapping("/relevanceE57")
    public Result relevanceE57(@RequestParam(value = "isObj", required = false) Integer isObj,
                               @RequestParam(value = "title", required = false) String title,
                               @RequestParam(value = "newFileName", required = false) String newFileName) {


        if (StringUtils.isBlank(newFileName)) {
            throw new BusinessException(ResultCode.PARAM_MISS);
        }
        String ossPath = "ucenter/e57/" + newFileName;
        if (!fYunFileServiceInterface.fileExist(ossPath)) {
            throw new BusinessException(ResultCode.UPLOAD_ERROR3);
        }

        UploadEditSceneParam editSceneParam = new UploadEditSceneParam();
        editSceneParam.setTitle(title);
        editSceneParam.setUserId(getUser().getId());
        editSceneParam.setPath("ucenter/e57/" + newFileName);
        editSceneParam.setIsObj(isObj);
        editSceneParam.setOtherType("E57_V4");

        JSONObject jsonObject = fdKKClient.reverseScene(editSceneParam);
        Integer code = jsonObject.getInteger("code");
        if (code != 0) {
            log.info("调用失败-toFdCreateScene:{}", jsonObject);
            throw new BusinessException(ResultCode.UPLOAD_ERROR);
        }
        return Result.success();
    }
}

