package com.sptg.ad.biz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.ad.api.dto.AdContentDto;
import com.sptg.ad.api.entity.AdAdsense;
import com.sptg.ad.api.entity.AdContent;
import com.sptg.ad.api.entity.AdContentImg;
import com.sptg.ad.api.entity.AdMaterial;
import com.sptg.ad.biz.mapper.AdContentMapper;
import com.sptg.ad.biz.service.AdAdsenseServiceInterface;
import com.sptg.ad.biz.service.AdContentImgServiceInterface;
import com.sptg.ad.biz.service.AdContentServiceInterface;
import com.sptg.ad.biz.service.AdMaterialServiceInterface;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * title: AdContentServiceImpl
 * package: com.sptg.ad.biz.security.impl
 * description: 广告类容-服务层实现类
 *
 *
 *
 */
@Service
public class AdContentServiceImpl  extends ServiceImpl<AdContentMapper, AdContent> implements AdContentServiceInterface{

    private final AdContentImgServiceInterface adContentImgServiceInterface;
    private final AdMaterialServiceInterface adMaterialServiceInterface;
    private final AdAdsenseServiceInterface adAdsenseServiceInterface;
    @Autowired
    public AdContentServiceImpl(AdContentImgServiceInterface adContentImgServiceInterface,AdMaterialServiceInterface adMaterialServiceInterface,AdAdsenseServiceInterface adAdsenseServiceInterface) {
        this.adContentImgServiceInterface = adContentImgServiceInterface;
        this.adMaterialServiceInterface = adMaterialServiceInterface;
        this.adAdsenseServiceInterface = adAdsenseServiceInterface;
    }




