package org.springblade.flow.base.controller;

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

import javax.validation.Valid;

import org.springblade.flow.base.ActionResult;
import org.springblade.flow.base.Page;
import org.springblade.flow.base.entity.ProvinceEntity;
import org.springblade.flow.base.model.province.ProvinceCrForm;
import org.springblade.flow.base.model.province.ProvinceInfoVO;
import org.springblade.flow.base.model.province.ProvinceListVO;
import org.springblade.flow.base.model.province.ProvinceSelectListVO;
import org.springblade.flow.base.model.province.ProvinceUpForm;
import org.springblade.flow.base.service.ProvinceService;
import org.springblade.flow.base.vo.ListVO;
import org.springblade.flow.database.exception.DataException;
import org.springblade.flow.util.JsonUtil;
import org.springblade.flow.util.JsonUtilEx;
import org.springblade.flow.util.StringUtil;
import org.springblade.flow.util.treeutil.ListToTreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 行政区划
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月27日 上午9:18
 */
@Api(tags = "行政区划", value = "Area")
@RestController
@RequestMapping("/paas/system/Area")
public class AreaController {

	@Autowired
	private ProvinceService provinceService;

	/**
	 * 列表（异步加载）
	 *
	 * @return
	 */
	@ApiOperation("列表（异步加载）")
	@GetMapping("/{nodeId}")
	public ActionResult<ListVO<ProvinceListVO>> list(@PathVariable("nodeId") String nodeId, Page page) {
		List<ProvinceEntity> data = provinceService.getList(nodeId);
		List<ProvinceEntity> dataAll = data;
		if (StringUtil.isNotEmpty(page.getKeyword())) {
			data = data.stream().filter(
					t -> t.getFullName().contains(page.getKeyword()) || t.getEnCode().contains(page.getKeyword()))
					.collect(Collectors.toList());
		}
		List<ProvinceEntity> result = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(data, dataAll),
				ProvinceEntity.class);
		List<ProvinceListVO> treeList = JsonUtil.getJsonToList(result, ProvinceListVO.class);
		int i = 0;
		for (ProvinceListVO entity : treeList) {
			boolean childNode = provinceService.getList(entity.getId()).size() <= 0;
			ProvinceListVO provinceListVO = JsonUtil.getJsonToBean(entity, ProvinceListVO.class);
			provinceListVO.setIsLeaf(childNode);
			provinceListVO.setHasChildren(childNode == true ? false : true);
			treeList.set(i, provinceListVO);
			i++;
		}
		ListVO<ProvinceListVO> vo = new ListVO<>();
		vo.setList(treeList);
		return ActionResult.success(vo);
	}

	/**
	 * 获取行政区划下拉框数据
	 *
	 * @return
	 */
	@ApiOperation("获取行政区划下拉框数据")
	@GetMapping("/{id}/Selector")
	public ActionResult<ListVO<ProvinceSelectListVO>> selectList(@PathVariable("id") String id) {
		List<ProvinceEntity> data = provinceService.getList(id);
		List<ProvinceSelectListVO> treeList = JsonUtil.getJsonToList(data, ProvinceSelectListVO.class);
		int i = 0;
		for (ProvinceSelectListVO entity : treeList) {
			boolean childNode = provinceService.getList(entity.getId()).size() <= 0;
			ProvinceSelectListVO provinceListVO = JsonUtil.getJsonToBean(entity, ProvinceSelectListVO.class);
			provinceListVO.setIsLeaf(childNode);
			treeList.set(i, provinceListVO);
			i++;
		}
		ListVO<ProvinceSelectListVO> vo = new ListVO<>();
		vo.setList(treeList);
		return ActionResult.success(vo);
	}

	/**
	 * 信息
	 *
	 * @param id 主键值
	 * @return
	 */
	@ApiOperation("获取行政区划信息")
	@GetMapping("/{id}/Info")
	public ActionResult<ProvinceInfoVO> info(@PathVariable("id") String id) throws DataException {
		ProvinceEntity entity = provinceService.getInfo(id);
		ProvinceInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, ProvinceInfoVO.class);
		if (!"-1".equals(entity.getParentId())) {
			ProvinceEntity parent = provinceService.getInfo(entity.getParentId());
			vo.setParentName(parent.getFullName());
		}
		return ActionResult.success(vo);
	}

	/**
	 * 新建
	 *
	 * @param provinceCrForm 实体对象
	 * @return
	 */
	@ApiOperation("添加行政区划")
	@PostMapping
	public ActionResult<String> create(@RequestBody @Valid ProvinceCrForm provinceCrForm) {
		ProvinceEntity entity = JsonUtil.getJsonToBean(provinceCrForm, ProvinceEntity.class);
		if (provinceService.isExistByEnCode(provinceCrForm.getEnCode(), entity.getId())) {
			return ActionResult.fail("区域编码不能重复");
		}
		if (StringUtil.isEmpty(provinceCrForm.getParentId())) {
			entity.setParentId("-1");
		}
		provinceService.create(entity);
		return ActionResult.success("新建成功");
	}

	/**
	 * 更新
	 *
	 * @param id 主键值
	 * @return
	 */
	@ApiOperation("修改行政区划")
	@PutMapping("/{id}")
	public ActionResult<String> update(@PathVariable("id") String id,
			@RequestBody @Valid ProvinceUpForm provinceUpForm) {
		ProvinceEntity entity = JsonUtil.getJsonToBean(provinceUpForm, ProvinceEntity.class);
		if (provinceService.isExistByEnCode(provinceUpForm.getEnCode(), id)) {
			return ActionResult.fail("区域编码不能重复");
		}
		boolean flag = provinceService.update(id, entity);
		if (flag == false) {
			return ActionResult.fail("更新失败，数据不存在");
		}
		return ActionResult.success("更新成功");
	}

	/**
	 * 删除
	 *
	 * @param id 主键值
	 * @return
	 */
	@ApiOperation("删除")
	@DeleteMapping("/{id}")
	public ActionResult<String> delete(@PathVariable("id") String id) {
		if (provinceService.getList(id).size() == 0) {
			ProvinceEntity entity = provinceService.getInfo(id);
			if (entity != null) {
				provinceService.delete(entity);
				return ActionResult.success("删除成功");
			}
			return ActionResult.fail("删除失败，数据不存在");
		} else {
			return ActionResult.fail("删除失败，当前有子节点数据");
		}
	}

	/**
	 * 更新行政区划状态
	 *
	 * @param id 主键值
	 * @return
	 */
	@ApiOperation("更新行政区划状态")
	@PutMapping("/{id}/Actions/State")
	public ActionResult<String> upState(@PathVariable("id") String id) {
		ProvinceEntity entity = provinceService.getInfo(id);
		if (entity.getEnabledMark() == null || "1".equals(String.valueOf(entity.getEnabledMark()))) {
			entity.setEnabledMark(0);
		} else {
			entity.setEnabledMark(1);
		}
		boolean flag = provinceService.update(id, entity);
		if (flag == false) {
			return ActionResult.fail("更新失败，数据不存在");
		}
		return ActionResult.success("更新成功");
	}

}
