package com.xxfc.platform.uccn.biz;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.xxfc.platform.uccn.dto.SeoDTO;
import com.xxfc.platform.uccn.entity.SEO;
import com.xxfc.platform.uccn.mapper.SEOMapper;
import com.xxfc.platform.uccn.vo.SEOQuery;
import com.xxfc.platform.uccn.vo.SEOVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

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

/**
 * @author Administrator
 */
@Service
@Slf4j
public class SEOBiz extends BaseBiz<SEOMapper, SEO> {

    public PageInfo<SeoDTO> getList(SEOQuery query) {
        PageHelper.startPage(query.getPage(),query.getLimit());
        List<SeoDTO> seodtoList = mapper.getSEODTOList();
        return PageInfo.of(seodtoList);
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean update(SEOVo seoVo)  {

        try {
            if (seoVo==null) {
                return false;
            }
            SEO seo = new SEO();
            BeanUtilsBean.getInstance().copyProperties(seo,seoVo);
            Example example = new Example(SEO.class);
             example.createCriteria().andEqualTo("modelId", seo.getModelId());
            List<SEO> list = mapper.selectByExample(example);
            if (CollectionUtils.isEmpty(list)) {
                seo.setCreTime(new Date());
                mapper.insertSelective(seo);
            }else if (list.size()==1){
                seo.setUpdTime(new Date());
                mapper.updateByPrimaryKeySelective(seo);
            }else {
                log.error("错误!该模块保存有多个seo");
                return false;
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    public SEO getSeoByModelId(Integer modelId) {
        SEO seo = new SEO();
        seo.setModelId(modelId);
        return selectOne(seo);
    }
}
