package com.example.logistics.ui;

import androidx.fragment.app.Fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.logistics.R;
import com.example.logistics.dao.goodDao;
import com.example.logistics.dao.operationDao;
import com.example.logistics.dao.userDao;
import com.example.logistics.entity.User;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.CaptureActivity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyFragment2 extends Fragment implements View.OnClickListener{

    private Button mButton;
    private Context mContext;

    private WebView mWebView;

    public MyFragment2(){

    }
    @Nullable

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_fragment2,container,false);
        mWebView = (WebView) view.findViewById(R.id.webview);

        WebSettings webSettings = mWebView.getSettings();
        mButton = (Button)view.findViewById(R.id.Pick_Button);
        mButton.setOnClickListener(this);
        mContext = getActivity();

        webSettings.setJavaScriptEnabled(true);
        mWebView.loadUrl("file:///android_asset/js.html");

        Log.i("set", "listner");

        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url){
                super.onPageFinished(view, url);
                String jsStr1 = "";
                try{
                    InputStream in1 = mContext.getAssets().open("em.js");
                    byte buff[] = new byte[1024];
                    ByteArrayOutputStream fromFile = new ByteArrayOutputStream();
                    do {
                        int numRead = in1.read(buff);
                        if (numRead <= 0) {
                            break;
                        }
                        fromFile.write(buff, 0, numRead);
                    } while (true);
                    jsStr1 = fromFile.toString();
                    in1.close();
                    fromFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mWebView.loadUrl("javascript:" + jsStr1);

                String jsStr2 = "";
                try{
                    InputStream in2 = mContext.getAssets().open("roslib.min.js");
                    byte buff[] = new byte[1024];
                    ByteArrayOutputStream fromFile = new ByteArrayOutputStream();
                    do {
                        int numRead = in2.read(buff);
                        if (numRead <= 0) {
                            break;
                        }
                        fromFile.write(buff, 0, numRead);
                    } while (true);
                    jsStr2 = fromFile.toString();
                    in2.close();
                    fromFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mWebView.loadUrl("javascript:" + jsStr2);
            }

        });


        return view;
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.Pick_Button:
                /*new IntentIntegrator(getActivity())
                        .setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)// 扫码的类型,一维码，二维码，一/二维码，默认为一/二维码
                        .setPrompt("请对准摄像头")
                        .setCameraId(0)
                        .setBeepEnabled(false)
                        .setCaptureActivity(CaptureActivity.class)
                        .initiateScan();*/
                pickup("abnc");

        }
    }

    public void test(){
        mWebView.loadUrl("javascript:callJS()");
        Log.i("abc", "bcd");
    }


    @Override
    @SuppressLint("MissingSuperCall")
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() != null) {
                //Toast.makeText(mContext, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                pickup(result.getContents());
            }
        }
    }

    public void pickup(String result){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        View view2 = View.inflate(mContext, R.layout.pickup, null);

        EditText PickUpCode = (EditText) view2.findViewById(R.id.pk_PickUp);
        EditText PhoneNum = (EditText) view2.findViewById(R.id.pk_PhoneNum);
        Button button = (Button) view2.findViewById(R.id.pk_button);

        builder.setTitle("取件").setView(view2);

        builder.create().show();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String pickupcode = PickUpCode.getText().toString().trim();
                String phonenum = PhoneNum.getText().toString().trim();
                Log.d("onclick", "123");
                //String QR_pickup = result.split(" ")[0];
                //String QR_phone = result.split(" ")[1];

                if(true){
                //if (pickupcode.equals(QR_pickup) && phonenum.equals(QR_phone)) {
                    /*new Thread() {
                        @Override
                        public void run() {
                            int msg = 0;

                            operationDao operationDao = new operationDao();
                            goodDao goodDao = new goodDao();
                            Bundle bundle = getArguments();

                            String user = bundle.getString("user");

                            boolean flag1 = operationDao.add(pickupcode, user);
                            boolean flag2 = goodDao.delete(pickupcode);

                            boolean flag = flag1 & flag2;
                            if (flag) {
                                msg = 1;
                            }
                            int msg = 1;
                            test();
                            hand1.sendEmptyMessage(msg);
                        }
                    }.start();*/
                    Toast.makeText(mContext, "取件成功", Toast.LENGTH_LONG).show();
                    test();

                } else {
                    Toast.makeText(mContext, "取件失败", Toast.LENGTH_LONG).show();
                }
            }


        });
    }

    @SuppressLint("HandlerLeak")
    final Handler hand1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Toast.makeText(mContext, "取件成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mContext, "取件失败", Toast.LENGTH_SHORT);
            }
        }
    };
}