package com.dxhy.erp.service.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dxhy.common.enums.ReturnCodeEnum;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.erp.dao.SysDeptDao;
import com.dxhy.erp.model.ReturnStateInfo;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.CheckIpBlocAppidService;
import com.dxhy.erp.utils.IpUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 校验IP，集团，appSecId
 * 
 * @author hp
 *
 */
@Service("checkIpBlocAppidService")
@Slf4j
public class CheckIpBlocAppidServiceImpl implements CheckIpBlocAppidService {

    @Resource
    private SysDeptDao sysDeptDao;

    /**
     * 获取ip
     *
     * @param request
     *            传入 request
     * @return 返回ip
     */
    @Override
    public String getIp(HttpServletRequest request) {
        String remoteAddr;
        String remoteAddr1 = request.getHeader("X-Real-IP");
        if (remoteAddr1 != null && !"".equals(remoteAddr1) && IpUtil.isboolIp(remoteAddr1)) {
            remoteAddr = remoteAddr1;
        } else {
            remoteAddr = request.getRemoteAddr();
        }
        return remoteAddr;
    }

    /**
     * 根据鉴权id 获取税号数量
     *
     * @param appSecId
     *            鉴权id
     * @param request
     *            传入 request
     * @return 返回数量
     */
    @Override
    public int checkBlocOne(String appSecId, HttpServletRequest request) {
        String remoteAddr = getIp(request);
        int blocOne;
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        blocOne = sysDeptDao.getBlocNoTax(remoteAddr, appSecId);
        return blocOne;
    }

    /**
     * 返回集团与税号不符
     *
     * @param globalInfo
     *            入参信息
     * @return 返回信息
     */
    @Override
    public String getCheckFailure(GlobalInfo globalInfo) {
        InterfaceCode interfaceCodeError = new InterfaceCode();
        ReturnStateInfo returnStateInfo = new ReturnStateInfo();
        returnStateInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
        returnStateInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
        interfaceCodeError.setGlobalInfo(globalInfo);
        interfaceCodeError.setReturnStateInfo(returnStateInfo);
        return JSON.toJSONString(interfaceCodeError);
    }
}
