package com.wteam.controller.passport;

import cn.hutool.core.text.CharSequenceUtil;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wteam.framework.common.enums.ResultCode;
import com.wteam.framework.common.enums.ResultUtil;

import com.wteam.framework.common.exception.ServiceException;
import com.wteam.framework.common.mybatis.util.PageUtil;
import com.wteam.framework.common.security.AuthUser;
import com.wteam.framework.common.security.context.UserContext;
import com.wteam.framework.common.utils.CommonUtil;
import com.wteam.framework.common.vo.PageVO;
import com.wteam.framework.common.vo.ResultMessage;
import com.wteam.framework.common.vo.SearchVO;
import com.wteam.framework.modules.file.entity.dos.File;
import com.wteam.framework.modules.file.plugin.FilePluginFactory;
import com.wteam.framework.modules.file.service.FileService;
import com.wteam.framework.modules.member.entity.dos.Member;
import com.wteam.framework.modules.member.service.MemberService;
import com.wteam.framework.modules.system.entity.dos.Setting;
import com.wteam.framework.modules.system.entity.enums.SettingEnum;
import com.wteam.framework.modules.system.service.SettingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Objects;

/**
 * 文件上传接口
 *
 * @author Chopper
 * @since 2020/11/26 15:41
 */
@Slf4j
@RestController
@Tag(name = "文件")
@RequestMapping("/common/file")
public class FileController {

    @Autowired
    private FileService fileService;
    @Autowired
    private SettingService settingService;
    @Autowired
    private FilePluginFactory filePluginFactory;

    @Autowired
    private MemberService memberService;


    @PutMapping
    @Operation(summary = "修改")
    public ResultMessage update(@RequestBody File entity) {
        ///处理过了
//        if (!("0").equals(entity.getState())) {
//            entity.setState("0");
//            return fileService.updateById(entity) ? ResultUtil.success() : ResultUtil.error(ResultCode.ERROR);
//        }
        return fileService.updateById(entity) ? ResultUtil.success() : ResultUtil.error(ResultCode.ERROR);
    }

    @GetMapping("page")
    @Operation(summary = "分页")
    public ResultMessage<IPage<File>> page(File entity,
                                           SearchVO searchVo,
                                           PageVO page) {

        QueryWrapper<File> wrapper = PageUtil.initWrapper(entity);
        if (ObjectUtil.isNotNull(entity.getName())) {
            wrapper.like("name", entity.getName());
        }
        wrapper.orderByDesc("create_time");
        IPage<File> data = fileService.page(PageUtil.initPage(page), wrapper);
        return ResultUtil.data(data);
    }


    @PostMapping("saveContent")
    public ResultMessage<Object> upload(@RequestBody File file) {

        AuthUser currentUser = UserContext.getCurrentUser();
        Member member = memberService.query().eq("id", currentUser.getId()).one();
        file.setOwnerId(member.getId());
        return fileService.save(file) ? ResultUtil.success() : ResultUtil.error(ResultCode.PARAMS_ERROR);

    }

    @GetMapping("/get/{id}")
    @Operation(summary = "信息")
    public ResultMessage get(@PathVariable("id") String id) {
        File data = fileService.getById(id);
        return ResultUtil.data(data);
    }


    @PostMapping("upload")
    public ResultMessage upload(MultipartFile file) {
        Setting setting = settingService.get(SettingEnum.OSS_SETTING.name());
        if (setting == null || CharSequenceUtil.isBlank(setting.getSettingValue())) {
            throw new ServiceException(ResultCode.OSS_NOT_EXIST);
        }
        String result = null;
        String fileKey = CommonUtil.rename(Objects.requireNonNull(file.getOriginalFilename()));
        File newFile = new File();
        try {
            InputStream inputStream = file.getInputStream();
            //上传至第三方云服务或服务器
            result = filePluginFactory.filePlugin().inputStreamUpload(inputStream, fileKey);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new ServiceException(ResultCode.OSS_EXCEPTION_ERROR);
        }

        return ResultUtil.data(result);
    }


    @PostMapping("uploadContent")
    public ResultMessage uploadContent(MultipartFile file) {
        AuthUser authUser = UserContext.getCurrentUser();
        String username = authUser.getUsername();
        //如果用户未登录，则无法上传图片
        if (null == authUser) {
            throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
        }
        if (null == file) {
            throw new ServiceException(ResultCode.FILE_NOT_EXIST_ERROR);
        }
        Setting setting = settingService.get(SettingEnum.OSS_SETTING.name());
        if (null == setting || CharSequenceUtil.isBlank(setting.getSettingValue())) {
            throw new ServiceException(ResultCode.OSS_NOT_EXIST);
        }

        String result = null;
        String fileKey = CommonUtil.rename(Objects.requireNonNull(file.getOriginalFilename()));
        File newFile = new File();
        try {
            InputStream inputStream = file.getInputStream();
            //上传至第三方云服务或服务器
            result = filePluginFactory.filePlugin().inputStreamUpload(inputStream, fileKey);
            newFile.setName(file.getOriginalFilename());
            newFile.setFileSize(file.getSize());
            newFile.setFileType(file.getContentType());
            newFile.setFileKey(fileKey);
            newFile.setUrl(result);
            newFile.setCreateBy(authUser.getUsername());
            newFile.setOwnerId(authUser.getId());
            newFile.setUrl(result);
//            newFile.setOwnerName(username);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new ServiceException(ResultCode.OSS_EXCEPTION_ERROR);
        }

        return ResultUtil.data(newFile);
    }


}
