package com.cym.controller.page;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cym.bean.Page;
import com.cym.ext.ExampleExt;
import com.cym.model.Admin;
import com.cym.model.Example;
import com.cym.service.ExampleService;
import com.cym.utils.BaseController;
import com.cym.utils.JsonResult;

import cn.hutool.core.bean.BeanUtil;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/adminPage/example")
public class ExampleController extends BaseController {
	@Autowired
	ExampleService exampleService;

	@RequestMapping("")
	public ModelAndView index(ModelAndView modelAndView, Page page, String keyword) {
		page = exampleService.search(page, keyword);

		List<ExampleExt> exts = new ArrayList<ExampleExt>();
		for (Example example : (List<Example>) page.getList()) {
			ExampleExt exampleExt = new ExampleExt();
			BeanUtil.copyProperties(example, exampleExt);

			exampleExt.setAdmin(jpaHelper.findById(example.getAdminId(), Admin.class));

			exts.add(exampleExt);
		}
		page.setList(exts);

		
		modelAndView.addObject("adminList", jpaHelper.findAll(Admin.class));
		modelAndView.addObject("page", page);
		modelAndView.addObject("keyword", keyword);
		modelAndView.setViewName("/example/index");
		return modelAndView;
	}
	
	

	@RequestMapping("addOver")
	@ResponseBody
	public JsonResult addOver(Example example) {

		jpaHelper.insertOrUpdate(example);

		return renderSuccess();
	}


	@RequestMapping("detail")
	@ResponseBody
	public JsonResult detail(String id) {
		Example example = jpaHelper.findById(id, Example.class);
		ExampleExt exampleExt = new ExampleExt();
		BeanUtil.copyProperties(example, exampleExt);

		exampleExt.setAdmin(jpaHelper.findById(example.getAdminId(), Admin.class));

		return renderSuccess(exampleExt);
	}

	@Transactional
	@RequestMapping("del")
	@ResponseBody
	public JsonResult del(String id) {
		jpaHelper.deleteById(id, Example.class);

		return renderSuccess();
	}
}
