package cn.palmte.work.controller.backend;

import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.model.ActTaskDef;
import cn.palmte.work.model.AdminRepository;
import cn.palmte.work.pojo.ActHisTask;
import cn.palmte.work.service.ActTaskDefService;
import cn.palmte.work.service.SysRoleService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 流程任务
 */
@Controller
@RequestMapping("/actTaskDef")
public class ActTaskDefController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ActTaskDefController.class);

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private SysRoleService sysRoleService;


    @Autowired
    private ActTaskDefService actTaskDefService;

    /**
     * 去任务配置页面
     *
     * @param procDefId
     * @param model
     * @return
     */
    @RequestMapping("/config/{procDefId}")
    public String list(@PathVariable String procDefId, Map<String, Object> model) {
        List<ActTaskDef> list = actTaskDefService.findByProcDefId(procDefId);
        //过滤掉发起节点的全是审批节点
        List<ActTaskDef> approveList = list.stream().filter(t-> t.getTaskIndex() == 0).collect(Collectors.toList());
        model.put("procDefId", procDefId);
        model.put("taskList", list);
        model.put("approveList", approveList);
        model.put("procDefName", list.get(0).getProcDefName());
        model.put("roleList", sysRoleService.getAllEnableSysRole());
        model.put("adminList", adminRepository.getAllEnable());

        return "/admin/act_task_def";
    }


    /**
     * 任务配置保存
     *
     * @param taskDef
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/saveConfig")
    public ResponseMsg saveConfig(ActTaskDef taskDef) {
        actTaskDefService.saveConfig(taskDef);
        return ResponseMsg.buildSuccessMsg("成功");
    }


    /**
     * 完成某个任务
     * 审批通过或者驳回
     *
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/completeTask")
    public ResponseMsg completeTask(@RequestBody String json) {
        JSONObject jsonParam = JSON.parseObject(json);
        actTaskDefService.completeTask(jsonParam);
        return ResponseMsg.buildSuccessMsg("处理成功");
    }

    /**
     * 审批过程查看
     *
     * @param procInsId
     * @param model
     * @return
     */
    @RequestMapping("/hisTaskList/{procInsId}")
    public String taskList(@PathVariable String procInsId, Map<String, Object> model) {
        List<ActHisTask> list = actTaskDefService.hisTaskList(procInsId);
        model.put("taskList", list);
        model.put("procInsId", procInsId);
        return "/admin/act_his_task_list";
    }

}
