package com.persagy.adm.diagram.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.persagy.adm.diagram.entity.IconEntity;
import com.persagy.adm.diagram.frame.BdtpRequest;
import com.persagy.adm.diagram.service.IconService;
import com.persagy.dmp.common.constant.ResponseCode;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.common.model.response.CommonResult;
import com.persagy.dmp.common.utils.ResultHelper;
import com.persagy.dmp.file.model.FileInfo;
import com.persagy.dmp.file.model.FileInfoCreator;
import com.persagy.dmp.file.utils.FileStorageHelper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;

/**
 * 图标相关接口
 *
 * @author liyang
 * @date 2022-01-06
 */
@RestController
@CrossOrigin
@RequestMapping("/icon")
public class IconController {

    @Autowired
    private IconService iconService;

    /**
     * 上传图标接口
     *
     * @param file     文件
     * @param legendId 所关联的图例id
     * @param system   图例所属系统类型
     * @param skin     皮肤
     * @return
     */
    @ApiOperation("上传图标")
    @PostMapping("/uploadIcon")
    public CommonResult<Object> uploadIcon(@RequestParam("file") MultipartFile file,
                                           @RequestParam String legendId,
                                           @RequestParam String system,
                                           @RequestParam(required = false) String skin) {
        String fileName = file.getOriginalFilename();
        long size = file.getSize();

        IconEntity entity = new IconEntity();
        entity.setIconSkin(skin);
        entity.setLegendId(legendId);
        entity.setSystemType(system);
        entity.setIconSize(String.valueOf(size));

        Optional.ofNullable(fileName).ifPresent(s -> {
            int index = s.lastIndexOf(".");
            String name = s.substring(0, index);
            String fileType = s.substring(index + 1);
            entity.setIconName(name);
            entity.setIconType(fileType);
        });
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (null == inputStream) {
            throw new BusinessException(ResponseCode.A0400.getCode(), "文件不能为空,并且必须是图片!");
        }
        //如果图例存在(已上传)，那么需要替换
        IconEntity icon = iconService.getIconsByLegendId(legendId, skin);
        if (null != icon) {
            String s = FileStorageHelper.replaceFile(icon.getIconFileId(), entity.getIconName(), inputStream);
            entity.setId(icon.getId());
            entity.setIconFileId(s);
        } else {
            FileInfo fileInfo = FileInfoCreator.of(BdtpRequest.getCurrent().getGroupCode(), null,
                    null, entity.getIconName());
            String fileId = FileStorageHelper.uploadFile(fileInfo, inputStream);
            entity.setIconFileId(fileId);
        }
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultHelper.single(iconService.saveIcon(entity));

    }

    /**
     * 图标预览
     *
     * @param request  请求体
     * @param response 响应体
     * @param iconId   图标数据id
     */
    @ApiOperation("图标预览")
    @GetMapping("/showImage")
    public void showImage(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam("id") String iconId) {
        IconEntity info = iconService.getIconInfo(iconId);
        if (null == info) {
            throw new BusinessException(ResponseCode.A0400.getCode(), "未查到此数据");
        }
        FileInfo fileInfo = FileStorageHelper.downloadUrl(info.getIconFileId());
        // 2.通过http请求获取文件流
        byte[] bytes = HttpUtil.downloadBytes(fileInfo.getFileDownloadUrl());
        ServletOutputStream out = null;
        try {
            //svg格式文件的Content-Type：svg+xml;charset=utf-8   text/xml ，都可以
            //element图片控件需要svg+xml
            if (StrUtil.equalsIgnoreCase(info.getIconType(), "svg")) {
                response.setHeader("Content-Type", "image/svg+xml;charset=utf-8");
                //response.setHeader("Content-Type", "image/svg+xml");
            } else {
                response.setHeader("Content-Type", "image/" + info.getIconType());
            }
            out = response.getOutputStream();
            out.write(bytes);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据图例id获取图标
     *
     * @param legendId 图例id
     * @return
     */
    @ApiOperation("根据图例id获取图例")
    @GetMapping("/icons/legend")
    public CommonResult<IconEntity> getIconsByLegendId(String legendId) {
        return ResultHelper.single(iconService.getIconsByLegendId(legendId, null));
    }

    /**
     * 获取项目 集团 下的所有图标
     *
     * @return
     */
    @ApiOperation("获取所有图标")
    @GetMapping("/icons")
    public CommonResult<List<IconEntity>> getIcons() {
        return ResultHelper.multi(iconService.getIcons());
    }

    /**
     * 根据系统类型获取所有图标
     *
     * @return
     */
    @ApiOperation("根据系统类型获取所有图标")
    @GetMapping("/icons/type")
    public CommonResult<List<IconEntity>> getIconsBySystemType(String system) {
        return ResultHelper.multi(iconService.getIconsBySystemType(system));
    }
}
