package com.jeeplus.pubmodules.oss.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.pubmodules.oss.domain.WorkAttachment;
import com.jeeplus.pubmodules.oss.service.OSSClientService;
import com.jeeplus.pubmodules.oss.service.OssService;
import com.jeeplus.pubmodules.oss.service.dto.AttachmentDTO;
import com.jeeplus.pubmodules.oss.service.dto.FileDetailDTO;
import com.jeeplus.pubmodules.oss.service.dto.FileUrlDto;
import com.jeeplus.pubmodules.oss.service.dto.WorkAttachmentDto;
import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IOfficeApi;
//import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.sys.feign.IUserApi;
//import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.CertDTO;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.dto.WorkAttachmentInfoDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags ="oss")
@RestController
@RequestMapping(value = "/oss/file")
public class OssFileController {

    @Value("${config.accessory.aliyun.aliyunUrl}")
    private String aliyunUrl;

    @Value("${config.accessory.aliyun.aliyunDownloadUrl}")
    private String aliyunDownloadUrl;

    @Resource
    private OssService ossService;

    @Resource
    private SerialnumTplService serialnumTplService;

    @Autowired
    private OSSClientService ossClientService;

//    @Autowired
//    private UserService userService;

//    @Autowired
//    private OfficeService officeService;

    @ApiOperation(value = "保存数据")
    @PostMapping("/saveMsg")
    public void saveMsg(@RequestBody List<WorkAttachment> workAttachments) {
        String currentToken = TokenProvider.getCurrentToken();
        ossService.saveMsg(workAttachments,currentToken);
    }

    @GetMapping("/deleteMsgByFileName")
    @ApiOperation(value = "删除数据")
    public void deleteMsgByFileName(@RequestParam String url) {
        ossService.deleteMsgByFileName(url);
    }

    @GetMapping("/deleteMsgById")
    @ApiOperation(value = "根据id删除数据")
    public void deleteMsgById(@RequestParam String id) {
        ossService.deleteMsgById(id);
    }

    @GetMapping("/getTemporaryUrl")
    @ApiOperation(value = "根据url获取临时文件地址")
    public ResponseEntity<String> getTemporaryUrl(@RequestParam String url) {
        String temporaryLookUrl = ossService.getFileTemporaryLookUrl(aliyunUrl + url);
        return ResponseEntity.ok(temporaryLookUrl);
    }

    @GetMapping("/findFileList")
    @ApiOperation(value = "查询数据")
    public ResponseEntity<List<AttachmentDTO>> findFileList(@RequestParam("attachmentId") String attachmentId) {
        List<AttachmentDTO> list = ossService.findFileList(attachmentId);
        return ResponseEntity.ok(list);
    }

