package cn.pluss.platform.base;

import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author djh
 */
@Slf4j
public class BaseModelController<S extends IService<T>, T> {

	@Autowired
	protected S baseService;

	@GetMapping("/one")
	@ResponseBody
	public Result<T> get(T condition) {
		QueryWrapper<T> queryWrapper = new QueryWrapper<>(condition);
		T one = baseService.getOne(queryWrapper);
		return ResultGenerator.genSuccessResult(one);
	}

	@GetMapping("/list")
	@ResponseBody
	public Result<List<T>> list(T condition, OrderItem orderItem) {
		QueryWrapper<T> queryWrapper = new QueryWrapper<>(condition);

		if (orderItem != null && StringUtils.isNotBlank(orderItem.getColumn())) {
			queryWrapper.orderBy(true, orderItem.isAsc(), orderItem.getColumn());
		}

		List<T> list;
		try {
			queryWrapper = queryWrapper.orderByDesc("createTime");
			list = baseService.list(queryWrapper);
			return ResultGenerator.genSuccessResult(list);
		} catch (Exception e){
			list = baseService.list(queryWrapper);
			return ResultGenerator.genSuccessResult(list);
		}
	}

	@GetMapping("/page")
	@ResponseBody
	public Result<Page<T>> page(Page<T> page, T condition, OrderItem orderItem) {
		page.getOrders().clear();
		page.getOrders().add(orderItem);
		Page<T> pageData = baseService.page(page, new QueryWrapper<>(condition));
		return ResultGenerator.genSuccessResult(pageData);
	}

	@DeleteMapping("/del/{id}")
	@ResponseBody
	public Result<String> delete(@PathVariable String id) {
		baseService.removeById(id);
		return ResultGenerator.genSuccessResult("删除成功", null);
	}

	@DeleteMapping("/del")
	@ResponseBody
	public Result<String> delete(T condition) {
		baseService.removeById(new QueryWrapper<>(condition));
		return ResultGenerator.genSuccessResult("删除成功", null);
	}

	@PostMapping("/save")
	@ResponseBody
	public Result<String> save(@RequestBody @Validated T entity) {
		baseService.saveOrUpdate(entity);
		return ResultGenerator.genSuccessResult("保存成功", null);
	}
	
}
