package com.ruoyi.project.activiti.controller;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.activiti.domain.MyProcessDefinition;
import com.ruoyi.project.activiti.domain.MyTask;
import com.ruoyi.project.activiti.domain.SelectVo;
import com.ruoyi.project.activiti.service.impl.ProcessDefinitionServiceImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.framework.web.domain.AjaxResult.error;
import static com.ruoyi.framework.web.domain.AjaxResult.success;

@RestController
@RequestMapping("/definition")
public class ProcessDefinitionController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(ProcessDefinitionController.class);


    @Autowired
    private ProcessDefinitionServiceImpl processDefinitionService;

    /**
     * 部署流程定义
     */
    @PostMapping("/upload")

    public AjaxResult upload(@RequestParam("processDefinition") MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                String extensionName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
                if ("xml".equalsIgnoreCase(extensionName)) {
                    if (!file.getOriginalFilename().contains("bpmn20.xml")) {
                        return error("流程定义文件仅支持 bpmn, bpmn20.xml, zip 和 bar 格式！");
                    }
                }
                if (!"xml".equalsIgnoreCase(extensionName)
                        && !"bpmn".equalsIgnoreCase(extensionName)
                        && !"zip".equalsIgnoreCase(extensionName)
                        && !"bar".equalsIgnoreCase(extensionName)) {
                    return error("流程定义文件仅支持 bpmn, bpmn20.xml, zip 和 bar 格式！");
                }
                processDefinitionService.deployProcessDefinition(file);
                return success();

            }
            return error();
        } catch (Exception e) {
            log.error("上传流程定义文件失败！", e);
            return error(e.getMessage());
        }
    }

    /**
     * 获取部署的流程文件
     */
    @GetMapping("/list")
    public AjaxResult list(Integer pageNum,Integer pageSize) {
        List<MyProcessDefinition> list = processDefinitionService.list(pageNum, pageSize);
        return AjaxResult.success(list);
    }

    /**
     * 获取部署的流程文件
     */
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id") String id) {
        return AjaxResult.success(processDefinitionService.get(id));
    }
    /**
     * 获取部署的流程文件
     */
    @GetMapping("/select")
    public AjaxResult select() {
        List<SelectVo> list = processDefinitionService.select();
        return AjaxResult.success(list);
    }
    /**
     * 获取部署的流程文件
     */
    @GetMapping("/start")

    public AjaxResult start() {
        processDefinitionService.start();
        return AjaxResult.success();
    }

    /**
     * 移除流程对象
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public AjaxResult remove(@RequestBody List<String> ids) {
        try {
            return toAjax(processDefinitionService.deleteProcessDeploymentByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @PostMapping("/export")
    public TableDataInfo export() {
        List<ProcessDefinition> list = processDefinitionService.listProcessDefinition();
        return getDataTable(list);
    }


    @RequestMapping(value = "/tasks", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<TaskRepresentation> getTasks(@RequestParam String assignee) {
        List<Task> tasks = processDefinitionService.getTasks(assignee);
        List<TaskRepresentation> dtos = new ArrayList<TaskRepresentation>();
        for (Task task : tasks) {
            dtos.add(new TaskRepresentation(task.getId(), task.getName()));
        }
        return dtos;
    }

    static class StartProcessRepresentation {

        private String assignee;

        public String getAssignee() {
            return assignee;
        }

        public void setAssignee(String assignee) {
            this.assignee = assignee;
        }
    }

    static class TaskRepresentation {

        private String id;
        private String name;

        public TaskRepresentation(String id, String name) {
            this.id = id;
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }

}
