package com.fourdage.system.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fourdage.base.common.JsonResult;
import com.fourdage.base.controller.BaseController;
import com.fourdage.system.entity.DataDictionary;
import com.fourdage.system.service.IDataDictionaryService;

@Controller
@RequestMapping("/admin/dataDictionary")
public class DataDictionaryController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
    private IDataDictionaryService dataDictionaryService;

    @RequestMapping(value = {"/index"})
    public String index(ModelMap modelMap) {
        Page<DataDictionary> page = dataDictionaryService.findAll(getPageRequest());
        modelMap.put("pageInfo", page);
        return "admin/dataDictionary/index";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap map) {
        return "admin/dataDictionary/form";
    }


    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable Integer id, ModelMap map) {
        DataDictionary dataDictionary = dataDictionaryService.find(id);
        map.put("dataDictionary", dataDictionary);
        return "admin/dataDictionary/form";
    }


    @RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult edit(DataDictionary dataDictionary, ModelMap map) {
        try {
        	
        	DataDictionary dbDictionary = dataDictionaryService.findByCodeAndDataKey(dataDictionary.getCode(), dataDictionary.getDataKey());
        	if (dbDictionary != null){
        		return JsonResult.failure("您所输入的数据类型代码和数据键已存在，请修改后再提交！");
        	}
        	dataDictionaryService.saveOrUpdate(dataDictionary);
        } catch (Exception e) {
        	logger.error("系统异常：", e);
            return JsonResult.failure("系统异常："+e);
        }
        return JsonResult.success();
    }
    
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delete(@PathVariable Integer id, ModelMap map) {
        try {
        	dataDictionaryService.delete(id);
        } catch (Exception e) {
        	logger.error("系统异常：", e);
            return JsonResult.failure("系统异常："+e);
        }
        return JsonResult.success();
    }

}
