package com.jpsoft.shinestar.modules.sys.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.sys.entity.Permission;
import com.jpsoft.shinestar.modules.sys.service.PermissionService;
import com.jpsoft.shinestar.modules.sys.service.RolePermissionService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/sys/permission")
public class PermissionController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<Permission> create(){
        MessageResult<Permission> msgResult = new MessageResult<>();

        Permission permission = new Permission();

        msgResult.setData(permission);
        msgResult.setResult(true);

        return msgResult;
    }

    @ApiOperation(value="批量导入")
    @PostMapping("batchImport")
    public MessageResult<Integer> batchImport(@RequestBody List<Permission> permList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (Permission permission : permList) {
                if(!permissionService.exist(permission.getPath(),permission.getMethod())){
                    permission.setId(UUID.randomUUID().toString());
                    permission.setDelFlag(false);
                    permission.setCreateBy(subject);
                    permission.setCreateTime(new Date());

                    affectCount += permissionService.insert(permission);
                }
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("未导入新记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<Permission> add(@RequestBody Permission permission,@RequestAttribute String subject){
        MessageResult<Permission> msgResult = new MessageResult<>();

        try {
            permission.setId(UUID.randomUUID().toString());
            permission.setDelFlag(false);
            permission.setCreateBy(subject);
            permission.setCreateTime(new Date());
            
            int affectCount = permissionService.insert(permission);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(permission);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<Permission> edit(@PathVariable("id") String id){
        MessageResult<Permission> msgResult = new MessageResult<>();

        try {
            Permission permission = permissionService.get(id);

            if (permission != null) {
                msgResult.setResult(true);
                msgResult.setData(permission);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<Permission> update(@RequestBody Permission permission,@RequestAttribute String subject){
        MessageResult<Permission> msgResult = new MessageResult<>();

        try {
            permission.setUpdateBy(subject);
            permission.setUpdateTime(new Date());
            
            int affectCount = permissionService.update(permission);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(permission);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            Permission permission = permissionService.get(id);
            permission.setDelFlag(true);
            permission.setUpdateBy(subject);
            permission.setUpdateTime(new Date());

            int affectCount = permissionService.update(permission);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取所有权限")
    @GetMapping(value = "selectAll")
    public MessageResult<List> selectAll(){
        MessageResult<List> msgResult = new MessageResult<>();

        try {
            List<Permission> perms = permissionService.list();

            msgResult.setResult(true);
            msgResult.setData(perms);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                Permission permission = permissionService.get(id);
                permission.setDelFlag(true);
                permission.setUpdateBy(subject);
                permission.setUpdateTime(new Date());

                affectCount += permissionService.update(permission);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String path,
            @RequestParam(name="pageIndex",defaultValue = "1") int pageIndex,
            @RequestParam(name="pageSize",defaultValue = "10") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("path_","asc"));

        if (StringUtils.isNotEmpty(path)) {
            searchParams.put("path","%" + path + "%");
        }

        Page<Permission> page = permissionService.pageSearch(searchParams,pageIndex,pageSize,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @PostMapping("hasPermission")
    @ApiOperation(value="是否拥有权限")
    public MessageResult<String> hasPermission(String path,String method,@RequestAttribute String subject){
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            String data = null;

            String userId = subject;

            boolean permitted = permissionService.hasPermitted(userId, path, method);

            messageResult.setResult(permitted);

            if (!permitted){
                messageResult.setMessage("当前用户无权限访问该接口!");
            }
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }
}
