
package com.goafanti.permission.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.goafanti.common.bo.Result;
import com.goafanti.common.controller.BaseApiController;
import com.goafanti.common.model.Permission;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.permission.service.PermissionService;

@RestController
public class PermissionApiController extends BaseApiController {
	@Resource
	private PermissionService permissionService;

	@RequestMapping(value = "/permissions", method = RequestMethod.GET)
	public Result permissions() {
		Result res = new Result();
		res.setData(permissionService.findPermissions());
		return res;
	}

	@RequestMapping(value = "/permission", method = RequestMethod.POST)
	public Result insertPermission(String data) {
		Result res = new Result();
		JSONArray ja = (JSONArray) JSON.parse(data);
		if (ja != null && !ja.isEmpty()) {
			List<Permission> records = new ArrayList<>();
			for (int idx = 0; idx < ja.size(); idx++) {
				records.add(ja.getJSONObject(idx).toJavaObject(Permission.class));
			}
			for (Permission p : records){
				if (StringUtils.isBlank(p.getId())){
					p.setId(UUID.randomUUID().toString());
				}
			}
			res.setData(permissionService.insert(records));
		} else {
			res.getError().add(buildError("", "参数格式不正确"));
		}
		return res;
	}

	@RequestMapping(value = "/permission/delete", method = RequestMethod.POST)
	public Result deletePermission(String data) {
		Result res = new Result();
		JSONArray ja = (JSONArray) JSON.parse(data);
		if (ja != null && !ja.isEmpty()) {
			List<String> records = new ArrayList<>();
			for (int idx = 0; idx < ja.size(); idx++) {
				records.add(ja.getString(idx));
			}
			res.setData(permissionService.deleteByPrimaryKeys(records));
		} else {
			res.getError().add(buildError("", "参数格式不正确"));
		}
		return res;
	}

}
