/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.workflow.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.codvision.commoncore.common.ResponseEntity;
import com.codvision.commoncore.exception.BusinessException;
import com.codvision.webcore.bean.QueryPage;
import com.codvision.workflow.entity.WorkFlowDefinition;
import com.codvision.workflow.entity.WorkFlowVersionRecord;
import com.codvision.workflow.entity.dto.WorkFlowDefinitionDTO;
import com.codvision.workflow.entity.vo.WorkFlowElementVO;
import com.codvision.workflow.service.WorkFlowDefinitionService;
import com.codvision.workflow.service.WorkFlowVersionRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author hxl
 */
@Slf4j
@Api(tags = "工作流流程定义管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/flowDefinition")
public class WorkFlowDefinitionController {

    private final WorkFlowDefinitionService service;
    private final WorkFlowVersionRecordService versionService;

    @PostMapping("/getPageResult")
    @ApiOperation("分页列表")
    public ResponseEntity<IPage<WorkFlowDefinition>> getPageResult(@RequestBody QueryPage<Map<String, Object>> queryPage) {
        return new ResponseEntity<IPage<WorkFlowDefinition>>().data(service.getPageResult(queryPage));
    }

    @PostMapping("/getVersionRecord")
    @ApiOperation("版本更新记录列表")
    public ResponseEntity<IPage<WorkFlowVersionRecord>> getVersionRecord(@RequestBody QueryPage<Map<String, Object>> queryPage) {
        return new ResponseEntity<IPage<WorkFlowVersionRecord>>().data(versionService.getPageResult(queryPage));
    }

    @PostMapping("/save")
    @ApiOperation("流程定义保存")
    public ResponseEntity<String> save(@RequestBody WorkFlowDefinitionDTO definitionDTO) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        try (InputStream in = new ByteArrayInputStream(definitionDTO.getXmlFile().getBytes(StandardCharsets.UTF_8))) {
            service.save(definitionDTO, in);
        } catch (Exception e) {
            log.error(e.getMessage());
            return responseEntity.error(10000,"保存失败");
        }

        return responseEntity.ok();
    }

    @ApiOperation("激活或挂起流程定义")
    @PostMapping("/activeOrSuspend")
    public ResponseEntity<String> changeState(@RequestParam(value = "state") Integer state,
                                              @RequestParam(value = "deployId") String deployId) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        if (state == null || StringUtils.isBlank(deployId)) {
            throw new BusinessException(30002);
        }

        service.activeOrSuspend(state, deployId);
        return responseEntity.ok();
    }


    @ApiOperation("删除流程定义")
    @PostMapping("/del")
    public ResponseEntity<String> del(@RequestBody List<String> deployIds) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        if (CollectionUtils.isEmpty(deployIds)) {
            throw new BusinessException(30002);
        }

        service.delete(deployIds);
        return responseEntity.ok();
    }

    @ApiOperation("获取流程定义xml文件")
    @GetMapping("/getXml/{deployId}")
    public ResponseEntity<String> getXml(@PathVariable(value = "deployId") String deployId) {
        return new ResponseEntity<String>().data(service.getXml(deployId));
    }

    @ApiOperation("获取流程定义图片文件")
    @GetMapping("/getImage/{deployId}")
    public void getImage(@PathVariable(value = "deployId") String deployId, HttpServletResponse response) {
        response.setContentType("image/png");
        try (OutputStream os = response.getOutputStream()) {
            BufferedImage image = ImageIO.read(service.getImage(deployId));
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    @ApiOperation("根据流程定义xml获取所有可回退的节点")
    @PostMapping("/getReturnTaskList")
    public ResponseEntity<List<WorkFlowElementVO>> getReturnTaskList(@RequestParam(value = "xmlStr") String xmlStr,
                                                                     @RequestParam(value = "currentTaskKey") String currentTaskKey) {
        ResponseEntity<List<WorkFlowElementVO>> responseEntity = new ResponseEntity<>();
        if (StringUtils.isBlank(xmlStr) || StringUtils.isBlank(currentTaskKey)) {
            throw new BusinessException(30002);
        }

        return responseEntity.data(service.getReturnTaskList(xmlStr, currentTaskKey));
    }
}
