package com.ibeetl.admin.flow.service;

import com.ibeetl.admin.core.service.BaseService;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.flow.dao.DirectedChannelUrlDao;
import com.ibeetl.admin.flow.dao.DirectedFestivalDao;
import com.ibeetl.admin.flow.entity.DirectedChannelUrlEntity;
import com.ibeetl.admin.flow.entity.DirectedFestivalEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DirectedFestivalService extends BaseService<DirectedFestivalEntity> {

    private final Log log = LogFactory.getLog(this.getClass());

    @Autowired
    private DirectedFestivalDao directedFestivalDao;

    @Autowired
    private DirectedChannelUrlDao directedChannelUrlDao;

    public void search(PageQuery<DirectedFestivalEntity> query) {
        PageQuery<DirectedFestivalEntity> ret = directedFestivalDao.searchFestival(query);
        queryListAfter(ret.getList());
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveFestival(DirectedFestivalEntity entity) {
        directedFestivalDao.saveFestival(entity);
    }

    public DirectedFestivalEntity findById(String id) {
        return directedFestivalDao.findById(id);
    }

    public DirectedFestivalEntity findByFescod(String fescod) {
        return directedFestivalDao.findByFescod(fescod);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateFestival(DirectedFestivalEntity entity) {
        DirectedFestivalEntity temp = findById(entity.getId());

        // 删除平价的活动链接
        directedChannelUrlDao.deleteByPromofescod(entity.getFescod());

        // 根据本次的平价渠道生成链接
        if (StringUtils.isEmpty(temp.getParitycode())) {

        }

        directedFestivalDao.updateFestival(entity);


    }

    public List<DirectedFestivalEntity> findAllFestival() {
        return directedFestivalDao.findAllFestival();
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteFesAndChannel(DirectedFestivalEntity entity) {
        List<DirectedChannelUrlEntity> list = directedChannelUrlDao.findByFesAndChannelByFescod(entity.getFescod());

        if (list != null && list.size() > 0) {
            throw new PlatformException("活动配置了渠道链接，不允许删除！");
        }

        directedFestivalDao.deleteFesAndChannel(entity);
    }
}
