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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.redpack.entity.TaMpMiniapp;
import com.huiju.estateagents.redpack.entity.TaMpPerson;
import com.huiju.estateagents.redpack.mapper.TaMpMiniappMapper;
import com.huiju.estateagents.redpack.mapper.TaMpPersonMapper;
import com.huiju.estateagents.redpack.service.ITaMpMiniappService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.redpack.service.ITaMpPersonService;
import com.huiju.estateagents.third.entity.TaMpInfo;
import com.huiju.estateagents.third.service.ITaMpInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 公众号小程序账户映射  服务实现类
 * </p>
 *
 * @author fxf
 * @since 2020-06-02
 */
@Service
public class TaMpMiniappServiceImpl extends ServiceImpl<TaMpMiniappMapper, TaMpMiniapp> implements ITaMpMiniappService {
    @Autowired
    ITaMpPersonService iTaMpPersonService;

    @Autowired
    ITaMpInfoService iTaMpInfoService;

    @Override
    public void mpPerson(TaPerson taPerson, String mpOpenId) {
        TaMpInfo mpInfo = iTaMpInfoService.getByOrgId(taPerson.getOrgId());

        TaMpPerson mpPerson = iTaMpPersonService.getByOpenId(taPerson.getOrgId(), mpInfo.getAppid(), mpOpenId);
        if (null == mpPerson) {
            return;
        }

        TaMpMiniapp origin = getByPrimaryKey(taPerson.getPersonId(), mpPerson.getMpPersonId());
        if (null == origin) {
            TaMpMiniapp mpMiniapp = new TaMpMiniapp();
            mpMiniapp.setMiniappPersonId(taPerson.getPersonId());
            mpMiniapp.setMpPersonId(mpPerson.getMpPersonId());
            save(mpMiniapp);
        }
    }

    @Override
    public TaMpMiniapp getByMiniAppPerson(String miniAppPersonId) {
        QueryWrapper<TaMpMiniapp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("miniapp_person_id", miniAppPersonId);

        return getOne(queryWrapper);
    }

    private TaMpMiniapp getByPrimaryKey(String miniPersonId, String mpPersonId) {
        QueryWrapper<TaMpMiniapp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("miniapp_person_id", miniPersonId);
        queryWrapper.eq("mp_person_id", mpPersonId);

        return getOne(queryWrapper);
    }
}
