package com.activiti6.controller.activiti;



import com.activiti6.common.utils.StringUtils;
import com.activiti6.domain.*;
import com.activiti6.mapper.MyActivitiMapper;
import com.activiti6.service.activiti.impl.ProcessDefinitionServiceImpl;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
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;


@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 AjaxResult.error("流程定义文件仅支持 bpmn, bpmn20.xml, zip 和 bar 格式！");
                    }
                }
                if (!"xml".equalsIgnoreCase(extensionName)
                        && !"bpmn".equalsIgnoreCase(extensionName)
                        && !"zip".equalsIgnoreCase(extensionName)
                        && !"bar".equalsIgnoreCase(extensionName)) {
                    return AjaxResult.error("流程定义文件仅支持 bpmn, bpmn20.xml, zip 和 bar 格式！");
                }
                processDefinitionService.deployProcessDefinition(file);
                return AjaxResult.success();

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

    /**
     * 获取部署的流程文件
     */
    @GetMapping("/list")
    public TableDataInfo list(String title, Integer pageNum, Integer pageSize) {
        TableDataInfo list = processDefinitionService.list(title, pageNum, pageSize);
        return list;
    }

    /**
     * 获取部署的流程文件
     */
    @GetMapping("/key/{processDefinitionKey}")
    public AjaxResult processDefinitionKey(@PathVariable("processDefinitionKey") String processDefinitionKey) {
        MyProcessDefinition myProcessDefinition = processDefinitionService.processDefinitionKey(processDefinitionKey);
        return AjaxResult.success(myProcessDefinition);
    }


    /**
     * 获取部署的流程文件
     */
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id") String id) {
        return AjaxResult.success(processDefinitionService.get(id));
    }

    /**
     * 获取部署的流程文件
     */
    @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 AjaxResult.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;
        }

    }


    @Autowired
    private IdentityService identityService;

    @Autowired
    private MyActivitiMapper myActivitiMapper;

    /**
     * 新增用户和
     *
     * @param
     */
    @PostMapping("/user")
    public AjaxResult addUser(@RequestBody SysUser sysUser) {
        String userId = sysUser.getUserId().toString();
        String userName = sysUser.getUserName();
        User user = null;
        try {
            user = identityService.createUserQuery().userId(userId).singleResult();
            if (null == user) {
                user = identityService.newUser(userId);
            } else {
                int i = myActivitiMapper.deleteGroupByUserId(userId);
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        user.setFirstName(userName);
        identityService.saveUser(user);
        Long deptId = sysUser.getDeptId();
        if (StringUtils.isNotNull(deptId)) {
            String groupId = deptId.toString();
            identityService.createMembership(userId, groupId);
        }
        return AjaxResult.success();
    }

    @DeleteMapping("/user")
    public AjaxResult deleteUser(String id) {
        identityService.deleteUser(id);
        return AjaxResult.success();
    }

    @PostMapping("/group")
    public AjaxResult addGroup(@RequestBody SysDept sysDept) {
        String deptName = sysDept.getDeptName();
        String deptId = sysDept.getDeptId().toString();
        Group group = identityService.createGroupQuery().groupId(deptId).singleResult();
        if (null == group) {
            group = identityService.newGroup(deptId);
        }
        group.setName(deptName);
        identityService.saveGroup(group);
        return AjaxResult.success();
    }

    @DeleteMapping("/group")
    public AjaxResult deleteGroup(String id) {
        identityService.deleteGroup(id);
        return AjaxResult.success();
    }

}
