package com.ylcm.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ylcm.sys.domain.AdTheatre;
import com.ylcm.sys.domain.AdTheatreTv;
import com.ylcm.sys.form.AdTheatreForm;
import com.ylcm.sys.mapper.AdTheatreMapper;
import com.ylcm.sys.service.AdTheatreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylcm.sys.service.AdTheatreTvService;
import com.ylcm.sys.service.AdTheatreTvStatService;
import com.ylcm.sys.vo.AdTheatreVO;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.List;

/**
 * <p>
 * 剧场管理表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-07-01
 */
@Slf4j
@Service
public class AdTheatreServiceImpl extends ServiceImpl<AdTheatreMapper, AdTheatre> implements AdTheatreService {

    @Resource
    private AdTheatreMapper adTheatreMapper;
    @Resource
    private AdTheatreTvService adTheatreTvService;
    @Resource
    private AdTheatreTvStatService adTheatreTvStatService;

    @Override
    public IPage<AdTheatreVO> page(IPage<AdTheatre> page, AdTheatreForm form) {
        form.trim();
        return adTheatreMapper.getListByCondition(page, form);
    }

    @Override
    public AdTheatre getUniqu(AdTheatre params) {
        LambdaQueryWrapper<AdTheatre> queryWrapper = new LambdaQueryWrapper<AdTheatre>();
        queryWrapper.eq(AdTheatre::getName, params.getName().trim())
                .eq(AdTheatre::getMediaName, params.getMediaName().trim())
                .eq(AdTheatre::getMediaNum, params.getMediaNum())
                .eq(AdTheatre::getShowDate, params.getShowDate())
                .eq(AdTheatre::getShowTime, params.getShowTime());
        if (params.getType() == null){
            queryWrapper.isNull(AdTheatre::getType);
        } else {
            queryWrapper.eq(AdTheatre::getType, params.getType());
        }
        if (StringUtils.isBlank(params.getTypeName())){
            queryWrapper.and(wrapper -> wrapper.isNull(AdTheatre::getTypeName)
                    .or().eq(AdTheatre::getTypeName, ""));
        } else {
            queryWrapper.eq(AdTheatre::getTypeName, params.getTypeName().trim());
        }
        queryWrapper.last("LIMIT 1");
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchAdd(List<AdTheatre> list, List<AdTheatreTv> tvList) throws Exception {
        if (list.size() != tvList.size()){
            throw new Exception("批量新增error：剧场ListSize != 收视率ListSize");
        }
        for (int i = 0; i < list.size(); i++){
            /*
             * insert 剧场数据
             */
            AdTheatre record = list.get(i);
            AdTheatre old = getUniqu(record);
            if (old != null) {
                throw new Exception("第"+ (i + 3) + "行数据重复");
            }
            baseMapper.insert(record);

            /*
             * insert 电视剧收视率数据
             */
            AdTheatreTv theatreTv = tvList.get(i);
            theatreTv.setAdTheatreId(record.getId());
            adTheatreTvService.add(theatreTv);
        }
        return "ok";
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String deleteById(Integer id) {
        AdTheatre adTheatre = baseMapper.selectById(id);
        baseMapper.deleteById(id);
        adTheatreTvService.removeById(id);
        adTheatreTvStatService.saveStatByTheatreTv(adTheatre);
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpd(AdTheatre adTheatre) {
        if (adTheatre.getId() == null) {
            baseMapper.insert(adTheatre);
            // 创建“电视剧数据”记录
            AdTheatreTv adTheatreTv = new AdTheatreTv();
            adTheatreTv.setAdTheatreId(adTheatre.getId());
            adTheatreTvService.add(adTheatreTv);
        } else {
            AdTheatre old = baseMapper.selectById(adTheatre.getId());
            baseMapper.updateById(adTheatre);
            adTheatreTvStatService.saveStatByTheatreTv(old);
        }

        adTheatreTvStatService.saveStatByTheatreTv(adTheatre);
    }

    @Override
    public void updateProductName(Integer type, String oldName, String newName) {
        AdTheatre adTheatre = new AdTheatre();
        adTheatre.setTypeName(newName);

        LambdaQueryWrapper<AdTheatre> queryWrapper = new LambdaQueryWrapper<AdTheatre>();
        queryWrapper.eq(AdTheatre::getTypeName, oldName);
        queryWrapper.eq(AdTheatre::getType, type);
        baseMapper.update(adTheatre, queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateTvName(String oldName, String newName,
            String newFirstTheme, String oldFirstTheme, String newSecondTheme) {
        log.info("修改了剧名 或者 题材 {}, {}, {}, {}", oldName, newName, newFirstTheme, newSecondTheme);

        AdTheatre adTheatre = new AdTheatre();
        adTheatre.setName(newName);
        adTheatre.setFirstTheme(newFirstTheme);
        adTheatre.setSecondTheme(newSecondTheme);
        
        LambdaQueryWrapper<AdTheatre> queryWrapper = new LambdaQueryWrapper<AdTheatre>();
        queryWrapper.eq(AdTheatre::getName, oldName);
        // 更新adTheatre
        baseMapper.update(adTheatre, queryWrapper);

        // 更新adTheatreStat
        adTheatreTvStatService.batchUpdateByName(newName, oldName, newFirstTheme, oldFirstTheme, newSecondTheme);
    }

    @Override
    public void updateMediaName(String oldName, String newName) {
        AdTheatre adTheatre = new AdTheatre();
        adTheatre.setMediaName(newName);

        LambdaQueryWrapper<AdTheatre> queryWrapper = new LambdaQueryWrapper<AdTheatre>();
        queryWrapper.eq(AdTheatre::getMediaName, oldName);
        baseMapper.update(adTheatre, queryWrapper);
        
    }

    @Cacheable(value = "TheatreAnalysis",keyGenerator = "cacheKeyGenerator")
    @Override
    public int countTvNum(String name, String mediaName, String startDate, String endDate) {
        return baseMapper.countTvNum(name, mediaName, startDate, endDate);
    }

    @Cacheable(value = "TheatreAnalysis",keyGenerator = "cacheKeyGenerator")
    @Override
    public int countThemeNum(String firstTheme, String mediaName, String timeQuery, String startDate, String endDate) {
        return baseMapper.countThemeNum(firstTheme, mediaName, timeQuery, startDate, endDate);
    }
}
