package com.nbclass.activity.controller;

import java.util.List;

import javax.annotation.Resource;

import com.nbclass.activity.mapper.DataDictMapper;
import com.nbclass.activity.model.ContentTags;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbclass.activity.model.DataDict;
import com.nbclass.activity.model.DataDictItem;
import com.nbclass.activity.service.DataDictService;
import com.nbclass.exception.ParameterException;
import com.nbclass.system.controller.BaseController;
import com.nbclass.system.model.SysLog;
import com.nbclass.system.model.User;
import com.nbclass.system.model.enums.SysLogType;
import com.nbclass.system.service.SysLogService;
import com.nbclass.util.CommonUtils;
import com.nbclass.util.PageUtil;
import com.nbclass.util.ResultUtil;
import com.nbclass.vo.base.PageResultVo;
import com.nbclass.vo.base.Result;

/**
 * 数据字典
 * @author Leon
 * @datetime 2020年5月28日 下午3:27:43
 */
@Controller
@RequestMapping("/console/datadict")
public class DataDictController extends BaseController {

    @Resource
    private DataDictService service;

    @Resource
    private SysLogService sysLogService;

    @Resource
	private DataDictMapper dataDictMapper;

    /**
     * 列表页面
     * @return
     */
    @GetMapping("/index")
    public String indexPage(){
        return "data_dict/list";
    }

    /**
     * 编辑页面
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/edit")
    public String editPage(Model model, Long id){
    	DataDict entity = new DataDict();
    	if(id!=null && id>0)entity=service.findById(id);
    	JSONObject obj = (JSONObject) JSON.toJSON(entity);
    	model.addAllAttributes(obj);
    	return "data_dict/edit";
    }

    /**
     * 报名用户信息列表
     * @param entity
     * @param limit
     * @param offset
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public PageResultVo getList(DataDict entity, Integer limit, Integer offset){
        PageHelper.startPage(PageUtil.getPageNo(limit, offset),limit);
        List<DataDict> userList = service.getList(entity);
        PageInfo<DataDict> pages = new PageInfo<>(userList);
        return ResultUtil.table(userList,pages.getTotal());
    }

    /**
     * 根据字典ID查询子项列表
     * @param entity
     * @param limit
     * @param offset
     * @return
     */
    @PostMapping("/getItemList")
    @ResponseBody
    public PageResultVo getItemList(DataDictItem entity, Integer limit, Integer offset){
        PageHelper.startPage(PageUtil.getPageNo(limit, offset),limit);
        List<DataDictItem> userList = service.getItemList(entity);
        PageInfo<DataDictItem> pages = new PageInfo<>(userList);
        return ResultUtil.table(userList,pages.getTotal());
    }

    /**
     * i添加或修改记录
     * @param entity
     */
    @PostMapping("/merge")
    @ResponseBody
    public Result merge(DataDict entity){
        String desc = null;
    	if(entity.getId()!=null && entity.getId()>0){
            service.update(entity);
            desc = "修改数据字典，内容为：" + JSON.toJSONString(entity);
        }else{
			int result = dataDictMapper.getDataDicName(entity.getName());
			if(result > 0 ) throw new ParameterException("该字典已存在!");
			service.add(entity);
            desc = "添加数据字典，内容为：" + JSON.toJSONString(entity);
        }
        User user = getLoginUser();
        sysLogService.add(new SysLog(SysLogType.dict.key(), user.getUserId()+"（"+user.getUsername()+"）", getIpAddr(), desc));
        return Result.success();
    }

    /**删除记录*/
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(String ids) {
        List<Long> IdList = CommonUtils.toLongList(ids);
        service.delete(IdList);
        User user = getLoginUser();
        sysLogService.add(new SysLog(SysLogType.dict.key(), user.getUserId()+"（"+user.getUsername()+"）", getIpAddr(), "删除数据字典，ids："+ids));
        return Result.success();
    }

    /**
	 * 根据字典key获取案例标签列表
	 * @param dictKey
	 * @return
	 */
	@RequestMapping("getTagSelect")
	@ResponseBody
	public Result getTagSelect(String dictKey){
		if(StringUtils.isBlank(dictKey)) {
			throw new ParameterException("参数不能为空");
		}
		try {
			List<DataDictItem> obj = service.getItemsByKey(dictKey);
			return Result.success(obj);
		} catch (Exception e) {
			logger.error("getTagSelect异常", e);
			return Result.error("获取数据失败");
		}
	}

	/**
	 * 标签下拉联想获取数据
	 * @param tags
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getTags")
	public JSONArray getCategoryTrees(String dictKey, String tags){
//		if(StringUtils.isBlank(dictKey)) {
//			throw new ParameterException("参数不能为空");
//		}
		JSONArray result = new JSONArray();
		//List<DataDictItem> list = service.getItemsByKey(dictKey);
		List<DataDictItem> list = service.getItemsByKey("other_labels");
		for (DataDictItem entity : list) {
			JSONObject obj = new JSONObject();
			obj.put("id", entity.getId());
			obj.put("value", entity.getName());
			result.add(obj);
		}
		return result;
	}


	/**
	 * 根据字典key获取案例来源列表
	 * @param dictKey
	 * @return
	 */
	@RequestMapping("getCaseFromSelect")
	@ResponseBody
	public Result getCaseFromSelect(String dictKey){
		if(StringUtils.isBlank(dictKey)) {
			throw new ParameterException("参数不能为空");
		}
		try {
			List<DataDictItem> obj = service.getItemsByKey(dictKey);
			return Result.success(obj);
		} catch (Exception e) {
			logger.error("getCaseFromSelect异常", e);
			return Result.error("获取数据失败");
		}
	}


    /**
     * 添加或修改字典子项
     * @param entity
     * @return
     */
    @PostMapping("/mergeDataDictItem")
    @ResponseBody
    public Result mergeDataDictItem(DataDictItem entity){
    	service.mergeDataDictItem(entity);
    	return Result.success();
    }

    /**
     * 删除字典子项
     * @param entity
     * @return
     */
    @PostMapping("/deleteDataDictItem")
    @ResponseBody
    public Result deleteDataDictItem(Long id){
    	service.deleteDataDictItem(id);
    	return Result.success();
    }

	/**
	 * 获取字典值
	 * @return
	 */
	@GetMapping("/getDropDownBox")
	@ResponseBody
	public Result getDropDownBox(){
		List<ContentTags> list = service.getDropDownBox();
		return Result.success(list);
	}

}
