package com.example.writeepc;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.example.writeepc.adapter.MyMesInfoAdapter;
import com.example.writeepc.base.BaseActivity;
import com.example.writeepc.base.okgo.MyRecultCall;
import com.example.writeepc.base.okgo.MyResult;
import com.example.writeepc.been.MESInfo;
import com.example.writeepc.databinding.ActivityShuangqian2Binding;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

public class ShuangqianActivity2 extends BaseActivity {
    private ActivityShuangqian2Binding binding;
private MyMesInfoAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_shuangqian2);
        initUHFRManager1();
        initDialog();
        adapter=new MyMesInfoAdapter(this);
        binding.setAdapter(adapter);
    }

    public void dataReadRFID(View view) {
        readEPC(12);
        // String msg="<Entity><ID>37f82ad8-6a16-4b9b-880c-78ebf644970a</ID><FAC>02</FAC><BARCODE>2408418883</BARCODE><STATE>1</STATE><CUSQTY>0</CUSQTY><CUDQTY>0</CUDQTY><CUBQTY>0</CUBQTY><CUIQTY>0</CUIQTY><BUITNBR>000000000080435113</BUITNBR><BUITDSC>2045</BUITDSC><BUDAT xsi:type=\"xsd:dateTime\">2025-08-04T00:00:00</BUDAT><BUTIM xsi:type=\"xsd:dateTime\">2025-08-04T10:55:31.517</BUTIM><BUSHT>1</BUSHT><BUBAN /><BUMCH>L403</BUMCH><BUNAM>张磊</BUNAM><BUNAMCOD>HL4969</BUNAMCOD><BUSQTY>1</BUSQTY><BUDQTY>0</BUDQTY><BUBQTY>0</BUBQTY><BUIQTY>0</BUIQTY><BUPLANCOD>YC250804L403204511</BUPLANCOD><BUCOTCOD /><NORMALSTA>P</NORMALSTA><TYRENO>2408418883</TYRENO><BUVERSION /><CRTIM xsi:type=\"xsd:dateTime\">2025-08-04T10:55:31.517</CRTIM><IS_DELETE>0</IS_DELETE><BUHELPER1 /><BUHELPER2 /><BUQCSTATE>1</BUQCSTATE><CUWARNING xsi:nil=\"true\" /><CULTIM>0</CULTIM><CUKTIM>0</CUKTIM><SPEC>S2045-05</SPEC><DOT>0</DOT><BUHELPER3 /><BUASS1 /><BUASS2 /><BUASS3 /><BUASS4 /><BUASS5 /><WMS_FLAG>0</WMS_FLAG><BUCARNO /></Entity>";
        // jiexi(msg);


    }

    @Override
    protected void readTidReault(boolean readState, String result, byte[] rdata) {
        super.readTidReault(readState, result, rdata);
        binding.dataEpc.setText(result);

        if (readState) {
            // callWebService(buildSelectRequest(result));
            haohuaMesSelect(result);
            
            
        }
    }

    private void haohuaMesSelect(String result) {
        OkGo.<MyResult>post("http://192.168.26.26:5050/UMInterface/RFID/tyreTracingBack")
                .params("rfid",result)
                .execute(new MyRecultCall(dialog,this) {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        MyResult body = response.body();
                        try {
                            if (body.getCode() == 200) {
                                List<String> list=gson.fromJson(body.getDataJson(),new TypeToken<List<String>>(){}.getType());
                                if (list.isEmpty()){
                                    tipsDialog.setTip(false, "未返回信息");
                                    tipsDialog.show();
                                    return;
                                }
                                List<MESInfo> mesInfos=new ArrayList<>(list.size());
                                list.forEach(item->{
                                    String[] split = item.split(":");
                                    MESInfo mesInfo=new MESInfo();
                                    mesInfo.setTitle(split[0]);
                                    mesInfo.setInfo(split[1]);
                                    mesInfos.add(mesInfo);
                                });
                                adapter.setList(mesInfos);

                            } else {
                                tipsDialog.setTip(false, body.getInfo());
                                tipsDialog.show();
                                adapter.setList(null);

                            }
                        } catch (Exception e) {
                            tipsDialog.setTip(false, "接口返回信息异常,解析失败");
                            tipsDialog.show();

                        }
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    private void callWebService(String soapRequest) {
        // 发送 POST 请求
        OkGo.<String>post("http://10.135.55.206:99/WebService.asmx")
                .headers("Content-Type", "text/xml; charset=utf-8")
                .upString(soapRequest, mediaType)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        dialog.show();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        // 处理响应结果
                        String result = response.body();
                        try {
                            String str = "<faultstring>";
                            int faultstringIndex = result.indexOf(str);
                            if (faultstringIndex > -1) {
                                String faultstring = result.substring(faultstringIndex + str.length(), result.indexOf("</faultstring>"));
                                tipsDialog.setTip(false, faultstring);
                                tipsDialog.show();
                                return;
                            }
                            int codeIndex = result.indexOf("<Code>");
                            if (codeIndex > -1) {
                                String resultCode = result.substring(codeIndex + 6, result.indexOf("</Code>"));
                                if (resultCode.equals("200")) {
                                    String resultMsg = result.substring(result.indexOf("<Entity>") + 8, result.indexOf("</Entity>"));

                                    jiexi(resultMsg);
                                    return;
                                }
                                String resultMsg = result.substring(result.indexOf("<Msg>") + 5, result.indexOf("</Msg>"));
                                tipsDialog.setTip(false, resultMsg);
                                tipsDialog.show();
                            }
                        } catch (Exception e) {
                            tipsDialog.setTip(false, "接口返回信息异常");
                            tipsDialog.show();
                        }
                    }


                    @Override
                    public void onFinish() {
                        super.onFinish();
                        dialog.dismiss();
                    }
                });
    }


    // 创建验证信息
    private String buildSelectRequest(String epcid) {
        StringBuilder soapRequest = new StringBuilder();
        soapRequest.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        soapRequest.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
        soapRequest.append("<soap:Body>");
        soapRequest.append("<TyreTracingBack xmlns=\"http://tempuri.org/\">");
        soapRequest.append("<epcid>").append(epcid).append("</epcid>");
        soapRequest.append("</TyreTracingBack>");
        soapRequest.append("</soap:Body>");
        soapRequest.append("</soap:Envelope>");
        return soapRequest.toString();
    }

    private void jiexi(String msg) {
        StringBuilder stringBuilder = new StringBuilder();

        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(new StringReader(msg));
            String currentTag = null;
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        currentTag = parser.getName();

                        break;

                    case XmlPullParser.TEXT:
                        if (currentTag != null && parser.getText() != null) {
                            String text = parser.getText().trim();
                            // 解析字段值
                            switch (currentTag) {

                                case "BARCODE":
                                    stringBuilder.append("条       码：").append(text).append("\n");
                                    break;

                                case "BUITNBR":
                                    stringBuilder.append("ERP编码：").append(text).append("\n");

                                    break;
                                case "BUITDSC":
                                    stringBuilder.append("规格名称：").append(text).append("\n");

                                    break;
                                case "BUDAT":
                                    stringBuilder.append("成型日期：").append(text).append("\n");
                                    break;
                                case "BUTIM":
                                    stringBuilder.append("成型时间：").append(text).append("\n");
                                    break;
                                case "BUSHT":
                                    stringBuilder.append("成型班次：").append(text).append("\n");
                                    break;
                                case "BUMCH":
                                    stringBuilder.append("成型机台：").append(text).append("\n");
                                    break;
                                case "BUNAM":
                                    stringBuilder.append("成  型  工：").append(text).append("\n");
                                    break;
                                case "BUNAMCOD":
                                    stringBuilder.append("成型工账号：").append(text).append("\n");
                                    break;
                                case "BUPLANCOD":
                                    stringBuilder.append("成型计划号：").append(text).append("\n");
                                    break;

                                case "TYRENO":
                                    stringBuilder.append("生  胎  码：").append(text).append("\n");
                                    break;
                            }
                        }
                        break;

                    case XmlPullParser.END_TAG:
                        currentTag = null;
                        break;
                }
                eventType = parser.next();
            }
            binding.dataInfo.setText(stringBuilder.toString());
        } catch (XmlPullParserException | IOException e) {
            Log.e("TAG", "解析XML失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}