package com.jianshui.income.service.impl.adapter.request;

import com.alibaba.fastjson.JSONObject;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.enums.ErrorCode;
import com.jianshui.common.exception.jianshui.JianshuiParamErrorException;
import com.jianshui.common.utils.StringUtils;
import com.jianshui.common.utils.encrypt.AisinoInvoiceDecryptUtil;
import com.jianshui.income.service.IIncomeRequestService;
import com.jianshui.system.service.ICompanyserviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 进项接口
 * @Description
 * @Author 巩权林
 * @Date 2022-03-25 10:03
 **/
@Slf4j
@Component("jn_aisino_income_request_adapter")
public class AisinoIncomeRequestAdapterImpl implements IIncomeRequestService {

    @Autowired
    private ICompanyserviceService companyserviceService;

    /**
     * 解密函数
     *
     * @param request
     * @param companyservice
     * @return
     */
    @Override
    public JSONObject decrypt(ServletRequest request, Companyservice companyservice) {
        // 根据servletRequest获取原始请求报文
        // String rawInput = HttpHelper.getBodyString(request);
        // if (StringUtils.isEmpty(rawInput)) {
        //     throw new JianshuiParamErrorException(ErrorCode.EMPTY_PARAMS, companyservice,"income);
        // }
        // JSONObject rawJson = JSONObject.parseObject(rawInput);
        // 因为航信的报文都是Form，所以这里要按form的来
        //方式一：getParameterMap()，获得请求参数map
        Map<String, String[]> map = request.getParameterMap();
        //参数名称
        Set<String> key = map.keySet();
        //参数迭代器
        Iterator<String> iterator = key.iterator();
        // JSONObject rawJson = JSONObject.parseObject(JSONObject.toJSONString(params));
        JSONObject rawJson = new JSONObject();
        while (iterator.hasNext()) {
            String k = iterator.next();
            rawJson.put(k, map.get(k)[0]);
        }


        if (StringUtils.isEmpty(rawJson)) {
            throw new JianshuiParamErrorException(ErrorCode.ERROR_PARAMS, companyservice, "income");
        }

        String order = rawJson.getString("order");
        String identity = rawJson.getString("identity");

        // 开始解析报文
        if (order == null || "".equals(order.trim())) {
            throw new JianshuiParamErrorException(ErrorCode.ERROR_PARAMS, companyservice, "income");
        }

        // // 查询企业验证信息
        // Companyservice companyservice = new Companyservice();
        // if (StringUtils.isEmpty(identity)) {
        //     throw new JianshuiParamErrorException(ErrorCode.EMPTY_IDENTITY, companyservice,"income);
        // }
        // companyservice = companyserviceService.selectCompanyserviceByCompanyid(Long.parseLong(identity));
        // if (companyservice == null) {
        //     throw new JianshuiParamErrorException(ErrorCode.COMPANY_NOT_FOUND, companyservice,"income);
        // }

        String JKey = companyservice.getSecret(); // 解密用的secret
        if (StringUtils.isEmpty(JKey)) {
            throw new JianshuiParamErrorException(ErrorCode.IDENTITY_NOT_SET, companyservice, "income");
        }

        // 平台解密
        try {
            order = AisinoInvoiceDecryptUtil.decrypt(order, JKey);
        } catch (Exception e) {
            e.printStackTrace();
            throw new JianshuiParamErrorException(ErrorCode.DECRYPT_ERROR, companyservice, "income");
        }

        log.info("查验报文：identity=" + identity + ",order=" + order);

        // 报文内容体
        JSONObject json = new JSONObject();
        try {
            json = JSONObject.parseObject(order);

            if (json == null || json.getString("taxNo") == null) {
                throw new JianshuiParamErrorException(ErrorCode.TAXCODE_NOT_FOUNC, companyservice, "income");
            }
            // 校验企业资质
            if (!json.getString("taxNo").equals(companyservice.getSellertax())) {
                throw new JianshuiParamErrorException(ErrorCode.IDENTITY_NOT_MATCH, companyservice, "income");
            }
        } catch (Exception e) {
            throw new JianshuiParamErrorException(ErrorCode.DECRYPT_ERROR, companyservice, "income");
        }

        return json;
    }
}