    /**
     * 下载附件
     */
    @GetMapping("/downLoadAttach")
    @ApiOperation(value = "下载附件")
    public String downLoadAttach(@RequestParam String file, HttpServletResponse response, HttpServletRequest request) throws IOException {
        file = "http://oss.gangwaninfo.com" + file;
        file = file.replace("amp;", "");
        String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
        String cons = "";
        if (file.contains(aliyunUrl)) {
            cons = aliyunUrl;
        } else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")) {
            cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
        } else {
            cons = aliyunDownloadUrl;
        }
        String key = file.split(cons + "/")[1];
        log.info("-----------------------------------------");
        log.info("fileName=" + fileName);
        log.info("key=" + key);
        log.info("-----------------------------------------");
        ossService.downByStream(key, fileName, response, request.getHeader("USER-AGENT"));
        return null;
    }

    @GetMapping("/getFileSizeByUrl")
    @ApiOperation(value = "根据文件路径获取文件信息")
    public ResponseEntity<FileDetailDTO> getFileSizeByUrl(@RequestParam("url") String url) {
        FileDetailDTO fileDetailDTO = ossService.getFileSizeByUrl(url);
        return ResponseEntity.ok(fileDetailDTO);
    }

    /**
     * 上传文件
     * @return
     * @throws IOException
     */
    @ApiOperation("上传文件")
    @PostMapping("webUpload/upload")
    public ResponseEntity<FileUrlDto> webUpload(MultipartFile file) throws IOException {
        String dir = "note";
        FileUrlDto dto = ossService.webUpload(file,dir);
        return ResponseEntity.ok(dto);
    }

    /**
     * 上传文件
     * @return
     * @throws IOException
     */
    @ApiOperation("上传文件")
    @PostMapping("webUpload/fileUpload")
    public ResponseEntity<FileUrlDto> fileUpload(MultipartFile file,@RequestParam(required = false) String dir) throws IOException {
        if(StringUtils.isBlank(dir)){
            dir = "oss";
        }
        FileUrlDto dto = ossService.webUpload(file,dir);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据attachmentId查询附件信息（list）
     * @param id
     * @return
     */
    @PostMapping("selectWorkAttachmentByAttachmentId")
    public List<WorkAttachmentInfo> selectWorkAttachmentByAttachmentId(String id){
        return ossService.selectWorkAttachmentByAttachmentId(id);
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @ApiLog("查询用户")
    @GetMapping("queryById")
    @ApiOperation(value = "查询用户")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getById ( id );
        if (CollectionUtil.isEmpty(userDTO.getCertDTOList())){
            List<CertDTO> certListByUserId = SpringUtil.getBean ( IUserApi.class ).getCertListByUserId();
//            List<CertDTO> certListByUserId = userService.getCertListByUserId();
            userDTO.setCertDTOList(certListByUserId);
        }
        if(StringUtils.isNotBlank(userDTO.getManageOfficeIds())){
            //获取当前人管理的部门id
            List<String> manageOfficeIdList= Arrays.asList(userDTO.getManageOfficeIds().split(","));
            //查询这些部门信息
            List<String> officeNameList = SpringUtil.getBean ( IOfficeApi.class ).getOfficeNameByIds(manageOfficeIdList);
//            List<String> officeNameList = officeService.getOfficeNameByIds(manageOfficeIdList);
            userDTO.setManageOfficeNameList(officeNameList);
        }
        if(ObjectUtil.isNotEmpty(userDTO)) {
            if(CollectionUtil.isNotEmpty(userDTO.getCertDTOList())){
                userDTO.getCertDTOList().stream().forEach(item->{
                    if (StringUtils.isNotBlank(item.getFileUrl())){
                        String fileTemporaryLookUrl = ossService.getFileTemporaryLookUrl(item.getFileUrl());
                        item.setFileLsUrl(fileTemporaryLookUrl);
                    }
                });
            }
        }
        //根据office.id 查询部门的所有父节点信息
        if(null != userDTO.getOfficeDTO() && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId())){
            OfficeDTO office = SpringUtil.getBean ( IOfficeApi.class ).getOfficeById(userDTO.getOfficeDTO().getId());
//            OfficeDTO office = officeService.getOfficeById(userDTO.getOfficeDTO().getId());
            //将office的父节点信息进行分割并查询赋值
            if(null != office){
                List<String> officeIdList = Arrays.asList(office.getParentIds().split(","));
                Integer sort = 0;
                if(null != officeIdList && officeIdList.size()>0){
                    for (String officeId : officeIdList) {
                        if(StringUtils.isNotBlank(officeId) && !"0".equals(officeId)){
                            sort ++ ;
                            OfficeDTO officeChild = SpringUtil.getBean ( IOfficeApi.class ).getOfficeById(officeId);
//                            OfficeDTO officeChild = officeService.getOfficeById(officeId);
                            if(null != officeChild) {
                                switch (sort){
                                    case 1:
                                        userDTO.setCompanyDTO(officeChild);
                                        break;
                                    case 2:
                                        userDTO.setCorporationDTO(officeChild);
                                        break;
                                    case 3:
                                        userDTO.setOfficeDTO(officeChild);
                                        break;
                                }
                            }
                        }
                    }
                }
            }

        }
        return ResponseEntity.ok ( userDTO );
    }

    /**
     * 财务模块保存附件使用
     * @param map
     */
    @RequestMapping(value = "financeFileSave", method = RequestMethod.POST)
    public void insertWorkAttachment (@RequestBody Map<String ,String > map){
        String attachmentInfo = map.get("workAttachment");
        String userDtoInfo = map.get("userDTO");
        WorkAttachment attachment = JSON.parseObject(attachmentInfo, new TypeReference<WorkAttachment>() {});
        UserDTO userDTO = JSON.parseObject(userDtoInfo, new TypeReference<UserDTO>() {});
        ossService.insertWorkAttachment(attachment,userDTO);
    }

    @GetMapping("/deleteById")
    @ApiOperation(value = "根据id删除财务文件数据")
    public void deleteById(@RequestParam String id) {
        ossService.deleteById(id);
    }

    /**
     * 保存附件操作
     * @param map
     */
    @RequestMapping(value = "saveOrUpdateFileList", method = RequestMethod.POST)
    public void saveOrUpdateFileList(@RequestBody Map<String ,String > map){
        String fileListInfo = map.get("fileList");
        String attachmentId = map.get("attachmentId");
        String attachmentFlag = map.get("attachmentFlag");
        String currentToken = map.get("currentToken");
        List<WorkAttachmentDto> fileList = JSON.parseObject(fileListInfo, new TypeReference<List<WorkAttachmentDto>>() {});
        ossService.saveOrUpdateFileList(fileList,attachmentId,attachmentFlag,currentToken);
    }

    @RequestMapping(value = "saveOrUpdateFileListFlag", method = RequestMethod.POST)
    public void saveOrUpdateFileListFlag(@RequestBody Map<String ,String > map) {
        String fileListInfo = map.get("fileList");
        String attachmentId = map.get("attachmentId");
        String attachmentFlag = map.get("attachmentFlag");
        String currentToken = map.get("currentToken");
        List<WorkAttachmentInfoDTO> fileList = JSON.parseObject(fileListInfo, new TypeReference<List<WorkAttachmentInfoDTO>>() {});
        ossService.saveOrUpdateFileListFlag(fileList,attachmentId,attachmentFlag,currentToken);
    }


    @GetMapping("/deleteByAttachmentId")
    @ApiOperation(value = "根据attachmentId删除附件")
    public void deleteByAttachmentId(String attachmentId) {
        ossService.deleteByAttachmentId(attachmentId);
    }

    @GetMapping("/deleteByAttachmentIdNotInIds")
    @ApiOperation(value = "根据attachmentId删除附件")
    public void deleteByAttachmentIdNotInIds(String attachmentId,List<String> delIds) {
        ossService.deleteByAttachmentIdNotInIds(attachmentId,delIds);
    }

    /**
     * 根据attachmentId查询附件信息（list）
     * @param attachmentId
     * @return
     */
    @PostMapping("selectListByAttachmentId")
    public List<WorkAttachmentInfo> selectListByAttachmentId(@RequestParam String attachmentId){
        return ossService.selectListByAttachmentId(attachmentId);
    }

    @ApiOperation(value = "根据ids删除财务文件数据")
    @RequestMapping(value = "deleteByIds", method = RequestMethod.POST)
    public void deleteByIds(@RequestBody String ids) {
        List<String> idList = JSON.parseObject(ids, new TypeReference<List<String>>() {});
        idList.forEach(id->{
            ossService.deleteById(id);
        });

    }

    /**
     * 保存附件操作
     * @param map
     */
    @RequestMapping(value = "saveFile", method = RequestMethod.POST)
    public String saveFile(@RequestBody Map<String ,String > map){
        WorkAttachmentDto workAttachmentDto = JSON.parseObject(map.get("workAttachmentDtoInfo"), new TypeReference<WorkAttachmentDto>() {});
        UserDTO userDTO = JSON.parseObject(map.get("userDTOInfo"), new TypeReference<UserDTO>() {});
        String attachmentId = map.get("attachmentId");
        String attachmentFlag = map.get("attachmentFlag");
        Integer sort = Integer.parseInt(map.get("sortInfo"));
        return ossService.saveFile(workAttachmentDto,userDTO,attachmentId,attachmentFlag,sort);
    }

    /**
     * 附件下载到本地指定文件夹
     * @param key
     * @param fileName
     * @param downFileStr
     */
    @RequestMapping(value = "/downByStreamSaveLocal", method = RequestMethod.POST)
    public void downByStreamSaveLocal(String key, String fileName, String downFileStr) {
        ossClientService.downByStreamSaveLocal(key, fileName, downFileStr);
    }

    /**
     * 获取编号模板编号
     * @param companyId
     * @param bizCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/genSerialNum", method = RequestMethod.POST)
    public String genSerialNum(String companyId, String bizCode,String currentToken) throws Exception{
        return serialnumTplService.genSerialNum(companyId, bizCode, currentToken);
    }

    /**
     * 获取编号模板报告编号
     * @param companyId
     * @param bizCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/genSerialNumNoSort", method = RequestMethod.POST)
    public String genSerialNumNoSort(String companyId, String bizCode,String currentToken) throws Exception{
        return serialnumTplService.genSerialNumNoSort(companyId, bizCode,currentToken);
    }

    /**
     * 获取编号模板报告编号
     * @param companyId
     * @param bizCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/genSerialReviewNum", method = RequestMethod.POST)
    public String genSerialReviewNum(String companyId, String bizCode,String currentToken) throws Exception{
        return serialnumTplService.genSerialReviewNum(companyId, bizCode,currentToken);
    }

    /**
     * 根据关联id和url查询数据信息
     * @param workattachment
     * @return
     */
    @RequestMapping(value = "getByAttachmentIdAndUrlAndAttachmentFlag", method = RequestMethod.POST)
    public List<WorkAttachmentInfo> getByAttachmentIdAndUrlAndAttachmentFlag(@RequestBody WorkAttachmentInfo workattachment){
        return ossService.getByAttachmentIdAndUrlAndAttachmentFlag(workattachment);
    }

    /**
     * 附件下载到本地指定文件夹(签章系统)
     * @param key
     * @param fileName
     * @param downFileStr
     */
    @RequestMapping(value = "/downQzByStreamSaveLocal", method = RequestMethod.POST)
    public void downQzByStreamSaveLocal(String key, String fileName,String downFileStr) throws Exception{
        ossClientService.downQzByStreamSaveLocal(key,fileName,downFileStr);
    }

    @PostMapping("datePath")
    public String datePath() {
        return ossClientService.datePath();
    }

    @RequestMapping(value = "/uploadFile2OSS", method = RequestMethod.POST)
    public String uploadFile2OSS(InputStream inStream,String fileDir,String fileName) {
        return ossClientService.uploadFile2OSS(inStream, fileDir, fileName);
    }

    @RequestMapping(value = "/uploadFileSignatureOSS", method = RequestMethod.POST)
    public String uploadFileSignatureOSS(String filePath,String fileDir,String fileName) {
        return ossClientService.uploadFileSignatureOSS(filePath, fileDir, fileName);
    }

    /**
     * 保存附件操作
     * @param map
     */
    @RequestMapping(value = "saveMsg2", method = RequestMethod.POST)
    public void saveMsg2(@RequestBody Map<String ,String > map){
        String attachmentInfo = map.get("workAttachments");
        String currentToken = map.get("currentToken");
        List<WorkAttachment> list = JSON.parseObject(attachmentInfo, new TypeReference<List<WorkAttachment>>() {});
        ossService.saveMsg(list,currentToken);
    }
}
