package com.bcxin.wps.controllers;

import cn.hutool.json.JSONUtil;
import cn.wps.solution.weboffice.provider.v3.model.UserPermission;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.bcxin.utils.BASE64Util;
import com.bcxin.wps.configs.WpsProperties;
import com.bcxin.wps.entity.File;
import com.bcxin.wps.repository.FileRepository;
import com.bcxin.wps.repository.StorageRepository;
import com.bcxin.wps.repository.UserRepository;
import com.bcxin.wps.util.WpsFileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.Map;

@Controller
@RequestMapping("/v2/wps")
public class V2PreviewController {
    private static Logger logger = LoggerFactory.getLogger(V2PreviewController.class);

    private final FileRepository fileRepository;
    private final StorageRepository storageRepository;
    private final WpsProperties wpsProperties;
    private final UserRepository userRepository;

    public V2PreviewController(FileRepository fileRepository, StorageRepository storageRepository,
                               WpsProperties wpsProperties, UserRepository userRepository) {
        this.fileRepository = fileRepository;
        this.storageRepository = storageRepository;
        this.wpsProperties = wpsProperties;
        this.userRepository = userRepository;
    }

    @GetMapping(value = "/preview")
    public ModelAndView preview(
            @RequestParam("filePath") String filePath,
            @RequestParam("readonly") String readonly,
            @RequestParam(value = "envi", required = false) String envi,
            @RequestParam(value = "officeType", required = false,defaultValue = "Writer") String officeType,
                                Model model) throws Exception {
        String userId = "1";
        String url = filePath;
        boolean encrypted = false;
        try {
            url = BASE64Util.decryptBASE64(filePath);
            encrypted = true;
        } catch (Exception ex) {
            logger.error("解密失败; 系统原本({})就是传递未加密的数据; 最终数据={}", filePath, url);
        }

        UserPermission.UserPermissionBuilder userPermissionBuilder =
                UserPermission.builder().read(true).print(true).userId(userId);
        if (!"1".equalsIgnoreCase(readonly) && !"true".equalsIgnoreCase(readonly)) {
            userPermissionBuilder = userPermissionBuilder
                    .comment(true)
                    .copy(true).download(true).rename(true).update(true)
                    .saveAs(true).history(true);
        }

        byte[] content = WpsFileUtils.readAllBytes(url);
        UserPermission permission = userPermissionBuilder.build();
        String fileName = url.substring(url.lastIndexOf('/') + 1);
        Timestamp now = Timestamp.from(Instant.now());
        String selectedEnvi = envi;
        if(StringUtils.hasLength(selectedEnvi) && selectedEnvi.length()>50) {
            selectedEnvi = selectedEnvi.substring(0, 50);
        }
        
        File file =
                File.builder()
                        .id(String.valueOf(IdWorker.getId()))
                        .version(1)
                        .name(fileName)
                        .url(url)
                        .permissionOption(JSONUtil.toJsonStr(permission))
                        .encrypted(encrypted)
                        .env(selectedEnvi)
                        .creatorId(userId)
                        .createTime(now)
                        .modifyTime(now)
                        .size(content.length)
                        .modifierId(userId).build();
        this.storageRepository.save(file, content);

        this.fileRepository.save(file);

        model.addAttribute("appId", this.wpsProperties.getAppId());
        model.addAttribute("fileId", file.getId());
        model.addAttribute("readonly", readonly);
        model.addAttribute("userId", userId);
        model.addAttribute("officeType", officeType);

        return new ModelAndView("wps_index");
    }

    @GetMapping(value = "/file-maps")
    public @ResponseBody Map getLocalMap() {
        return this.storageRepository.findAll();
    }
}
