package com.huiju.estateagents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.BeanTools;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.exception.EstaException;
import com.huiju.estateagents.mapper.TaFavorMapper;
import com.huiju.estateagents.mapper.TaNewsMapper;
import com.huiju.estateagents.mapper.TaSaveMapper;
import com.huiju.estateagents.service.*;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 资讯表  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-07-25
 */
@Service
public class TaNewsServiceImpl extends ServiceImpl<TaNewsMapper, TaNews> implements ITaNewsService {

    @Autowired
    private ITaNewsTypeService iTaNewsTypeService;

    @Autowired
    private ITaBuildingService iTaBuildingService;

    @Autowired
    private TaFavorMapper taFavorMapper;

    @Autowired
    private TaNewsMapper taNewsMapper;

    @Autowired
    private TaSaveMapper taSaveMapper;

    @Autowired
    private TaPosterService taPosterService;

    @Autowired
    private TaShareContentService taShareContentService;


    @Override
    public ResponseBean getList(Integer pageNum, Integer pageSize, String buildingId, Integer orgId, Integer newsTypeId, Integer newsStatus,String title, Integer cityId,List<TaPersonBuilding> personBuildingList) {
        ResponseBean responseBean = new ResponseBean();

        IPage<TaNews> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        QueryWrapper<TaNews> taNewsQueryWrapper = new QueryWrapper<>();
        taNewsQueryWrapper.eq(!StringUtils.isEmpty(buildingId),"building_id", buildingId);
        taNewsQueryWrapper.eq(orgId != null,"org_id", orgId);
        taNewsQueryWrapper.eq(newsTypeId != null,"news_type_id", newsTypeId);
        taNewsQueryWrapper.eq(newsStatus != null, "news_status", newsStatus);
        taNewsQueryWrapper.eq("status", 1);
        taNewsQueryWrapper.eq(cityId != null, "city_id", cityId);
        taNewsQueryWrapper.like(title!=null,"news_name", title);
        taNewsQueryWrapper.in(personBuildingList.size() > 0,"building_id",personBuildingList.stream().map(TaPersonBuilding::getBuildingId).collect(Collectors.toList()));
        taNewsQueryWrapper.orderByAsc("news_status");
        taNewsQueryWrapper.orderByDesc("weight","create_date");
        IPage<TaNews> taNewsIPage = this.page(page, taNewsQueryWrapper);

        injectType(taNewsIPage.getRecords());

        responseBean.addSuccess(taNewsIPage);
        return responseBean;
    }

    private void injectType(List<TaNews> records) {
        records.forEach(e -> {
            TaNewsType newsType = iTaNewsTypeService.getById(e.getNewsTypeId());
            e.setNewsType(newsType);
        });
    }

    @Override
    public ResponseBean getTaNewsById(Integer newsId) {
        ResponseBean responseBean = new ResponseBean();
        if (null == newsId) {
            responseBean.addError("编号不能为空！");
        }
        TaNews data = this.getById(newsId);
        data.setPosters(taPosterService.getPostersForTarget(newsId.toString(),CommConstant.POSTER_CONTENT_TYPE_NEWS));
        data.setShareContents(taShareContentService.getPostersForTarget(newsId.toString(),CommConstant.POSTER_CONTENT_TYPE_NEWS));
        responseBean.addSuccess(data);
        return  responseBean;
    }

    @Override
    public ResponseBean updateTaNews(TaNews taNews) {
        ResponseBean responseBean = new ResponseBean();
        TaNews oldNews = this.getById(taNews.getNewsId());
        if (null == oldNews) {
            responseBean.addError("资讯不存在！");
            return responseBean;
        }

        //-- 校验 公司，楼盘，资讯类型
        check(taNews);

        BeanTools.copyProperties(taNews, oldNews);
        this.updateById(oldNews);
        responseBean.addSuccess(oldNews);
        return responseBean;
    }

