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.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.event.EventBus;
import com.huiju.estateagents.mapper.*;
import com.huiju.estateagents.service.ITaShareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户访问表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-05-10
 */
@Service
public class TaShareServiceImpl extends ServiceImpl<TaShareMapper, TaShare> implements ITaShareService {
    @Autowired
    TaPersonMapper taPersonMapper;

    @Autowired
    TaShareMapper taShareMapper;

    @Autowired
    TaShareCountMapper taShareCountMapper;

    @Autowired
    private TaBuildingMapper taBuildingMapper;

    @Autowired
    private TaBuildingDynamicMapper taBuildingDynamicMapper;

    @Autowired
    private TaNewsMapper newsMapper;

    @Autowired
    private TaSalesBatchMapper taSalesBatchMapper;

    @Autowired
    private TaLiveActivityMapper taLiveActivityMapper;

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public ResponseBean saveData(String openid, String typeOf, String id) {
        List<TaPerson> persons = getPersonsByOpenId(openid);
        if (null == persons || persons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson taPerson = persons.get(0);
        // 如果是分享活动, 则活动 + 1
        if (typeOf.equals(CommConstant.FAVOR_ACTIVITY)) {
            QueryWrapper<TaBuildingDynamic> taBuildingDynamicQuery= new QueryWrapper<>();
            taBuildingDynamicQuery.eq("dynamic_id",id);
            TaBuildingDynamic taBuildingDynamic = taBuildingDynamicMapper.selectOne(taBuildingDynamicQuery);
            taBuildingDynamicMapper.updateById( taBuildingDynamic.setShareNum(taBuildingDynamic.getShareNum() == null ? 1:taBuildingDynamic.getShareNum()+1));
        }

        TaShareCount taShareCount = new TaShareCount();
        taShareCount.setBeShare(id);
        taShareCount.setCreateDate(LocalDateTime.now());
        taShareCount.setPersonId(taPerson.getPersonId());
        taShareCount.setTagertType(typeOf);
        taShareCount.setOrgId(taPerson.getOrgId());
        int countRow = taShareCountMapper.insert(taShareCount);
        if (countRow < 1) {
            return ResponseBean.error("分享增加失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        QueryWrapper<TaShare> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("person_id", taPerson.getPersonId());
        queryWrapper.eq("be_share", id);
        queryWrapper.eq("tagert_type", typeOf);
        List<TaShare> uvs = taShareMapper.selectList(queryWrapper);
        if (null != uvs && uvs.size() > 0) {
            //更新分享为最新时间
            TaShare taShare = new TaShare();
            taShare.setCreateDate(LocalDateTime.now());
            taShareMapper.update(taShare, queryWrapper);
            return ResponseBean.success("");
        }

        TaShare taShare = new TaShare();
        taShare.setBeShare(id);
        taShare.setCreateDate(LocalDateTime.now());
        taShare.setNameOrnick(taPerson.getNickname());
        taShare.setPersonId(taPerson.getPersonId());
        taShare.setPhotoOravatar(taPerson.getAvatarurl());
        taShare.setTagertType(typeOf);

        int row = taShareMapper.insert(taShare);
        if (row < 1) {
            return ResponseBean.error("分享增加失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        // 如果是分享置业, 则人员分享 + 1
        if (typeOf == CommConstant.FAVOR_CONSULTANT) {
            taPersonMapper.setFieldIncrement(id,"share_num", 1);
        }

        if(typeOf.equals(CommConstant.FAVOR_PROJECT)) {
            taBuildingMapper.setFieldNum(id, "share_num", 1);
        }

        if(typeOf.equals("card")){
            taPersonMapper.setFieldNum(id, "share_num", 1);
        }

        if(typeOf.equals(CommConstant.FAVOR_ACTIVITY)){
            taPersonMapper.setFieldNum(id, "share_num", 1);
        }

        if(typeOf.equals(CommConstant.FAVOR_NEWS)){
            newsMapper.setFieldNum(id,"share_num",1);
        }

        return ResponseBean.success("");
    }

    @Override
    public ResponseBean getListOf(String id, String typeOf, Integer pageNumber, Integer pageSize) {
        IPage<TaShare> page = new Page(pageNumber, pageSize);
        QueryWrapper<TaShare> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("be_share", id);
        queryWrapper.eq("tagert_type", typeOf);
        queryWrapper.orderByDesc("create_date");

        IPage<TaShare> result = taShareMapper.selectPage(page, queryWrapper);
        return ResponseBean.success(result);
    }

    @Override
    public ResponseBean selectHouseShareList(Integer pageNum, Integer pageSize, Integer orgId, String personType, String shareType, String phone, Integer saleBatchId) {
        Page page = new Page(pageNum,pageSize);
        // 分页查询
        List<TaShare> list = taShareMapper.selectHouseShareList(page, orgId, personType, shareType, phone, saleBatchId);
        TaSalesBatch taSalesBatch = taSalesBatchMapper.selectById(saleBatchId);
        list.forEach(e -> {
            e.setSalesBatchName(taSalesBatch.getSalesBatchName());
        });
        page.setRecords(list);
        return ResponseBean.success(page);
    }

    @Override
    public void makeSure(String openid, String typeOf, String id, Integer orgId) {
        // 查找分享记录
        TaShare taShare = taShareMapper.selectById(id);
        if (null == taShare) {
            return;
        }

        // 记录分享人
        TaPerson shareUsr = taPersonMapper.getById(taShare.getPersonId());
        if (null == shareUsr) {
            return;
        }

        // 如果分享人没有授权手机号
        if (StringUtils.isEmpty(shareUsr.getPhone()) && StringUtils.isEmpty(shareUsr.getTel())) {
            return;
        }

        // 查找打开人
        List<TaPerson> persons = taPersonMapper.getPersonByOpenId(openid);
        if (null == persons || persons.size() == 0) {
            return;
        }
        TaPerson openUsr = persons.get(0);

        // 如果打开人员与分享人员是同一个人
        // 此处通过 personId 来判断，其实并不准确
        // todo
        if (openUsr.getPersonId().equals(shareUsr.getPersonId())) {
            return;
        }

        taShare.setOpenUser(openUsr);

        // 赠送积分
        // 发放分享积分
        if (typeOf.equals(CommConstant.FAVOR_PROJECT)){
            applicationContext.publishEvent(new EventBus(taShare, EventBus.EventType.SharePoster, orgId));
        }
    }

    @Override
    public ResponseBean listLiveShare(Integer pageNum, Integer pageSize, Integer orgId, String personType, String shareType, String phone, Integer liveActivityId) {
        Page page = new Page(pageNum,pageSize);
        // 分页查询
        List<TaShare> list = taShareMapper.listLiveShare(page, orgId, personType, shareType, phone, liveActivityId);
        TaLiveActivity taLiveActivity = taLiveActivityMapper.selectById(liveActivityId);
        list.forEach(e -> {
            e.setLiveActivityTitle(taLiveActivity.getLiveActivityTitle());
        });
        page.setRecords(list);
        return ResponseBean.success(page);
    }

    @Override
    public List<Map<String, Object>> statTopShare(Integer orgId, String targetType, String targetId, Integer top, String beginDate, String endDate) {
        return taShareMapper.statTopShare(orgId, targetType, targetId, top, beginDate, endDate);
    }

    List<TaPerson> getPersonsByOpenId(String openid) {
        return taPersonMapper.getPersonByOpenId(openid);
    }
}
