package cn.palmte.work.controller.backend;


import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.model.SysPermission;
import cn.palmte.work.model.SysPermissionRepository;
import cn.palmte.work.service.SysPermissionService;
import cn.palmte.work.service.SysRolePermissionService;
import cn.palmte.work.utils.DateKit;
import org.apache.commons.lang.StringUtils;
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 org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 资源管理
 *@author nsp
 *
 */
@Controller
@RequestMapping("/permission")

public class SysPermissionController extends BaseController{

    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private SysPermissionRepository sysPermissionRepository;
    @Autowired
    private SysRolePermissionService sysRolePermissionService;

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


    @RequestMapping("/list")
    public String list(@RequestParam(value = "keywords",required = false) String keywords,
                       @RequestParam(value = "pageNumber",defaultValue = "1") String pageNumber,
                       @RequestParam(value = "sql", required = false) String sql,
                       Map<String, Object> model){
        // 初始化参数
        setModel(keywords, model);
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo(keywords,model);
        model.put("pager",sysPermissionService.getAllPermissionListByPage(searchInfo,pageNumber));
        model.put("sql", sql);

        return "/admin/sys_permission_list";
    }

    private void setModel(String keywords, Map<String, Object> model){
        model.put("pmsLevel","0");
        model.put("pmsType","0");
        model.put("pmsDeleted","-1");
        model.put("permissionID","-1");
        model.put("keywords",keywords);
    }


    @GetMapping(value = "/add")
    public String add( Map<String, Object> model){
        SysPermission  permission=new SysPermission();
        model.put("permissionID","-1");
        model.put("permission",permission);
        model.put("ps", sysPermissionRepository.findPermissions());
        return "/admin/sys_permission_input";
    }


    @PostMapping(value = "/save")
    public String save(@RequestParam("permissionID") String permissionID,
                       SysPermission sysPermission, RedirectAttributes attr, Map<String, Object> model) throws IOException{

        final SysPermission parent = sysPermissionRepository.findOne(sysPermission.getParentId());
        sysPermission.setLevel(parent.getLevel()+1);
        int type = (parent.getLevel()==4) ? 2 : 1;
        sysPermission.setType(type);

        String message = sysPermissionService.check(sysPermission,permissionID);

        if (StringUtils.isNotEmpty(message)) {
            model.put("errorMessage", message);
            return "/common/error";
        }

        if ("-1".equals(permissionID)){
            getSql(sysPermission, attr, parent);
            sysPermissionService.addPermission(sysPermission); //新增
        }else {
            sysPermissionService.updatePermission(sysPermission,permissionID); // 修改
        }
        return "redirect:/permission/list";
    }

    private void getSql(SysPermission sysPermission, RedirectAttributes attr, SysPermission parent) {
        String sql1 = "INSERT INTO `sys_permission` (`name`, `icon`, `url`, `permission`, `parent_id`, `level`, `type`, `sort`, `remark`, `is_deleted`, `created_by`, `created_time`, `last_updated_by`, `last_updated_time`) VALUES ('{name}', '', '{url}', '{permission}', (SELECT id FROM sys_permission sp WHERE sp.permission = '{parentPermission}'), '{level}', '{type}', '{sort}', '', b'0', '1', '{time}', '1', '{time}');"
                .replace("{name}", sysPermission.getName())
                .replace("{url}", sysPermission.getUrl())
                .replace("{permission}", sysPermission.getPermission())
                .replace("{parentPermission}", parent.getPermission())
                .replace("{level}", sysPermission.getLevel()+"")
                .replace("{type}", sysPermission.getType()+"")
                .replace("{sort}", sysPermission.getSort()+"")
                .replace("{time}", DateKit.toStr(new Date(), DateKit.TIME_FORMAT));

        String sql2 = "INSERT INTO `sys_role_permission` (`role_id`, `permission_id`, `is_deleted`, `created_by`, `created_time`, `last_updated_by`, `last_updated_time`) VALUES ('1', (SELECT id FROM sys_permission WHERE permission = '{permission}'), b'0', '1', '{time}', '1', '{time}');"
                .replace("{permission}", sysPermission.getPermission())
                .replace("{time}", DateKit.toStr(new Date(), DateKit.TIME_FORMAT));
        attr.addAttribute("sql", sql1 + "</br>" + sql2);
    }


    @GetMapping(value = "/edit")
    public String edit(@RequestParam("id") String permissionID,Map<String, Object> model){
        SysPermission permission =sysPermissionRepository.findOne(Integer.parseInt(permissionID));
        model.put("permissionID",permissionID);
        model.put("permission",permission);
        model.put("ps", sysPermissionRepository.findPermissions());
        return "/admin/sys_permission_input";
    }


    @GetMapping(value = "/delete")
    @ResponseBody
    public ResponseMsg delete(@RequestParam("ids") String ids){
        String[] deleteIds=ids.split("#%#");
        boolean deleted = sysPermissionService.deletePermissionByIDs(deleteIds);
        boolean bDel = sysRolePermissionService.deleteSysRolePermissionByIDs(deleteIds);

        ResponseMsg responseMsge=new ResponseMsg();
        if(deleted && bDel){
            logger.info("删除成功");
            responseMsge.setStatus(0);
            responseMsge.setMsg("删除成功");
        } else{
            responseMsge.setStatus(1);
            responseMsge.setMsg("删除失败");
        }
        return responseMsge;
    }

}
