package com.dxhy.erp.service.impl;

import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import cn.hutool.core.codec.Base64;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.ReturnCodeEnum;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.erp.dao.SysDeptDao;
import com.dxhy.erp.entity.SysDeptEntity;
import com.dxhy.erp.model.ReturnStateInfo;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.AuthStatusService;
import com.dxhy.erp.utils.HmacSHA1Util;

import lombok.extern.slf4j.Slf4j;

/**
 * 申请认证状态变更逻辑层
 *
 * @author JLY
 * @date 2017年6月8日下午3:55:34
 */
@Service("authStatusService")
@Slf4j
public class AuthStatusServiceImpl implements AuthStatusService {

    @Resource
    private SysDeptDao sysDeptDao;

    /**
     * 获取数据库
     *
     * @param taxno
     * @return
     */
    @Override
    public String getDbName(String taxno) {
        SysDeptEntity deptEntity = sysDeptDao.getOrg(taxno);
        String dbName = null;
        if (deptEntity != null && deptEntity.getDbName() != null) {
            dbName = deptEntity.getDbName();
        }
        return dbName;
    }

    /**
     * @Methods:getGlobalInfo : 通用报文头信息
     * @author JLY
     * @date 2017年6月9日下午3:35:55
     * @param requestParam
     * @return 头信息实体
     * @throws Exception
     */
    @Override
    public GlobalInfo getGlobalInfo(Map<String, String> requestParam) throws Exception {
        return JSON.parseObject(requestParam.get("globalInfo"), GlobalInfo.class);
    }

    /**
     * @Methods:getInterfaceCodeError : 返回接口编码不存在
     * @author JLY
     * @date 2017年6月12日上午11:53:22
     * @param globalInfo
     * @return
     */
    @Override
    public String getInterfaceCodeError(GlobalInfo globalInfo) throws Exception {
        InterfaceCode interfaceCodeError = new InterfaceCode();
        ReturnStateInfo returnStateInfo = new ReturnStateInfo();
        returnStateInfo.setReturnCode(ReturnCodeEnum.JKDMBCZ.getFhzDm());
        returnStateInfo.setReturnMessage(ReturnCodeEnum.JKDMBCZ.getFhzMc(ReturnCodeEnum.JKDMBCZ.getIndex()));
        interfaceCodeError.setGlobalInfo(globalInfo);
        interfaceCodeError.setReturnStateInfo(returnStateInfo);
        return JSON.toJSONString(interfaceCodeError);

    }

    /**
     * @Methods:getDealWithFailure : 处理失败
     * @author JLY
     * @date 2017年6月14日上午10:00:37
     * @param globalInfo
     * @return 失败报文
     */
    @Override
    public String getDealWithFailure(GlobalInfo globalInfo) {
        InterfaceCode interfaceCodeError = new InterfaceCode();
        ReturnStateInfo returnStateInfo = new ReturnStateInfo();
        returnStateInfo.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
        returnStateInfo.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
        interfaceCodeError.setGlobalInfo(globalInfo);
        interfaceCodeError.setReturnStateInfo(returnStateInfo);
        try {
            return JSON.toJSONString(interfaceCodeError);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Methods:getSignFailure : 签权失败返回报文
     * @author JLY
     * @date 2017年6月15日下午4:41:27
     * @param globalInfo
     * @return
     * @throws Exception
     */
    @Override
    public String getSignFailure(GlobalInfo globalInfo) throws Exception {
        InterfaceCode interfaceCodeError = new InterfaceCode();
        ReturnStateInfo returnStateInfo = new ReturnStateInfo();
        returnStateInfo.setReturnCode(ReturnCodeEnum.SQXXCW.getFhzDm());
        returnStateInfo.setReturnMessage(ReturnCodeEnum.SQXXCW.getFhzMc(ReturnCodeEnum.SQXXCW.getIndex()));
        interfaceCodeError.setGlobalInfo(globalInfo);
        interfaceCodeError.setReturnStateInfo(returnStateInfo);
        return JSON.toJSONString(interfaceCodeError);
    }

    /**
     * 百度检查密钥是否合法
     *
     * @param request
     * @param
     * @return
     */
    @Override
    public int validParams(HttpServletRequest request, Map<String, String> requestParam) {
        try {
            // 拼接签名的前半部分字符串
            StringBuilder strB = new StringBuilder();
            strB.append(request.getMethod());
            strB.append(request.getRequestURI());
            strB.append("?");

            // 拼接签名的后半部分字符串
            StringBuilder strB2 = new StringBuilder();
            Authorize authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            strB2.append("authorize=").append("{\"appSecId\":\"").append(authorize.getAppSecId()).append("\"}");
            GlobalInfo globalInfo = this.getGlobalInfo(requestParam);
            strB2.append("&globalInfo=").append("{\"appId\":\"").append(globalInfo.getAppId())
                .append("\",\"version\":\"").append(globalInfo.getVersion()).append("\",\"interfaceCode\":\"")
                .append(globalInfo.getInterfaceCode()).append("\",\"enterpriseCode\":\"")
                .append(globalInfo.getEnterpriseCode()).append("\",\"dataExchangeId\":\"")
                .append(globalInfo.getDataExchangeId()).append("\"}");
            strB2.append("&data=").append(Base64.encode(requestParam.get("data")));

            // 总拼接
            strB.append(strB2.toString());
            String str = strB.toString();
            log.info("签权的字符串：{}", str);
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            String secretKey = sysDeptDao.getSecretKey(authorize.getAppSecId());
            String hmacsha1 = HmacSHA1Util.hmacsha1(str, secretKey);
            log.info("加密之后：{}", hmacsha1);
            // 验证签名
            log.info("客户端传过来的签权字符串：{}", authorize.getAppSec());
            if (!authorize.getAppSec().equals(hmacsha1)) {
                return 1;
            }
        } catch (Exception e) {
            return 1;
        }
        return 0;
    }
}
