package com.sptg.video.cloud.biz.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.video.cloud.api.dto.FileInfoDto;
import com.sptg.video.cloud.api.entity.FileInfo;
import com.sptg.video.cloud.api.entity.SysParams;
import com.sptg.video.cloud.api.feigns.FileInfoFeign;
import com.sptg.video.cloud.biz.service.FileInfoServiceInterface;
import com.sptg.video.cloud.biz.service.VCSysParamsServiceInterface;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zwx
 * @create 2020/10/18 21:12
 */
@RequiredArgsConstructor
@RestController
@Slf4j
public class FileInfoController implements FileInfoFeign {

    private final FileInfoServiceInterface fileInfoServiceInterface;
    private final VCSysParamsServiceInterface sysParamsServiceInterface;

    @Override
    @PostMapping(value = "/vcFileInfo/showFileInfoList")
    public ResultBean<Page<FileInfo>> showFileInfoList(@RequestBody FileInfoDto fileInfoDto) {
        List<FileInfo> fileInfoList = this.fileInfoServiceInterface.showFileInfoList(fileInfoDto);
        ResultBean<Page<FileInfo>> pageResultBean = new ResultBean<>();
        Page<FileInfo> page = new Page<>();
        page.setRecords(fileInfoList);
        pageResultBean.setData(page);
        return pageResultBean;
    }

    @Override
    @GetMapping(value = "/vcFileInfo/findFileInfoById/{id}")
    public FileInfo findFileInfoById(@PathVariable(value = "id") Long id) {
        return this.fileInfoServiceInterface.selectById(id);
    }

    @Override
    @PostMapping(value = "/vcFileInfo/sync/list")
    public ResultBean<Boolean> syncFileInfoList(@RequestBody FileInfoDto fileInfoDto) {
        SysParams sysParams = this.sysParamsServiceInterface.findSysParamsById(1L);
        List<FileInfo> fileInfoList = this.fileInfoServiceInterface.syncFileInfoList(sysParams, fileInfoDto);
        if (fileInfoList != null && fileInfoList.size() > 0) {
            fileInfoList.forEach(fileInfo -> {fileInfo.setDeviceNum(fileInfoDto.getDeviceNum());});
            List<FileInfo> oldFileList = null;
            oldFileList = this.fileInfoServiceInterface.findFileInfoByDeviceNum(fileInfoDto.getDeviceNum());
            if (oldFileList == null) {
                //添加最新的
                this.fileInfoServiceInterface.insertBatch(fileInfoList);
            }else {
                List<Long> oldIds = oldFileList.stream().map(FileInfo::getId).collect(Collectors.toList());
                //删除原有的
                boolean b = this.fileInfoServiceInterface.deleteBatchIds(oldIds);
                if(b){
                    //添加最新的
                    this.fileInfoServiceInterface.insertBatch(fileInfoList);
                }
            }
        }
        return new ResultBean<>(ResultEnum.SUCCESS, true);
    }
}