    /**
     * 功能描述:
     * @param
     * @return
     *
     *
     */
    @Override
    public Page<AdContent> showAdContentList(AdContentDto adContentDto){
        //排序字段 时间降序
        adContentDto.getPage().setOrderByField("t_create_date");
        adContentDto.getPage().setAsc(false);
        //构建查询条件
        Wrapper<AdContent> wrapper = new EntityWrapper<>();
        //根据标题查询
        if(StringUtils.isNotBlank(adContentDto.getAdTitle())){
            wrapper.like("c.s_ad_title",adContentDto.getAdTitle());
        }
        //广告编号
        if(StringUtils.isNotBlank(adContentDto.getAdCode())){
            wrapper.like("c.s_ad_code", adContentDto.getAdCode());
        }
        //广告类型
        if(adContentDto.getAdTypeId()!=null){
            wrapper.eq("c.l_ad_type_id", adContentDto.getAdTypeId());
        }
        //是否已经关联素材
        if(adContentDto.getHasMaterial()!=null){
            wrapper.eq("i_has_material", adContentDto.getHasMaterial());
        }
        //线上或线下
        if(adContentDto.getOnlineOrOffline()!=null){
            wrapper.eq("i_online_or_offline", adContentDto.getOnlineOrOffline());
        }
        //排除删除的数据
        wrapper.notIn("c.i_status", OperationConstant.MINUS_ONE);
        //查询本级以及下级广告记录
        wrapper.like("c.s_org_position",adContentDto.getOrgPosition());
        Page<AdContent> page = adContentDto.getPage();
        //xml文件sql查询
        page.setRecords(this.baseMapper.showAdContentList(wrapper,adContentDto.getPage()));
        List<AdContent> list = page.getRecords();
        for (AdContent a:list){
            //获取广告图片
//            List<AdContentImg> adContentImgs = adContentImgServiceInterface.getAdContentImgs(a.getId());
//            a.setAdContentImgs(adContentImgs);

            //获取广告素材
            if(a.getAdMaterialId() != null){
                AdMaterial adMaterial = adMaterialServiceInterface.findAdMaterialById(a.getAdMaterialId());
                if (null != adMaterial) {
                a.setAdMaterial(adMaterial);
                a.setMaterialType(adMaterial.getMaterialType());
                }
            }
            //获取广告位
            if(a.getAdsenseId()!=null){
                AdAdsense adAdsense = adAdsenseServiceInterface.findAdAdsenseById(a.getAdsenseId());
                a.setAdAdsense(adAdsense);
                a.setAdsenseName(adAdsense.getAdsenseName());
            }

        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public ResultBean<Boolean> addAdContent(AdContent adContent){
        //编辑
        if(adContent.getId()!=null){
            //删除之前的图片
            adContentImgServiceInterface.deleteImgByAdContentId(adContent.getId());
        }else{//新增
            //获取时间对象
            Date date = adContent.getCreateDate();
            //获取日期字符串
            String s = new SimpleDateFormat("yyMMdd").format(date);
            Wrapper<AdContent> wrapper = new EntityWrapper<>();
            wrapper.like("s_ad_code",s);
            //排除删除的数据
            wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
            //统计当天新增的广告条数
            int count = this.selectCount(wrapper);
            //广告编号的格式用yyMMdd+2位排序号前面补0
            adContent.setAdCode(s+(count<9?("0"+(count+1)):++count));
        }
        String[] imgUri = adContent.getImgUri();
        //有图片
        if(imgUri!=null && imgUri.length>0){
            adContent.setHasImg(1);
        }else{
            adContent.setHasImg(0);
        }
        boolean result = this.insertOrUpdate(adContent);
        if(result && imgUri!=null && imgUri.length>0){
            adContent.setHasImg(1);
            List<AdContentImg> adContentImgs = new ArrayList<>();
            AdContentImg adContentImg;
            String[] s;
            for(int i=0;i<imgUri.length;i++){
                adContentImg = new AdContentImg();
                adContentImg.setAdId(adContent.getId());
                adContentImg.setSort(i);
                // 图片路径：md5
                s=imgUri[i].split(":");
                adContentImg.setImgUri(s[0]);
                adContentImg.setImgMd5(s[1]);
                adContentImgs.add(adContentImg);
            }
            //保存图片
            adContentImgServiceInterface.addAdContentImg(adContentImgs);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    @Override
    public ResultBean<Boolean> deleteAdContent(String ids) {
        String[] id = ids.split(",");
        if(id!=null && ids.length()>0){
            List<String> list = Arrays.asList(id);
            Wrapper<AdContent> wrapper = new EntityWrapper<>();
            wrapper.in("l_id", list);
            //需要修改状态的广告类型
            AdContent adContent = new AdContent();
            adContent.setStatus(OperationConstant.MINUS_ONE);
            return new ResultBean<>(ResultEnum.SUCCESS, this.update(adContent,wrapper));
        }
        return new ResultBean<>(ResultEnum.ERROR);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public ResultBean<Boolean> deleteAdContentList(AdContentDto adContentDto) {
        List<String> ids = adContentDto.getIds();
        for(String id : ids){
            //  获取账号信息
            AdContent adContent = this.selectById(Long.valueOf(id));
            Assert.notNull(adContent,"记录不存在,请核实后重新操作");
            //  标记为删除状态
            adContent.setStatus(OperationConstant.MINUS_ONE);
            this.updateById(adContent);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,true);
    }

    @Override
    public AdContent findAdContentById(Long id) {
        AdContent adContent = this.selectById(id);
        if(adContent!=null){
             //获取广告对应的图片
             adContent.setAdContentImgs(adContentImgServiceInterface.getAdContentImgs(id));
        }
        return adContent;
    }

    @Override
    public ResultBean<AdContent> getList(AdContentDto adContentDto) {
        //构建查询条件
        Wrapper<AdContent> wrapper = new EntityWrapper<>();
        //根据标题查询
        if(StringUtils.isNotBlank(adContentDto.getAdTitle())){
            wrapper.like("s_ad_title",adContentDto.getAdTitle());
            //匹配输入类容是否是数字
            Pattern pattern = compile("^[-\\+]?[\\d]*$");
            boolean result = pattern.matcher(adContentDto.getAdTitle()).matches();
            if(result){
                //广告编号
                wrapper.or().like("s_ad_code", adContentDto.getAdTitle()).and();
            }
        }
        if (adContentDto.getOnlineOrOffline() != null) {
            wrapper.eq("i_online_or_offline", adContentDto.getOnlineOrOffline());
        }
        //排除删除的数据
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        //排序字段 时间降序
        wrapper.orderBy("t_create_date", false);
        //查询本级以及下级广告记录
        wrapper.like("s_org_position",adContentDto.getOrgPosition());
        List<AdContent> adContentList = this.selectList(wrapper);
        if(adContentDto.getMaterialType() != null){
            for(int i=0;i<adContentList.size();i++){
                AdContent adContent = adContentList.get(i);
                if (adContent.getAdMaterialId() != null) {
                    AdMaterial adMaterial = adMaterialServiceInterface.findAdMaterialById(adContent.getAdMaterialId());
                    if (adMaterial != null) {
                        if(adMaterial.getMaterialType().equals(adContentDto.getMaterialType())){
                            continue;
                        }else{
                            adContentList.remove(i);
                            i--;
                        }
                    }else{
                        adContentList.remove(i);
                        i--;
                    }
                } else {
                    adContentList.remove(i);
                    i--;
                }
            }
        }
        return new ResultBean<>(ResultEnum.SUCCESS, adContentList);
    }

    @Override
    public void updateOrgPosition(String oldPosition, String newPosition) {
        this.baseMapper.updateOrgPosition(oldPosition,newPosition);
    }

}
