package com.artfess.cqxy.wps.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.context.BaseContext;
import com.artfess.base.model.CommonResult;
import com.artfess.base.util.StringUtil;
import com.artfess.cqxy.universal.manager.AccessoryManager;
import com.artfess.cqxy.universal.model.Accessory;
import com.artfess.cqxy.wps.model.File;
import com.artfess.cqxy.wps.model.User;
import com.artfess.cqxy.wps.vo.FileVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.*;
import java.text.DecimalFormat;
import java.time.ZoneOffset;

/**
 * @author 黎沐华
 * @date 2022/5/5 17:32
 */
@Slf4j
@RestController
@Api(tags = "WPS在线文档服务.文件回调接口")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
@RequestMapping("/v1/3rd/file")
public class FileCallbackController {
    @Autowired
    private AccessoryManager accessoryManager;
    @Autowired
    private BaseContext baseContext;

    /**
     * 回调接口获取文件信息
     * @param fileid 文件 / 附件 信息
     * @return 文件信息VO
     */
    @ResponseBody
    @GetMapping("/info")
    @ApiOperation("文件信息")
    public FileVo fileInfo(String _w_fileid){
        // 文件信息
        File file = new File();
        // 两层继承，get(id) 拿不到顶层中封装的update_time_字段
        Accessory accessory = accessoryManager.getOne(new QueryWrapper<Accessory>().select("*").eq("ID_", _w_fileid));
        file.setId(accessory.getId());
        file.setName(accessory.getName());
        file.setVersion(StringUtil.isEmpty(accessory.getVersion())?0l:accessory.getVersion());
        //  必须返回文件真实大小，服务端会检查
        file.setSize(accessory.getFileSizeB());
        // 处理时间为时间戳
        file.setCreate_time(accessory.getCreateTime().toEpochSecond(ZoneOffset.of("+8")));
        file.setModify_time(accessory.getUpdateTime().toEpochSecond(ZoneOffset.of("+8")));
        file.setCreator(accessory.getCreateBy());
        file.setModifier(accessory.getUpdateBy());
        // 下载链接中的参数如带中文等特殊字符，参数必须进行urlencode
        file.setDownload_url(accessory.getUrl());
        // 用户信息
        User user = new User();
        user.setId(baseContext.getCurrentUserId());
        user.setName(baseContext.getCurrentUserName());
        user.setPermission("read");
        user.setAvatar_url("http://122.9.167.145:9086/fvue/cqxy.ico");
        return new FileVo(200, "success", "操作成功", file, user);
    }

    @ResponseBody
    @PostMapping("/online")
    public CommonResult online() {
        return new CommonResult<>("");
    }

    @ResponseBody
    @PostMapping("/save")
    public Object save(@RequestParam("file") MultipartFile file, @RequestParam("_w_fileid") String fileid) {
        Accessory accessory = accessoryManager.get(fileid);
        if (!file.isEmpty()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new java.io.File(accessory.getUrl())));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 返回保存后的文件信息 特别是文件大小与版本信息要准确
        accessory.setFileSize(new DecimalFormat("#,##0.##").format(file.getSize() / 1024.00 / 1024.00) + " MB");
        accessory.setVersion(accessory.getVersion() + 1);
        accessoryManager.updateById(accessory);
        return accessory;
    }

    @ResponseBody
    @GetMapping("/version/{version}")
    public Object fileVersionInfo(@PathVariable("version") Long version, @RequestParam("_w_fileid") String _w_fileid) throws UnsupportedEncodingException {
        // 文件信息
        File file = new File();
        // 两层继承，get(id) 拿不到顶层中封装的update_time_字段
        Accessory accessory = accessoryManager.getOne(new QueryWrapper<Accessory>().select("*").eq("ID_", _w_fileid));
        file.setId(accessory.getId());
        file.setName(accessory.getName());
        file.setVersion(version);
        //  必须返回文件真实大小，服务端会检查
        file.setSize(accessory.getFileSizeB());
        // 处理时间为时间戳
        file.setCreate_time(accessory.getCreateTime().toEpochSecond(ZoneOffset.of("+8")));
        file.setModify_time(accessory.getUpdateTime().toEpochSecond(ZoneOffset.of("+8")));
        file.setCreator(accessory.getCreateBy());
        file.setModifier(accessory.getUpdateBy());
        // 下载链接中的参数如带中文等特殊字符，参数必须进行urlencode
        file.setDownload_url(accessory.getUrl());
        // 用户信息
        User user = new User();
        user.setId(baseContext.getCurrentUserId());
        user.setName(baseContext.getCurrentUserName());
        user.setPermission("read");
        user.setAvatar_url("http://122.9.167.145:9086/fvue/cqxy.ico");
        return new FileVo(200, "success", "操作成功", file, user);
    }
}
