package com.njcn.serviceimpl.tiansu;

import com.njcn.mapper.tiansu.TenantMapper;
import com.njcn.pojo.tiansu.Tenant;
import com.njcn.service.tiansu.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

/**
 * @author hongawen
 * @Date: 2018/7/19 13:42
 */
@Service
public class TenantServiceImpl implements TenantService {

    @Autowired
    private TenantMapper tenantMapper;

    /**
     * 保存租户信息和永久授权码
     * @param suiteId 应用ID
     * @param corpId  租户ID
     * @param suiteTicket 动态码
     * @param permanentCode 永久授权码
     * @param accessToken 平台接口凭证
     */
    @Override
    public void saveTenant(String suiteId, String corpId, String suiteTicket, String permanentCode, String accessToken) {
        Tenant tenant=new Tenant();
        tenant.setSuiteid(suiteId);
        tenant.setCorpId(corpId);
        tenant=tenantMapper.selectOne(tenant);
        if(null==tenant){
            //新增
            tenant=new Tenant();
            tenant.setCorpId(corpId);
            tenant.setSuiteid(suiteId);
            tenant.setSuteTicket(suiteTicket);
            tenant.setPermanentCode(permanentCode);
            tenant.setAccessToken(accessToken);
            tenantMapper.insert(tenant);

        }else{
            //该用户已经授权,更新授权码和token
            tenant.setPermanentCode(permanentCode);
            tenant.setAccessToken(accessToken);
            Example example=new Example(Tenant.class);
            example.createCriteria().andEqualTo("suiteid",tenant.getSuiteid()).andEqualTo("corpId",tenant.getCorpId());
            tenantMapper.updateByExample(tenant,example);
        }


    }

    /**
     * 根据服务商ID和租户ID获取accessToken
     */
    @Override
    public Tenant selectOne(String suiteId, String corpId) {
        Tenant tenant=new Tenant();
        tenant.setSuiteid(suiteId);
        tenant.setCorpId(corpId);

        return tenantMapper.selectOne(tenant);
    }
}