    @Override
    public ResponseBean addTaNews(TaNews taNews) {
        ResponseBean responseBean = new ResponseBean();
        check(taNews);

        taNews.setCreateDate(LocalDateTime.now());
        taNews.setStatus(1);
        taNews.setNewsStatus(1);
        this.save(taNews);
        responseBean.addSuccess(taNews);
        return responseBean;
    }

    private void check(TaNews taNews) {
        //-- 校验 公司，楼盘，资讯类型
        // TODO 公司校验没有写 taNews.getOrgId()

        TaBuilding taBuilding = iTaBuildingService.getById(taNews.getBuildingId());
        if (null == taBuilding) {
            throw new EstaException("楼盘不存在！");
        }
        TaNewsType taNewsType = iTaNewsTypeService.getById(taNews.getNewsTypeId());
        if (null == taNewsType) {
            throw new EstaException("资讯类型不存在！");
        }
    }

    @Override
    public ResponseBean deleteTaNews(Integer newsId) {
        ResponseBean responseBean = getTaNewsById(newsId);
        if (1 == responseBean.getCode()) {
            return responseBean;
        }
        TaNews taNews = (TaNews) responseBean.getData();
        if (null == taNews) {
            responseBean.addError("数据不存!");
        }

        // 修改状态
        taNews.setStatus(0);
        this.updateById(taNews);

        responseBean.addSuccess(taNews);
        return responseBean;
    }

    @Override
    public ResponseBean getWxTaNewsById(Integer newsId,String personId) {
        ResponseBean responseBean = getTaNewsById(newsId);
        if (1 == responseBean.getCode()) {
            return responseBean;
        }
        TaNews taNews = (TaNews) responseBean.getData();
        if (null == taNews) {
            responseBean.addError("数据不存!");
        }else {
            QueryWrapper<TaSave> saveQueryWrapper = new QueryWrapper<>();
            saveQueryWrapper.eq("tagert_type", CommConstant.FAVOR_NEWS);
            saveQueryWrapper.eq("person_id",personId);
            saveQueryWrapper.eq("saved_target",taNews.getNewsId());
            Integer num = taSaveMapper.selectCount(saveQueryWrapper);
            if (num>0){
                taNews.setIsSave(CommConstant.STATUS_NORMAL);
            }else {
                taNews.setIsSave(CommConstant.STATUS_UNACCALIMED);
            }
        }

        responseBean.addSuccess(taNews);
        return responseBean;
    }

    @Override
    public ResponseBean wxTaPvNum(Integer id) {
        ResponseBean responseBean = getTaNewsById(id);
        if (1 == responseBean.getCode()) {
            return responseBean;
        }
        TaNews taNews = (TaNews) responseBean.getData();
        if (null == taNews) {
            responseBean.addError("数据不存!");
        }

        taNewsMapper.setFieldNum(String.valueOf(id), "pv_num", 1);

        responseBean.addSuccess((Object)"");
        return responseBean;
    }

    @Override
    public IPage<TaNews> getWxList(Integer pageNum, Integer pageSize, String buildingId, List<String> targets,Integer cityId,boolean mine,Integer orgId) {
        IPage<TaNews> page = new Page<>(pageNum, pageSize);

        QueryWrapper<TaNews> taNewsQueryWrapper = new QueryWrapper<>();
        taNewsQueryWrapper.eq(!StringUtils.isEmpty(buildingId), "building_id", buildingId);
        taNewsQueryWrapper.in(null != targets && targets.size() > 0, "news_id", targets);
        taNewsQueryWrapper.eq(null != cityId && cityId != 0,"city_id",cityId);
        taNewsQueryWrapper.eq("org_id",orgId);
        taNewsQueryWrapper.eq("status", 1);
        taNewsQueryWrapper.eq("news_status", 0);
        taNewsQueryWrapper.orderByDesc("weight","create_date");
        IPage<TaNews> taNewsIPage = this.page(page, taNewsQueryWrapper);
        IPage<TaNews> pageEmpty = new Page<>(pageNum, pageSize);
        injectType(taNewsIPage.getRecords());
        if (targets.size()<=0 && mine){
            return pageEmpty;
        }else {
            return taNewsIPage;
        }

    }
}
