package cn.hmsoft.frame.control;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hmsoft.application.web.Ajax;
import cn.hmsoft.frame.data.dao.FrameResDao;
import cn.hmsoft.frame.data.model.FrameRes;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.service.FrameResService;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.jdbc.entity.QueryOrder;

@RestController
public class FrameResControl extends FrameControl {

	@Autowired
	private FrameResService sFrameRes;
	@Autowired
	private FrameResDao daoFrameRes;
	
	
	@RequestMapping("frame/res/page")
	public Ajax page(String query, Integer limit, Integer start, String order, String type) {
		// 鉴权
		this.authAdminRole();	
		order = StringHelper.isEmpty(order) ? "res_id" : order;
		return new Ajax(this.daoFrameRes.pageRes(start, limit, query, getQueryOrder(order, type)));
	}
	
	@RequestMapping("frame/res/all")
	public Ajax all() {
		return new Ajax(this.daoFrameRes.all(new QueryOrder("res_id")));
	}

	@RequestMapping("frame/res/find")
	public Ajax find(Integer resId) {
		return new Ajax(this.daoFrameRes.find(resId));
	}

	@RequestMapping("frame/res/add")
	public Ajax add(FrameRes res) {
		this.authAdminRole();
		this.sFrameRes.addRes(res);
		return new Ajax();
	}

	@RequestMapping("frame/res/edit")
	public Ajax edit(FrameRes res) {
		this.authAdminRole();
		this.sFrameRes.editRes(res);
		return new Ajax();
	}
	@RequestMapping("frame/res/delete")
	public Ajax delete(int res_id) {
		this.authAdminRole();
		this.sFrameRes.deleteRes(res_id);
		return new Ajax();
	}
	
	/**
	 * @Description: 同步资源
	 * @date 2023-04-20 10:46:43 
	 */  
	@RequestMapping("frame/res/sync")
	public Ajax syncRes() {
		Properties framePro = null;
		Properties sysPro = null;
		Resource resource = null;
		//读取菜单文件内容
		try {
			ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
			resource = resourceLoader.getResource("classpath:/frame-res.properties");
			framePro = PropertiesLoaderUtils.loadProperties(new EncodedResource(resource, "UTF-8"));
			
			resource = resourceLoader.getResource("classpath:/sys-res.properties");
			sysPro = PropertiesLoaderUtils.loadProperties(new EncodedResource(resource, "UTF-8"));
		} catch (Exception e) {
			throw new BusinessException("配置文件不存在，请在项目根目录下新建sys-res.properties，并配置【 url=ID,菜单名称】 的业务菜单！");
		}
		sFrameRes.syncRes(framePro, sysPro);
		return new Ajax();
	}
	
}
