package cn.hmsoft.frame.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hmsoft.frame.data.dao.FrameReportDao;
import cn.hmsoft.frame.data.model.FrameReport;
import cn.hmsoft.frame.data.model.FrameReportDetail;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.util.FrameAssertUtil;

@Service
public class FrameReportService extends FrameService {

	@Autowired
	private FrameReportDao frameReportDao;

	public void addReport(FrameReport report, List<FrameReportDetail> detailArr) {
		FrameAssertUtil.isNotEmpty(report.getReport_name(), "报表名称为空");
		report.setReport_name(report.getReport_name().trim());
		FrameReport tr = this.frameReportDao.find("report_name", report.getReport_name());
		FrameAssertUtil.isNull(tr, "报表名称 " + report.getReport_name() + " 已经存在，请重新输入");
		this.checkSql(report.getReport_sql());
		this.frameReportDao.insert(report);
		for (FrameReportDetail detail : detailArr) {
			this.frameReportDao.insert(detail);
		}
	}

	public void editReport(FrameReport report, List<FrameReportDetail> detailArr) {
		FrameAssertUtil.isNotEmpty(report.getReport_name(), "报表名称为空");
		this.checkSql(report.getReport_sql());
		this.frameReportDao.update(report);
		this.frameReportDao.deleteDetail(report.getReport_name());
		for (FrameReportDetail detail : detailArr) {
			this.frameReportDao.insert(detail);
		}
	}

	public void deleteReport(String report_name) {
		this.frameReportDao.delete(report_name);
		this.frameReportDao.deleteDetail(report_name);
	}

	private void checkSql(String v) {
		v = v.toLowerCase();
		if (v.indexOf("update ") > -1 || v.indexOf("drop ") > -1 || v.indexOf("create ") > -1
				|| v.indexOf("insert ") > -1 || v.indexOf("truncate ") > -1 || v.indexOf("delete ") > -1)
			throw new BusinessException("检查到SQL注入，禁止此操作！");
	}

}
