package com.app.component.sysconfig.controller;

import com.app.component.sysconfig.model.SysConfig;
import com.app.component.sysconfig.service.SysConfigService;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.controller.CrudControllerSupport;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.grid.ExGridLoad;
import com.app.framework.core.support.view.grid.Paging;
import com.app.framework.core.utils.request.SessionUtil;
import org.apache.commons.lang.StringUtils;
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 javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * 系统配置管理
 */
@Controller
@RequestMapping("/sys/config")
public class SysConfigController extends CrudControllerSupport {

    @Autowired
    SysConfigService sysConfigService;


    @RequestMapping(value = "/golist")
    public ModelAndView golist(HttpServletRequest request) {
        return new ModelAndView("admin/component/sysconfig/list.html");
    }

    /**
     * 列表配置项
     */
    @RequestMapping(value = "/list")
    public @ResponseBody ExGridLoad list(SysConfig config, Paging paging) {
        List<SysConfig> list = sysConfigService.getPageList(config, paging);
        return ExGridLoad.wrapExGridLoad(list, paging);
    }

    /**
     * 跳转到编辑页面
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit(SysConfig cfg, String editType) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (cfg.getOid() != null) {
            cfg = sysConfigService.getById(cfg.getOid());
        }
        map.put("entity", cfg);
        map.put("editType", StringUtils.isBlank(editType) ? "edit" : editType);
        return new ModelAndView("admin/component/sysconfig/edit.html", map);
    }

    /**
     * 保存配置项
     *
     * @param cfg 配置项
     */
    @RequestMapping(value = "/saveCfg")
    public @ResponseBody AjaxResult saveCfg(HttpServletRequest request, SysConfig cfg) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        sysConfigService.saveCfg(cfg, loginUser);
        return AjaxResult.wrapData(cfg);
    }
}
