package cn.iocoder.yudao.module.infra.controller.admin.file;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONObject;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.security.config.SecurityProperties;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.*;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.*;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.PostApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.dept.dto.PostRespVO;
import cn.iocoder.yudao.module.system.api.social.SocialClientApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.ap.internal.util.Strings;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.OA_QRCODE_ERROR;

@Tag(name = "管理后台 - 文件存储")
@RestController
@RequestMapping("/infra/file")
@Validated
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    @Resource
    private SocialClientApi socialClientApi;

    @Resource
    private DeptApi deptApi;

    @Resource
    private PostApi postApi;

    @Resource
    private SecurityProperties securityProperties;

    @PostMapping("/uploadBpmFileProcessInstanceId")
    @Operation(summary = "更新文件的流程实例ID")
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
    public String uploadBpmFileProcessInstanceId(@Valid @RequestBody BpmFileUploadReqVO reqVO) throws Exception {
         fileService.uploadBpmFileProcessInstanceId(reqVO);
         return "success" ;
    }

    @PostMapping("/bpmUpload")
    @Operation(summary = "上传文件")
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
    public CommonResult<BpmFileDO> bpmUploadFile(@RequestParam("uploadFiles") MultipartFile file) throws Exception {
        return success(fileService.createReturnFile(file));
    }

    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
    public CommonResult<String> uploadFile(FileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        String path = uploadReqVO.getPath();
        return success(fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream())));
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除文件")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('infra:file:delete')")
    public CommonResult<Boolean> deleteFile(@RequestParam("id") Long id) throws Exception {
        fileService.deleteFile(id);
        return success(true);
    }

    @GetMapping("/{configId}/get/**")
    @PermitAll
    @Operation(summary = "下载文件")
    @Parameter(name = "configId", description = "配置编号",  required = true)
    public void getFileContent(HttpServletRequest request,
                               HttpServletResponse response,
                               @PathVariable("configId") Long configId) throws Exception {
        // 获取请求的路径
        String path = StrUtil.subAfter(request.getRequestURI(), "/get/", false);
        if (StrUtil.isEmpty(path)) {
            throw new IllegalArgumentException("结尾的 path 路径必须传递");
        }
        // 解码，解决中文路径的问题 https://gitee.com/zhijiantianya/ruoyi-vue-pro/pulls/807/
        path = URLUtil.decode(path);

        // 读取内容
        byte[] content = fileService.getFileContent(configId, path);
        if (content == null) {
            log.warn("[getFileContent][configId({}) path({}) 文件不存在]", configId, path);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        ServletUtils.writeAttachment(response, path, content);
    }

    @GetMapping("/page")
    @Operation(summary = "获得文件分页")
    @PreAuthorize("@ss.hasPermission('infra:file:query')")
    public CommonResult<PageResult<FileRespVO>> getFilePage(@Valid FilePageReqVO pageVO) {
        PageResult<FileDO> pageResult = fileService.getFilePage(pageVO);
        return success(BeanUtils.toBean(pageResult, FileRespVO.class));
    }

    @DeleteMapping("/deleteBpmFile")
    @Operation(summary = "删除工作流附件")
    @Parameter(name = "url", description = "附件URL地址", required = true)
    public CommonResult<Boolean> deleteBpmFile(@RequestParam("url") String url) throws Exception {
        fileService.deleteBpmFile(url);
        return success(true);
    }


    //add by yj  2024 04-11 Begin
    @PostMapping("/businessUpload")
    @Operation(summary = "上传业务类型附件【如：工作日/周报附件】")
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
    @PermitAll
    public CommonResult<BusinessFileDO> businessUpload(@RequestParam("uploadFiles") MultipartFile file,@RequestParam("businessType")Long businessType) throws Exception {
        return success(fileService.createBusinessReturnFile(file,businessType));
    }

    @DeleteMapping("/deleteBusinessFile")
    @Operation(summary = "删除业务流附件【如：工作日/周报附件】")
    @Parameter(name = "url", description = "附件URL地址", required = true)
    @PermitAll
    public CommonResult<Boolean> deleteBusinessFile(@RequestParam("url") String url) throws Exception {
        fileService.deleteBusinessFile(url);
        return success(true);
    }

    @PostMapping("/uploadBusinessFileProcessInstanceId")
    @Operation(summary = "更新文件的实例ID【如：工作日/周报附件】")
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
    public String uploadBusinessFileProcessInstanceId(@Valid @RequestBody BusinessFileUploadReqVO reqVO) throws Exception {
        fileService.uploadBusinessFileProcessInstanceId(reqVO);
        return "success" ;
    }
    //add by yj  2024 04-11 End

    @PostMapping("/userFileUpload")
    @Operation(summary = "上传用户文件")
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
    @PermitAll
    public CommonResult<UserFileDO> userFileUpload(@RequestParam("uploadFiles") MultipartFile file) {
        return success(fileService.createUserReturnFile(file));
    }

    @DeleteMapping("/deleteUserFile")
    @Operation(summary = "删除用户文件")
    @Parameter(name = "url", description = "附件URL地址", required = true)
    public CommonResult<Boolean> deleteUserFile(@RequestParam("url") String url) throws Exception {
        fileService.deleteUserFile(url);
        return success(true);
    }

    @PostMapping("/create-QRCode")
    @Operation(summary = "创建入职申请小程序码")
    @Parameter(name = "userId", description = "发起人用户编号", required = true, example = "1024")
    @Parameter(name = "deptId", description = "部门编号", required = true, example = "1024")
    @Parameter(name = "postId", description = "岗位编号", example = "1024")
    public CommonResult<QRCodeDO> createQRCode(@RequestParam("userId") Long userId,
                                               @RequestParam("deptId") Long deptId,
                                               @RequestParam(value = "postId", required = false) Long postId) {



        // 查询当前部门编号下 是否存在小程序码
        QRCodeDO qrCodeDO = fileService.getQRCode(deptId, null);

        JSONObject scene = new JSONObject();
        scene.set("userId", userId);
        scene.set("deptId", deptId);
        scene.set("postId", postId);

        // 小程序码不存在，则 生成新的小程序码
        if (qrCodeDO == null) {

            try {
                qrCodeDO = createQRCode(deptId, scene.toString());

            } catch (IOException e) {

                return error(OA_QRCODE_ERROR);
            }
        }else { // 存在的时候， 判断是否已存在相同参数的小程序码

            // 查询是否存在 参数一致的小程序码
            qrCodeDO = fileService.getQRCode(deptId, scene.toString());
            if (qrCodeDO == null) {

                try {
                    qrCodeDO = createQRCode(deptId, scene.toString());

                } catch (IOException e) {

                    return error(OA_QRCODE_ERROR);
                }
            }else {
                fileService.updateQRCodeFile(qrCodeDO.getId());
            }
        }

        return success(qrCodeDO);
    }

    @GetMapping("getQRCode")
    @Operation(summary = "获得入职申请小程序码")
    @PermitAll
    public CommonResult<QRCodeReqVO> getQRCode(@RequestParam("id") Long id) {

        // 查询当前部门编号下 是否存在小程序码
        QRCodeDO qrCodeDO = fileService.getQRCode(id);

        if (qrCodeDO != null) {

            // 判断小程序码更新时间 是否是当前日期
            if (qrCodeDO.getUpdateTime().toLocalDate().equals(LocalDate.now())) {

                JSONObject scene = new JSONObject(qrCodeDO.getScene());

                QRCodeReqVO reqVO = new QRCodeReqVO();
                reqVO.setUserId(Long.valueOf(qrCodeDO.getUpdater()));

                // 获取部门信息
                Long deptId = Long.valueOf(scene.get("deptId").toString());
                DeptRespDTO deptRespDTO = deptApi.getDept(deptId).getCheckedData();
                reqVO.setDeptId(deptId);
                reqVO.setDeptName(deptRespDTO.getName());

                String postId = scene.get("postId").toString();
                if (!Strings.isEmpty(postId)) {
                    // 获取岗位信息
                    PostRespVO postRespVO = postApi.getPost(Long.valueOf(scene.get("postId").toString())).getCheckedData();
                    reqVO.setPostId(Long.valueOf(postId));
                    reqVO.setPostName(postRespVO.getName());
                }

                return success(reqVO);
            }
        }

        return success(null);
    }

    @DeleteMapping("/delete-QRCode")
    @Operation(summary = "删除小程序码文件")
    @Parameter(name = "url", description = "文件链接", required = true, example = "1024")
    public CommonResult<Boolean> deleteQRCode(@RequestParam("url") String url) {

        fileService.deleteQRCode(url);

        return success(true);
    }

    public QRCodeDO createQRCode(Long deptId, String scene) throws FileNotFoundException {

        Long id = fileService.createQRCodeFile(deptId, scene.toString());

        // 生成小程序码
        File QRCode = socialClientApi.getQRCode("subPages/register/register", "id=" + id).getCheckedData();

        FileInputStream fis = new FileInputStream(QRCode);
        byte[] content = IoUtil.readBytes(fis);

        // 上传小程序码 获得url
        return fileService.updateQRCodeFile(id, deptId, QRCode.getName(), content);
    }
}
