package com.jeequan.jeepay.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.MchWxmpUser;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.service.mapper.MchWxmpUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 商户公众号消息接收用户列表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2021-10-15
 */
@Service
public class MchWxmpUserService extends ServiceImpl<MchWxmpUserMapper, MchWxmpUser> {

    @Autowired private MchInfoService mchInfoService;
    @Autowired private SysUserService sysUserService;

    /** 初始化 **/
    public void saveOrUpdateRecord(String mchNo, Long sysUserId, String appId, String openId, String nickname){

        if(mchInfoService.count(MchInfo.gw().eq(MchInfo::getMchNo, mchNo)) <= 0
            || sysUserService.count(SysUserEntity.gw().eq(SysUserEntity::getSysUserId, sysUserId)) <= 0){
            throw new BizException("参数错误");
        }

        // 查询系统已授权用户
        MchWxmpUser mchWxmpUser = getByUniqueKey(mchNo, appId, openId);

        MchWxmpUser updateRecord = new MchWxmpUser();
        updateRecord.setMchNo(mchNo);
        updateRecord.setSysUserId(sysUserId);
        updateRecord.setWxAppId(appId);
        updateRecord.setWxOpenId(openId);
        updateRecord.setNickname(nickname);
        updateRecord.setSendStatus(MchWxmpUser.SEND_STATE_OPEN);

        if(mchWxmpUser != null){
            updateRecord.setUserId(mchWxmpUser.getUserId());
            updateById(updateRecord);
            return ;
        }

        save(updateRecord);
    }

    public MchWxmpUser getByUniqueKey(String mchNo, String appId, String openId) {

        return baseMapper.selectOne(MchWxmpUser.gw()
                .eq(MchWxmpUser::getMchNo, mchNo)
                .eq(MchWxmpUser::getWxAppId, appId)
                .eq(MchWxmpUser::getWxOpenId, openId)
        );
    }

}
