package org.jeecg.modules.activiti.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.poi.util.IOUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.activiti.model.entity.ReModelEntity;
import org.jeecg.modules.activiti.service.ReModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * 模型管理
 *
 * @author yao
 * @date 2019/06/13
 */
@RestController
@RequestMapping("/act/remodel")
public class ReModelController {

    @Autowired
    private ReModelService actReModelService;

    @Autowired
    private RepositoryService repositoryService;
    @Resource
    private ObjectMapper objectMapper;
    /**
     * 分页查询
     *
     * @param req
     *            查询参数
     * @return RestResponse
     */
    @GetMapping("/list")
    public Result list(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                       HttpServletRequest req) {
        IPage page = actReModelService.queryPage( pageNo, pageSize, req);

        return Result.OK(page);
    }

    /**
     * 新增
     *
     * @param actReModel
     *            actReModel
     * @return RestResponse
     */
    @PostMapping("/save")
    public Result save(@RequestBody  ReModelEntity actReModel,HttpServletRequest req) {
        String modelId = "";
        try {
            String tenantId = req.getHeader("tenant-id");
            actReModel.setTenantId(tenantId);
            Model model = actReModelService.add(actReModel);
            modelId = model.getId();
        } catch (Exception e) {
            Result.error(e.getMessage());
        }
        return Result.OK(modelId);
    }

    /**
     * 根据Model部署流程
     *
     * @param id
     *            标识
     * @return RestResponse
     */
    @RequestMapping("/deploy")
    public Result deploy(String id,HttpServletRequest request) {

        return actReModelService.deploy(id,request);
    }

    /**
     * 导出model的xml文件
     *
     * @param modelId
     *            model标识
     * @param response
     *            响应
     */
    @GetMapping(value = "/export")
    public void export(String modelId, HttpServletResponse response) throws IOException {

        byte[] modelData = repositoryService.getModelEditorSource(modelId);
        JsonNode jsonNode = objectMapper.readTree(modelData);
        BpmnModel bpmnModel = (new BpmnJsonConverter()).convertToBpmnModel(jsonNode);
        byte[] xmlBytes = (new BpmnXMLConverter()).convertToXML(bpmnModel, "UTF-8");
        ByteArrayInputStream in = new ByteArrayInputStream(xmlBytes);
        IOUtils.copy(in, response.getOutputStream());
        String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";
        response.setHeader("Content-Disposition","attachment;filename=" + filename);
        response.setHeader("content-Type", "application/xml");
        response.flushBuffer();
    }

    /**
     * 根据主键批量删除
     * @param ids
     * @return RestResponse
     */
    @RequestMapping("/deleteBatchByIds")
    public Result deleteBatchByIds(@RequestParam("ids[]") String[] ids) {
        actReModelService.deleteBatch(ids);
        return Result.OK();
    }

    /**
     * 根据主键删除
     * @param id
     * @return RestResponse
     */
    @RequestMapping("/deleteById")
    public Result deleteById(@RequestParam("id") String id) {
        actReModelService.delete(id);
        return Result.OK();
    }

}
