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

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.estate.api.dto.NoticePushDto;
import com.sptg.estate.api.dto.UserDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.biz.mapper.NoticePushMapper;
import com.sptg.estate.biz.service.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * title: NoticeServiceImpl
 * package: com.sptg.estate.biz.security.impl
 * description: 公告发布-服务层实现层
 *
 *
 *
 */
@Service
@AllArgsConstructor
public class NoticePushServiceImpl extends ServiceImpl<NoticePushMapper, NoticePush> implements NoticePushServiceInterface {

    private final NoticeServiceInterface noticeServiceInterface;
    private final NoticePushDetailsServiceInterface noticePushDetailsServiceInterface;
    private final NoticeImgServiceInterface noticeImgServiceInterface;
    private final NoticePushImgServiceInterface noticePushImgServiceInterface;
    private final ResidentialServiceInterface residentialServiceInterface;

    @Override
    public Page<NoticePush> showNoticePushList(NoticePushDto noticePushDto) {
        Page<NoticePush> page=noticePushDto.getPage();
        EntityWrapper<NoticePush> wrapper=new EntityWrapper<NoticePush>();
        //公告条件
        Notice notice= noticePushDto.getNotice();
        //标题
        String title="";
        //编号
        String code="";
        if(notice!=null){
            title=notice.getTitle();
            code=notice.getCode();
        }

        //开始时间条件
        Date startDateCondition=noticePushDto.getStartDateCondition();
        //结束时间条件
        Date endDateCondition=noticePushDto.getEndDateCondition();
        //发布状态
        Integer pushStatus=noticePushDto.getPushStatus();
        //机构
        Long orgId=noticePushDto.getOrgId();
        //根机构
        Long rootOrgId=noticePushDto.getRootOrgId();
        //机构位置
        String orgPosition=noticePushDto.getOrgPosition();

        if(StringUtils.isNotBlank(title)) {
            wrapper.like("n.s_title", title);
        }
        if(StringUtils.isNotBlank(code)){
            wrapper.like("n.s_code",code);
        }
        if(startDateCondition!=null){
            wrapper.ge("np.t_push_date",startDateCondition);
        }
        if(endDateCondition!=null){
            wrapper.le("np.t_push_date",endDateCondition);
        }
        if(pushStatus!=null){
            wrapper.eq("np.i_push_status",pushStatus);
        }
        //正常状态
        wrapper.eq("np.i_status", OperationConstant.ZERO);
        if(orgId!=null){
            wrapper.eq("np.l_org_id",orgId);
        }
        if(rootOrgId!=null){
            wrapper.eq("np.l_root_org_id",rootOrgId);
        }
        if(StringUtils.isNotBlank(orgPosition)){
            wrapper.like("np.s_org_position",orgPosition, SqlLike.RIGHT);
        }
        //分页查询
        List<NoticePush> noticePushList=this.baseMapper.showNoticePushList(page,wrapper);
        page.setRecords(noticePushList);
        return page;
    }
    @Override
    public NoticePush findNoticePushById(long id) {
        NoticePush noticePush = this.baseMapper.findNoticePushById(id);
        //查询 小区/单元/设备/区域 详细信息
        if(noticePush!=null){
            List<NoticePushDetails> noticePushDetailsList = noticePushDetailsServiceInterface.getListByNoticePushId(id);
            noticePush.setNoticePushDetailsList(noticePushDetailsList);
        }
        return noticePush;
    }
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Long addNoticePush(NoticePush noticePush){
        Long noticeId=noticePush.getNoticeId();
        if(noticeId==null){
            return null;
        }
        Notice notice = noticeServiceInterface.findNoticeById(noticeId);
        if(notice==null){
            return null;
        }
        //公告标题
        noticePush.setNoticeTitle(notice.getTitle());
        //公告内容
        noticePush.setNoticeContent(notice.getContent());
        boolean result= this.insert(noticePush);
        if(result){
            //保存公告发布，小区/单元/设备/区域 发布类型存储对应的id
            Long []fkIds=noticePush.getFkIds();
            if(fkIds!=null){
                List<NoticePushDetails> noticePushDetailsList=new ArrayList<NoticePushDetails>();
                for(Long fkId:fkIds){ //fkId可能是小区ID，单元ID，设备ID，或者是区域ID
                    NoticePushDetails noticePushDetails=new NoticePushDetails();
                    noticePushDetails.setNoticePushId(noticePush.getId());
                    noticePushDetails.setFkId(fkId);
                    noticePushDetailsList.add(noticePushDetails);
                }
                noticePushDetailsServiceInterface.insertBatch(noticePushDetailsList);
            }
            //保存公布发布图片
            EntityWrapper<NoticeImg> wrapper=new EntityWrapper<NoticeImg>();
            wrapper.eq("l_notice_id",noticePush.getNoticeId());
            List<NoticeImg> noticeImgList=noticeImgServiceInterface.selectList(wrapper);
            if(noticeImgList!=null&&!noticeImgList.isEmpty()) {
                List<NoticePushImg> noticePushImgList=new ArrayList<NoticePushImg>();
                noticeImgList.forEach(img-> {
                    NoticePushImg noticePushImg=new NoticePushImg();
                    noticePushImg.setNoticePushId(noticePush.getId());
                    noticePushImg.setSort(img.getSort());
                    noticePushImg.setImgUri(img.getImgUri());
                    noticePushImg.setImgMd5(img.getImgMd5());
                    noticePushImgList.add(noticePushImg);
                });
                noticePushImgServiceInterface.insertBatch(noticePushImgList);
            }
            return noticePush.getId();
        }
        return null;
    }
    @Override
    public boolean updatePushStatus(long id,int pushStatus){
        int count=this.baseMapper.updatePushStatus(id,pushStatus);
        return count>0?true:false;
    }

    @Override
    public List<NoticePush> getListByUser(UserDto userDto) {
        //构建查询条件
        EntityWrapper<NoticePush> wrapper=new EntityWrapper<>();
        Date date = new Date();
        //有效期结束时间大于等于当前时间
        wrapper.ge("p.t_end_date",date);
        //有效期开始时间小于当前等于当前时间
        wrapper.le("p.t_start_date",date );
        //发布目标渠道  1-app 2-小程序,
        wrapper.like("p.s_push_target", userDto.getPushTarget());
        List<User> users = userDto.getList();
        //查询条件
        List<Long> ids = new ArrayList<>();
        List<Long> regionIds = new ArrayList<>();
        Residential residential;
        for(User user:users){
            ids.add(user.getResidentialId());
            ids.add(user.getUnitId());
            residential = this.residentialServiceInterface.selectById(user.getResidentialId());
            regionIds.add(Long.valueOf(residential.getRegionProvince()));
            regionIds.add(Long.valueOf(residential.getRegionCity()));
            regionIds.add(Long.valueOf(residential.getRegionArea()));
        }
        int pageSize = userDto.getPage().getSize();
        int pageNum = (userDto.getPage().getCurrent()-1)*pageSize;
        List<NoticePush> list = this.baseMapper.getListByUser(wrapper,ids,regionIds,pageSize,pageNum);
        return list;
    }
}
