package com.huiju.estateagents.drainage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.CommonUtils;
import com.huiju.estateagents.common.DateUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.drainage.entity.TaDrainage;
import com.huiju.estateagents.drainage.mapper.TaDrainageMapper;
import com.huiju.estateagents.drainage.service.ITaDrainageService;
import com.huiju.estateagents.entity.TaMiniapp;
import com.huiju.estateagents.mapper.TaMiniappMapper;
import com.huiju.estateagents.redpack.entity.TaH5Template;
import com.huiju.estateagents.redpack.entity.TaRedPacket;
import com.huiju.estateagents.redpack.mapper.TaH5TemplateMapper;
import com.huiju.estateagents.redpack.service.ITaRedPacketService;
import com.huiju.estateagents.sample.entity.TaH5Sample;
import com.huiju.estateagents.sample.mapper.TaH5SampleMapper;
import com.huiju.estateagents.service.IMiniAppService;
import com.huiju.estateagents.third.entity.TaThirdPartyMiniappConfig;
import com.huiju.estateagents.third.service.ITaThirdPartyMiniappConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 引流项目  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-10-18
 */
@Service
public class TaDrainageServiceImpl extends ServiceImpl<TaDrainageMapper, TaDrainage> implements ITaDrainageService {

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

    @Autowired
    private TaDrainageMapper taDrainageMapper;

    @Autowired
    private TaMiniappMapper taMiniappMapper;

    @Autowired
    private IMiniAppService miniAppService;

    @Autowired
    private ITaRedPacketService iTaRedPacketService;

    @Autowired
    private ITaThirdPartyMiniappConfigService iTaThirdPartyMiniappConfigService;

    @Autowired
    private TaH5SampleMapper taH5SampleMapper;

    @Autowired
    private TaH5TemplateMapper taH5TemplateMapper;

    @Override
    public void updateDrainageToEnd() {
        taDrainageMapper.updateDrainageToEnd();
    }

    @Override
    public ResponseBean saveDrainage(TaDrainage taDrainage, Integer orgId, Integer userId) {
        ResponseBean responseBean = new ResponseBean();

        // 1.保存H5活动信息
        taDrainage.setOrgId(orgId);
        taDrainage.setCreateUser(userId);
        taDrainage.setCreateDate(LocalDateTime.now());
        taDrainage.setStatus(CommConstant.STATUS_UNACCALIMED);
        if (DateUtils.dayToLocalDateime(taDrainage.getEndDate()).isAfter(LocalDateTime.now())) {
            taDrainage.setStatus(CommConstant.STATUS_NORMAL);
        }
        Boolean saveResult = save(taDrainage);
        if (!saveResult) {
            responseBean.addError("fail");
            return responseBean;
        }

        // 2.生成二维码
        QueryWrapper<TaMiniapp> taMiniappQuery = new QueryWrapper<>();
        taMiniappQuery.eq("org_id", orgId);
        TaMiniapp taMiniapp = taMiniappMapper.selectOne(taMiniappQuery);
        ResponseBean taMiniappQrcode = miniAppService.getQrCode(CommConstant.DRAINAGE_QRCODE.replace("#0", taDrainage.getDrainageId().toString()).replace("#1", "h5"), taMiniapp.getMiniappId());
        taDrainage.setQrCode(String.valueOf(taMiniappQrcode.getData()));

        // 3.判断是否从h5样例入口创建
        if (taDrainage.getFromH5Sample() != null && taDrainage.getFromH5Sample() && taDrainage.getH5SampleId() != null) {

            // 5.查询h5样例是否配置默认模板
            TaH5Sample taH5Sample = taH5SampleMapper.selectById(taDrainage.getH5SampleId());
            if (taH5Sample != null && !StringUtils.isEmpty(taH5Sample.getH5TemplateId())) {

                TaH5Template taH5Template = taH5TemplateMapper.selectById(taH5Sample.getH5TemplateId());
                if (CommConstant.RED_PACKET.equals(taH5Template.getActivityType())) {

                    // 7.初始化活动(红包)相关数据
                    String activityId = CommonUtils.getUUIDS();
                    TaRedPacket taRedPacket = new TaRedPacket();
                    taRedPacket.setOrgId(orgId);
                    taRedPacket.setActivityId(activityId);
                    taRedPacket.setTempleActivityId(taH5Template.getActivityId());
                    taRedPacket.setName(taDrainage.getName());
                    taRedPacket.setCreateDate(LocalDateTime.now());
                    taRedPacket.setStartDate(LocalDateTime.now().plusDays(1));
                    taRedPacket.setQrcode(taDrainage.getQrCode());
                    taRedPacket.setEndDate(DateUtils.dayToLocalDateime(taDrainage.getEndDate()));
                    taRedPacket.setBuildingId(taDrainage.getBuildingId());
                    iTaRedPacketService.initializeRedPacket(taRedPacket,orgId);

                    taDrainage.setH5Address(String.format(taH5Template.getActivityUrl(), activityId));
                    taDrainage.setActivityType(taH5Template.getActivityType());
                    taDrainage.setActivityId(activityId);
                }
            }
        }
        updateById(taDrainage);

        // 4.添加第三方appid和secretis
        TaThirdPartyMiniappConfig taThirdPartyMiniappConfig = new TaThirdPartyMiniappConfig();
        taThirdPartyMiniappConfig.setOrgId(orgId);
        taThirdPartyMiniappConfig.setAppid(CommonUtils.getUUIDS());
        taThirdPartyMiniappConfig.setAppSecret(CommonUtils.getUUIDS());
        taThirdPartyMiniappConfig.setExpirationDate(LocalDateTime.now().plusDays(7));
        taThirdPartyMiniappConfig.setTargetType(CommConstant.TARGET_TYPE_H5);
        taThirdPartyMiniappConfig.setTargetId(taDrainage.getDrainageId().toString());
        iTaThirdPartyMiniappConfigService.save(taThirdPartyMiniappConfig);

        responseBean.addSuccess(taDrainage);
        return responseBean;
    }
}
