package com.huiju.estateagents.service.impl;

import com.alibaba.fastjson.JSONObject;
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.entity.*;
import com.huiju.estateagents.mapper.TaLiveActivityMapper;
import com.huiju.estateagents.mapper.TdLiveDictMapper;
import com.huiju.estateagents.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2020-02-20
 */
@Service
public class TaLiveActivityServiceImpl extends ServiceImpl<TaLiveActivityMapper, TaLiveActivity> implements ITaLiveActivityService {

    private Logger logger = LoggerFactory.getLogger(TaLiveActivityServiceImpl.class);

    @Autowired
    private TaShareContentService taShareContentService;

    @Autowired
    private ITaMiniappService taMiniappService;

    @Autowired
    private IMiniAppService miniAppService;

    @Autowired
    private TaLiveActivityMapper taLiveActivityMapper;

    @Autowired
    private TaPosterServiceImpl taPosterService;

    @Autowired
    private ShareContentServiceImpl shareContentService;

    @Autowired
    private TdPosterTemplateServiceImpl posterTemplateService;

    @Autowired
    private TdLiveDictMapper tdLiveDictMapper;


    @Override
    public ResponseBean taLiveActivityAdd(TaLiveActivity taLiveActivity) {
        logger.info("TaLiveActivityServiceImpl.taLiveActivityAdd 接收参数：" + JSONObject.toJSONString(taLiveActivity));

        ResponseBean responseBean = new ResponseBean();

        taLiveActivity.setVisitNum(0);
        taLiveActivity.setCreateDate(LocalDateTime.now());
        taLiveActivity.setUpdateDate(LocalDateTime.now());
        if (StringUtils.isNotBlank(taLiveActivity.getLiveRoomParam())) {
            taLiveActivity.setLiveAppPath(taLiveActivity.getLiveRoomParam().replace(".html", ""));
        }

        Boolean result = save(taLiveActivity);
        if (!result) {
            responseBean.addError("fail");
            return responseBean;
        }
        QueryWrapper<TaMiniapp> taMiniappQuery = new QueryWrapper<>();
        taMiniappQuery.eq("org_id", taLiveActivity.getOrgId());
        TaMiniapp taMiniapp = taMiniappService.getOne(taMiniappQuery);
        ResponseBean taMiniappQrcode = miniAppService.getQrCode
                (CommConstant.LIVE_ACTIVITY_QRCODE.replace("#0", taLiveActivity.getLiveActivityId().toString())
                        .replace("#1", "live"), taMiniapp.getMiniappId());
        taLiveActivity.setQrCode(String.valueOf(taMiniappQrcode.getData()));
        updateById(taLiveActivity);

        // 设置默认海报数据
        TaShareContent shareContent = new TaShareContent();
        shareContent.setOrgId(taLiveActivity.getOrgId());
        shareContent.setTargetId(taLiveActivity.getLiveActivityId().toString());
        shareContent.setShareContentTitle("直播看房，在线答疑，快上车~");
//        shareContent.setShareContentImg(taLiveActivity.getDetailImg());
        shareContent.setShareContentType(CommConstant.LIVE);
        shareContent.setStatus(CommConstant.STATUS_NORMAL);
        shareContent.setCreateDate(LocalDateTime.now());
        taShareContentService.save(shareContent);

        responseBean.addSuccess(taLiveActivity);
        return responseBean;
    }

    @Override
    public IPage<TaLiveActivity> listLiveActivityByCondition(Integer pageNum, Integer pageSize, Integer orgId, String liveActivityTitle,
                                                             String cityId, String buildingId, Integer status, List<TaPersonBuilding> taPersonBuildingListByUserId,
                                                             Integer userId, Integer source) {
        logger.info("TaLiveActivityServiceImpl.listLiveActivityByCondition 接收参数：pageNum:{},pageSize:{},orgId:{},iveActivityTitle:{},cityId:{},buildingId:{},liveDetailType:{},status:{},source:{}",
                pageNum, pageSize, liveActivityTitle, cityId, buildingId, status, source);

        IPage<TaLiveActivity> pg = new Page<>(pageNum, pageSize);
        return taLiveActivityMapper.selectLiveListByCondition(pg, liveActivityTitle, cityId, buildingId, status, orgId, taPersonBuildingListByUserId, userId, source);
    }

    @Override
    public ResponseBean addVisitNum(String id) {
        ResponseBean responseBean = new ResponseBean();
        Boolean result = taLiveActivityMapper.addVisitNum(id);
        if (result) {
            responseBean.addSuccess("成功");
            return responseBean;
        }
        responseBean.addError("fail");
        return responseBean;
    }

    @Override
    public ResponseBean getLiveActivityDetailById(String id, Integer orgId) {
        logger.info("getLiveActivityDetailById 接收参数：id：{},orgId:{}", id, orgId);

        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaLiveActivity> liveActivityQueryWrapper = new QueryWrapper<>();
        liveActivityQueryWrapper.eq("live_activity_id", id);
        liveActivityQueryWrapper.eq("org_id", orgId);
        TaLiveActivity result = taLiveActivityMapper.selectOne(liveActivityQueryWrapper);
        if (result == null) {
            responseBean.addSuccess(null);
            return responseBean;
        }

        // 获取直播小程序信息
        QueryWrapper<TdLiveDict> tdLiveDictQueryWrapper = new QueryWrapper<>();
        tdLiveDictQueryWrapper.eq("id", result.getLiveApp());
        tdLiveDictQueryWrapper.eq("status", "1");
        TdLiveDict tdLiveDict = tdLiveDictMapper.selectOne(tdLiveDictQueryWrapper);
        if (tdLiveDict == null) {
            responseBean.addSuccess(null);
            return responseBean;
        }
        result.setLiveAppName(tdLiveDict.getLivePlatName());
        result.setLiveAppAppId(tdLiveDict.getLivePlatValue());

        // 获取海报信息
        QueryWrapper<TaPoster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("target_id", id + "");
        queryWrapper.eq("target_type", CommConstant.LIVE);
        queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        List<TaPoster> posterList = taPosterService.list(queryWrapper);

        List<TaPoster> resultPosterList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(posterList)) {
            for (TaPoster poster : posterList) {
                QueryWrapper<TdPosterTemplate> templateQueryWrapper = new QueryWrapper<>();
                templateQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
                templateQueryWrapper.eq("type ", "liveActivity");
                List<TdPosterTemplate> posterTemplate = posterTemplateService.list(templateQueryWrapper);

                poster.setTemplates(posterTemplate);
                resultPosterList.add(poster);
            }
        }

        // 获取分享内容信息
        List<TaShareContent> shareContentList = shareContentService.getPostersForTarget(id + "", CommConstant.LIVE);

        result.setPosters(resultPosterList);
        result.setShareContents(shareContentList);
        responseBean.addSuccess(result);
        return responseBean;
    }

    @Override
    public ResponseBean delLiveActivityList(Integer orgId, List<TaLiveActivity> liveActivityList) {
        ResponseBean responseBean = new ResponseBean();
        taLiveActivityMapper.updateLiveActivityStatus(orgId, liveActivityList);
        return responseBean;
    }

    @Override
    public ResponseBean getDetailById(Integer id) {
        ResponseBean responseBean = new ResponseBean();
        responseBean.addSuccess(taLiveActivityMapper.getDetailById(id));
        return responseBean;
    }
}
