package com.tiesheng.core.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiesheng.core.config.web.TieshengWebConfigurer;
import com.tiesheng.core.mapper.CorePlatformUniqueMapper;
import com.tiesheng.core.pojos.dao.CorePlatformUnique;
import com.tiesheng.login.config.TieshengLoginConfigurer;
import com.tiesheng.login.config.token.bean.TokenBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

/**
 * @author hao
 */
@Service
public class CorePlatformUniqueService extends TsServiceBase<CorePlatformUniqueMapper, CorePlatformUnique> implements TieshengLoginConfigurer {

    @Autowired
    TieshengWebConfigurer tieshengWebConfigurer;
    @Autowired
    CoreLogService coreLogService;

    @Override
    public TokenBean doLogin(String appId, String uniqueId, String platfrom, String info) {

        CorePlatformUnique platformUnique = getByAppAndUnique(appId, uniqueId, platfrom);
        platformUnique.setInfo(info);
        TokenBean tokenBean = tieshengWebConfigurer.loginConfigurer().doLogin(platformUnique);
        if (tokenBean != null) {
            platformUnique.setUserId(tokenBean.getId());
            platformUnique.setIsDeleted(0);
            saveOrUpdate(platformUnique);

            // 添加登录日志
            coreLogService.addLoginLog(platformUnique);
        }
        return tokenBean;
    }

    @Override
    public void onLoginRedirect(TokenBean bean, String extra, HttpServletResponse response) {
        tieshengWebConfigurer.loginConfigurer().redirect(bean, extra, response);
    }


    /**
     * 通过appId获取登录对象
     *
     * @param appId
     * @param uniqueId
     * @return
     */
    private CorePlatformUnique getByAppAndUnique(String appId, String uniqueId, String platform) {
        QueryWrapper<CorePlatformUnique> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_id", appId);
        queryWrapper.eq("unique_id", uniqueId);
        queryWrapper.eq("platform", platform);
        queryWrapper.last("limit 1");
        CorePlatformUnique platformUnique = getOne(queryWrapper);
        if (platformUnique == null) {
            platformUnique = new CorePlatformUnique();
            platformUnique.setAppId(appId);
            platformUnique.setUniqueId(uniqueId);
            platformUnique.setPlatform(platform);
        }
        return platformUnique;
    }

}
