package com.cku.oa.show.service;

import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.oa.show.dao.CkuMatchRuleDao;
import com.cku.oa.show.entity.CkuMatchRule;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 犬展规范Service
 * @author wj
 * @version 2020-07-10
 */
@Service
@Transactional(readOnly = true)
public class CkuMatchRuleService extends CrudService<CkuMatchRuleDao, CkuMatchRule> {

	public CkuMatchRule get(String id) {
		return super.get(id);
	}

	public List<CkuMatchRule> findList(CkuMatchRule ckuMatchRule) {
		return super.findList(ckuMatchRule);
	}

	public Page<CkuMatchRule> findPage(Page<CkuMatchRule> page, CkuMatchRule ckuMatchRule) {
		return super.findPage(page, ckuMatchRule);
	}

	@Transactional(readOnly = false)
	public void saveCkuMatchRule(CkuMatchRule ckuMatchRule){
        if (StringUtils.isNotBlank(ckuMatchRule.getRuleInfo())) {
            ckuMatchRule.setRuleInfo(StringEscapeUtils.unescapeHtml4(ckuMatchRule.getRuleInfo()));
        }
		CkuMatchRule rule= dao.getOneByCode(ckuMatchRule.getCode());
		if(rule!=null&& !rule.getId().equals(ckuMatchRule.getId())){
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "排序重复。");
		}
		String[] typeArr = ckuMatchRule.getTypeArr();
		for(int i=0; i<typeArr.length;i++){
			List<CkuMatchRule> ruleList = dao.getByType(typeArr[i]+",");
			if(ruleList.size()>30){
				throw new ZAException(ZAErrorCode.ZA_VALID_FAILED,  "类型为"+typeArr[i]+"的犬展规范已经超过30条，请勿重复添加");
			}
		}
		ckuMatchRule.setCreateTime(new Date());
		ckuMatchRule.setType(StringUtils.join(typeArr,",")+",");
        super.save(ckuMatchRule);
	}

	@Transactional(readOnly = false)
	public void delete(CkuMatchRule ckuMatchRule) {
		super.delete(ckuMatchRule);
	}

}