
package com.tmerclub.cloud.biz.controller.multishop;

import com.tmerclub.cloud.biz.constant.FileType;
import com.tmerclub.cloud.biz.dto.AttachFileDTO;
import com.tmerclub.cloud.biz.model.AttachFile;
import com.tmerclub.cloud.biz.service.AttachFileService;
import com.tmerclub.cloud.biz.vo.AttachFileVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Author lth
 * @Date 2021/6/1 15:20
 */
@RestController("multishopAttachFileController")
@RequestMapping("/m/attachFile")
@Tag(name = "multishop-上传文件记录表")
public class AttachFileController {

    @Autowired
    private AttachFileService attachFileService;


    @DeleteMapping("/deleteByIds")
    @Operation(summary = "根据文件id列表批量删除文件记录", description = "根据文件id列表批量删除文件记录")
    public ServerResponseEntity<Void> deleteByIds(@RequestBody List<Long> ids) {
        Long shopId = AuthUserContext.get().getTenantId();
        attachFileService.deleteByIdsAndShopId(ids, shopId);
        return ServerResponseEntity.success();
    }

    @PutMapping("/batchMove")
    @Operation(summary = "根据文件id列表与分组id批量移动文件", description = "根据文件id列表与分组id批量移动文件")
    public ServerResponseEntity<Void> batchMove(@RequestBody List<Long> ids, @RequestParam(value = "groupId", required = false, defaultValue = "") Long groupId) {
        Long shopId = AuthUserContext.get().getTenantId();
        Integer sysType = AuthUserContext.get().getSysType();
        attachFileService.batchMoveByShopIdAndIdsAndGroupId(shopId, ids, groupId, sysType);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getFileById")
    @Operation(summary = "根据文件id获取文件信息")
    public ServerResponseEntity<AttachFileVO> getFileById(Long fileId) {
        AttachFileVO attachFileVO = attachFileService.getById(fileId);
        Long shopId = AuthUserContext.get().getTenantId();
        if (!Objects.equals(shopId, attachFileVO.getShopId())) {
            throw new LuckException("无法查看非本店铺的文件");
        }
        return ServerResponseEntity.success(attachFileVO);
    }

    @PostMapping("/savePdfFile")
    @Operation(summary = "保存商家发票")
    public ServerResponseEntity<AttachFileVO> savePdfFile(@RequestBody AttachFileDTO attachFileDTO) {
        AttachFile attachFile = BeanUtil.map(attachFileDTO, AttachFile.class);
        attachFile.setType(FileType.FILE.value());
        attachFile.setShopId(AuthUserContext.get().getTenantId());
        attachFileService.saveFile(attachFile);
        return ServerResponseEntity.success(attachFileService.getById(attachFile.getFileId()));
    }

}
