package cn.palmte.work.controller.backend;


import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.service.ActModelService;

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 javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 流程模型
 */
@Controller
@RequestMapping("/actModel")
public class ActModelController extends BaseController {

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

    @Autowired
    private ActModelService activitiModelService;

    @RequestMapping("/list")
    public String list(@RequestParam(value = "keywords", required = false) String keywords,
                       @RequestParam(value = PAGE_NUMBER, defaultValue = DEFAULT_PAGE_NUMBER) int pageNumber,
                       @RequestParam(value = PAGE_SIZE, defaultValue = DEFAULT_PAGE_SIZE) int pageSize,
                       Map<String, Object> model) {
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo(keywords, model);
        model.put("pager", activitiModelService.list(searchInfo, pageNumber, pageSize));
        return "/admin/act_model_list";
    }


    @GetMapping(value = "/add")
    public String add() {
        return "/admin/act_model_input";
    }

    @RequestMapping("/save")
    public String save(HttpServletRequest request) {
        try {
            activitiModelService.createModel(request.getParameter("procDefKey"), request.getParameter("modelName"));
        } catch (Exception e) {
            logger.error("", e);
        }
        return "redirect:/actModel/list";
    }


    @ResponseBody
    @GetMapping(value = "/delete")
    public ResponseMsg delete(@RequestParam("ids") String ids) {
        if ("".equals(ids)) {
            return ResponseMsg.buildFailedMsg("删除失败，无选中项！");
        } else {
            String[] deleteIds = ids.split("#%#");
            for (String id : deleteIds) {
                activitiModelService.deleteModel(id);
            }
            return ResponseMsg.buildSuccessMsg("删除成功");
        }
    }


    /**
     * 部署流程
     *
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/deploy")
    public ResponseMsg deploy(@RequestParam("id") String id) {
        try {
            activitiModelService.deploy(id);
        } catch (Exception e) {
            logger.error("", e);
            return ResponseMsg.buildFailedMsg(e.getMessage());
        }
        return ResponseMsg.buildSuccessMsg("部署成功");
    }

}
