package com.iformall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iformall.common.IdWorker;
import com.iformall.domain.po.WxCUser;
import com.iformall.domain.po.WxCuserFloatingLayer;
import com.iformall.domain.po.WxFloatingLayer;
import com.iformall.enums.EnumFloatingLayerStatus;
import com.iformall.mapper.WxCUserMapper;
import com.iformall.mapper.WxCuserFloatingLayerMapper;
import com.iformall.mapper.WxFloatingLayerMapper;
import com.iformall.service.WxCuserFloatingLayerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author gongbiao
 */
@Service
public class WxCuserFloatingLayerServiceImpl implements WxCuserFloatingLayerService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxCuserFloatingLayerMapper wxCuserFloatingLayerMapper;

    @Autowired
    WxFloatingLayerMapper wxFloatingLayerMapper;

    @Autowired
    WxCUserMapper wxCUserMapper;


    @Override
    public WxFloatingLayer getFloatingLayer(String openId, String appId) {
        //1 查看是否存在用户，用户不存在 直接返回浮层信息
        WxCUser user = new WxCUser();
        user.setOpenId(openId);
        user.setAppId(appId);
        WxCUser byOpenId = wxCUserMapper.findByOpenId(user);
        String tenantId = byOpenId.getTenantId();
        if (byOpenId == null) {
            return getWxFloatingLayer(tenantId);
        }
        //2 用户存在 查看是否已有弹出记录 没有 保存记录后返回浮层信息
        WxCuserFloatingLayer wxCuserFloatingLayerQuery = new WxCuserFloatingLayer();
        wxCuserFloatingLayerQuery.setUserId(byOpenId.getId());
        WxCuserFloatingLayer wxCuserFloatingLayer = wxCuserFloatingLayerMapper.selectOne(new QueryWrapper<>(wxCuserFloatingLayerQuery));
        if (wxCuserFloatingLayer == null) {
            saveCuserFloatingLayer(byOpenId);
            return getWxFloatingLayer(tenantId);
        }
        return null;
    }

    public void saveCuserFloatingLayer(WxCUser wxCUser) {
        WxCuserFloatingLayer wxCuserFloatingLayer;
        wxCuserFloatingLayer = new WxCuserFloatingLayer();
        final IdWorker idWorker = IdWorker.get();
        wxCuserFloatingLayer.setId(idWorker.nextId());
        wxCuserFloatingLayer.setUserId(wxCUser.getId());
        wxCuserFloatingLayer.setTenantId(wxCUser.getTenantId());
        wxCuserFloatingLayer.setCreateTime(new Date());
        wxCuserFloatingLayerMapper.insert(wxCuserFloatingLayer);
    }

    public WxFloatingLayer getWxFloatingLayer(String tenantId) {
        WxFloatingLayer wxFloatingLayer = new WxFloatingLayer();
        wxFloatingLayer.setTenantId(tenantId);
        wxFloatingLayer.setStatus(EnumFloatingLayerStatus.STATUS_THROW_IN.getCode());
        return wxFloatingLayerMapper.selectOne(new QueryWrapper<>(wxFloatingLayer));
    }
}
