package weaver.interfaces.htsc.workflow;

import com.alibaba.fastjson.JSONObject;
import com.weaver.general.GCONST;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class EquipmentUnlockAction extends BaseBean implements Action {
    private Log log = LogFactory.getLog(this.getClass());

    @Override
    public String execute(RequestInfo requestInfo) {
        RecordSet rst = new RecordSet();
        try{
            String tablename = requestInfo.getRequestManager().getBillTableName();
            String requestid = requestInfo.getRequestid();
            Map<String,String> map = new HashMap<>();
            Property[] property = requestInfo.getMainTableInfo().getProperty();
            for (int i = 0;i<property.length;i++){
                String name = property[i].getName();//主字段名称
                String value = Util.null2String(property[i].getValue());
                map.put(name,value);
            }
            String sbsl = map.get("sbsl");
            log.info("设备数量"+sbsl);
            //设备数量为0走人工解锁
            if ("0".equals(sbsl)){
                return Action.SUCCESS;
            }

            log.info("requestid--"+requestid+"--"+tablename);
            String scmmdkhh = "";
            //2022-04-08
            String type = "";
            String sql = "select scmmdkhh,xtzdjsjg,sblx from "+tablename+" where requestid = "+requestid;
            rst.execute(sql);
            if (rst.next()){
                scmmdkhh = Util.null2String(rst.getString("scmmdkhh"));
                switch (Util.null2String(rst.getString("sblx"))){
                    case "0":type ="pc";break;
                    case "1":type ="phone";break;
                }
            }
            log.info("sql-"+sql);
            log.info("account--"+scmmdkhh);
            PropBean propBean = new PropBean();
            String url = propBean.getPropName("UnlockUrl");
            String token = propBean.getPropName("UnlockToken");
//            url = url+"/iscs/api/unLock?account="+scmmdkhh+"&type=phone";
            url = url+"/iscs/api/unLock?account="+scmmdkhh+"&type="+type;
            Map<String,String> headers = new HashMap<>();
            headers.put("user","oa");
            headers.put("token",token);
            JSONObject parmsObject = new JSONObject();
//            parmsObject.put("account",scmmdkhh);
//            parmsObject.put("type","phone");
            String encode = "utf-8";
            String str = httpPostRaw(url, parmsObject.toString(), headers, encode);
            JSONObject dataObject = JSONObject.parseObject(str);
            log.info("解密接口返回结果"+str);
            //更新解锁结果
            int status = dataObject.getIntValue("status");
            log.info("status-"+status);
            String updateSql = "update "+tablename+" set xtzdjsjg = "+status+" where requestid = "+requestid;
            rst.execute(updateSql);
            log.info("updateSql-"+updateSql);
        }catch (Exception e){
            e.printStackTrace();
            requestInfo.getRequestManager().setMessageid("111111");
            requestInfo.getRequestManager().setMessagecontent("解锁失败");
        }
        return Action.SUCCESS;
    }

    /**
     * 发送http请求
     * @param url        接口地址
     * @param stringJson 请求的 json 字符串
     * @param headers    头部参数
     * @param encode     编码
     * @return 响应结果
     */
    private String httpPostRaw(String url, String stringJson, Map<String, String> headers, String encode)
    {
        BaseBean bb = new BaseBean();
        if (encode == null) {
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {
            //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);
            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);
            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            bb.writeLog("httpResponse===" + "httpResponse===" + httpResponse);
            HttpEntity entity = httpResponse.getEntity();
            bb.writeLog("entity", "entity===" + entity);
            content = EntityUtils.toString(entity, encode);
            bb.writeLog("content", "content===" + content);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
}
