package com.th.demo.controller.process;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.th.demo.model.system.Type;

import com.th.demo.tools.Tools;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;

import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dell on 2018-11-12.
 */
@RestController
@RequestMapping(value = "/ProcessDeployment")
public class DeploymentController {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;

    String result = Type.FAIL;

    @RequestMapping(value = "/query.do")
    public String query(int page,
                        int rows,
                        String key,
                        String userId,
                        HttpServletResponse response) throws IOException {

        PageHelper.startPage(page, rows);
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().processDefinitionKey(key).orderByProcessDefinitionVersion().desc().list();

        List<Map<String, Object>> listmap = new ArrayList<>();
        Map<String, Object> map;
        for (int i = 0; i < list.size(); i++) {
            map = new HashMap<String, Object>();
            map.put("id", list.get(i).getId());
            map.put("key", list.get(i).getKey());
            map.put("deploymentId", list.get(i).getDeploymentId());
            map.put("version", list.get(i).getVersion());
            map.put("name", list.get(i).getName());
            map.put("suspensionState", list.get(i).isSuspended());

            listmap.add(map);
        }
        // List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().listPage((page-1)*rows+1,page*rows);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(listmap);
        result = JSON.toJSONString(pageInfo);
        return result;
    }


    /**
     * 删除deployment
     **/
    @RequestMapping(value = "/remove.do")
    public String remove(String deploymentId,
                         String userId,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        try {


            repositoryService.deleteDeployment(deploymentId);
            result = Type.SUCCESS;

        } catch (Exception ex) {
            ex.printStackTrace();
            result = Type.FAIL + ex.getMessage();
        } finally {
            return result;
        }
    }

    /**
     * 挂起
     */
    @RequestMapping(value = "/suspend.do")
    public String suspend(String definitionId,
                          String userId,
                          HttpServletRequest request, HttpServletResponse response) {
        try {

            repositoryService.suspendProcessDefinitionById(definitionId);
            result = Type.SUCCESS;

        } catch (Exception ex) {
            ex.printStackTrace();
            result = Type.FAIL + ex.getMessage();
        } finally {
            return result;
        }
    }

    /**
     * 激活
     */
    @RequestMapping(value = "/activate.do")
    public String activate(String definitionId,
                           String userId,
                           HttpServletRequest request, HttpServletResponse response) {
        try {
            repositoryService.activateProcessDefinitionById(definitionId);
            result = Type.SUCCESS;
        } catch (Exception ex) {
            ex.printStackTrace();
            result = Type.FAIL + ex.getMessage();
        } finally {
            return result;
        }
    }

    /**
     * 显示流程图
     */
    @RequestMapping(value = "/showImage.do")
    public void showPng(String deploymentId,
                        HttpServletRequest request, HttpServletResponse response) {
        try {
            List<String> names = repositoryService.getDeploymentResourceNames(deploymentId);
            String imageName = null;
            for (String name : names) {
                if (name.indexOf(".png") >= 0) {
                    imageName = name;
                }
            }

            if (imageName != null) {
                InputStream in = repositoryService.getResourceAsStream(deploymentId, imageName);

//                File f = new File("d:/" + imageName);
//                FileUtils.copyInputStreamToFile(i, f);

                OutputStream out = response.getOutputStream();
                byte[] b = new byte[1024];
                for (int len = -1; (len = in.read(b)) != -1; ) {
                    out.write(b, 0, len);
                }
                out.close();
                in.close();
            }


            result = Type.SUCCESS;
        } catch (Exception ex) {
            ex.printStackTrace();
            //result = Type.FAIL + ex.getMessage();
        }
//        finally {
//            Tools.out(response, result);
//        }
    }
}
