package com.sdtool.webcore.servlet;

import com.sdtool.common.api.ERPService;
import com.sdtool.common.datas.ERPHeader;
import com.sdtool.common.datas.TokenUserFrom;
import com.sdtool.common.entity.base.DataBaseMultiItemEx;
import com.sdtool.common.entity.site.ERPTokenUser;
import com.sdtool.common.tool.ERPUtils;
import com.sweetfish.convert.json.JsonConvert;
import com.sweetfish.net.http.HttpContext;
import com.sweetfish.net.http.HttpFilter;
import com.sweetfish.net.http.HttpRequest;
import com.sweetfish.net.http.HttpResponse;
import com.sweetfish.util.AnyValue;
import com.sweetfish.util.ResourceFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.annotation.Priority;
import javax.annotation.Resource;
import java.io.IOException;

/**
 * Created by jlutt on 2018-05-07.
 * 将erp参数调用网页的参数session转换为cookie中的session
 *
 * @author jlutt
 */
@Priority(value = 98)
public class ERPSessionFilter extends HttpFilter {

    private final Logger logger = LogManager.getLogger(this.getClass().getSimpleName());

    @Resource(name = "server")
    private ResourceFactory rf;

    @Resource(name = "property.saasHostName")
    private String saasHostName;

    @Resource
    ERPService erpService;

    @Resource
    JsonConvert jsonConvert;

    @Override
    public void init(HttpContext context, AnyValue config) {
        super.init(context, config);
    }

    @Override
    public void doFilter(HttpRequest request, HttpResponse response) throws IOException {
        String erpSessionId = request.getHeader("ERPSessionId");
        if (StringUtils.isNotEmpty(erpSessionId)) {
            request.setSessionId(erpSessionId);
            request.addHeaderValue("ERPJSession", erpSessionId);
        }

        String userFrom = ERPUtils.parseHttpFrom(request);
        if (!request.existsHeader(ERPHeader.HTTPHEADER_USERFROM)) {
            request.addHeaderValue(ERPHeader.HTTPHEADER_USERFROM, userFrom);
        }
        int userFromInt = (StringUtils.isEmpty(userFrom)) ? TokenUserFrom.PC_ERP_ADMIN.getValue() : Integer.parseInt(userFrom);
        String ssoTokenCommonKey = rf.find("property." + TokenUserFrom.getTokenKey(userFromInt), String.class);

        //从cookies中的用户token解析出数据源id和分表key
        //有些终端无法修改cookie，可在提交的header中添加token
        String token = ERPUtils.parseHttpToken(request);
        ERPTokenUser tokenUser = ERPUtils.parseERPUserFromToken(token, ssoTokenCommonKey, jsonConvert);
        if (tokenUser != null) {
            //这里有个问题，如果token中的dataSourceId和supplierCode和header中的不一致，应该如何处理
            if (request.existsHeader(ERPHeader.HTTPHEADER_DATASOURCE)) {
                request.removeHeader(ERPHeader.HTTPHEADER_DATASOURCE);
            }
            if (request.existsHeader(ERPHeader.HTTPHEADER_SUPPLIER)) {
                request.removeHeader(ERPHeader.HTTPHEADER_SUPPLIER);
            }
//            logger.info(jsonConvert.convertTo(tokenUser));
            request.addHeaderValue(ERPHeader.HTTPHEADER_DATASOURCE, tokenUser.getDataSourceId());
            request.addHeaderValue(ERPHeader.HTTPHEADER_SUPPLIER, String.valueOf(tokenUser.getSupplierCode()));
        } else {
            String host = request.getHost();
            if (!StringUtils.isEmpty(saasHostName)) {
                if (host.toLowerCase().contains(saasHostName)) {
                    //saas域名,取第一段
                    DataBaseMultiItemEx item = erpService.getERPSupplierInfoByCode(host.split("\\.")[0]);
                    if (item != null) {
                        request.addHeaderValue(ERPHeader.HTTPHEADER_DATASOURCE, item.getDataBaseAlias());
                        request.addHeaderValue(ERPHeader.HTTPHEADER_SUPPLIER, item.getShardingKey());
                    }
                }
            }

        }
        //必须调用
        response.nextEvent();
    }

    @Override
    public void destroy(HttpContext context, AnyValue config) {
        super.destroy(context, config);
    }

    @Override
    public String getName() {
        return "ERPSessionFilter";
    }
}
