package com.ruoyi.system.service.grid.qcc.impl;

import com.ruoyi.system.domain.qcc.EsearchJsonRecord;
import com.ruoyi.system.domain.qcc.enums.EsearchTypeEnum;
import com.ruoyi.system.domain.qcc.ext.EsearchResult;
import com.ruoyi.system.domain.qcc.util.FinalCostHttpHelper;
import com.ruoyi.system.service.grid.qcc.ISearch;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpHead;

import java.util.List;

public class QccSearch implements ISearch {

    @Override
    public EsearchTypeEnum getType() {
        return EsearchTypeEnum.qcc;
    }

    @Override
    public EsearchResult searchByUrl(String url, String appKey, String secKey) {
        String tokenJson = getTokenJson(url,appKey,secKey);
        EsearchResult result = new EsearchResult();
        if (StringUtils.isNotBlank(tokenJson)) {
            EsearchJsonRecord record = FinalCostHttpHelper.getJsonObject(tokenJson);
            String status = FinalCostHttpHelper.FormartJson(tokenJson, "Status");
            result.setStatus(status);
            result.setRecord(record);
        }
        return result;
    }

    @Override
    public EsearchResult vagueSearch(String url,String appKey,String secKey) {
        String tokenJson = getTokenJson(url,appKey,secKey);
        EsearchResult result = new EsearchResult();
        if (StringUtils.isNotBlank(tokenJson)) {
            List<EsearchJsonRecord> jsonRecords = FinalCostHttpHelper.PrettyPrintJson2(tokenJson);
            String status = FinalCostHttpHelper.FormartJson(tokenJson, "Status");
            result.setStatus(status);
            result.setRecords(jsonRecords);
        }
        return result;
    }

    @Override
    public String getTokenJson(String url, String appkey, String secKey) {
        HttpHead reqHeader = new HttpHead();
        String[] autherHeader = RandomAuthentHeader(appkey,secKey);
        reqHeader.setHeader("Token", autherHeader[0]);
        reqHeader.setHeader("Timespan", autherHeader[1]);
        String tokenJson = null;
        try {
            tokenJson = FinalCostHttpHelper.httpGet(url, reqHeader.getAllHeaders());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tokenJson;
    }




    private String[] RandomAuthentHeader(String appKey,String secKey) {
        String timeSpan = String.valueOf(System.currentTimeMillis() / 1000);
        String[] authentHeaders = new String[] { DigestUtils.md5Hex(appKey.concat(timeSpan).concat(secKey)).toUpperCase(), timeSpan };
        return authentHeaders;
    }


}
