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.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
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.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.logistics.R;
import com.example.logistics.manager.goodManager;
import com.example.logistics.manager.operationManager;
import com.example.logistics.tools.JWebSocketClient;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

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

public class PickUpUI extends Fragment implements View.OnClickListener{

    private Button mButton;
    private Context mContext;
    private JWebSocketClient client;
    private AlertDialog alert;
    private AlertDialog alert2;
    private EditText PickUpCode;
    private EditText PhoneNum;
    private String pickupcode;
    private String phonenum;
    private int shelfnum = 1;
    private int floornum = 1;

    private String ws = "ws://192.168.43.203:8080/result";

    private String TAG = "PickUpUI";

    int flag = 0; //flag=0:chushi

    public PickUpUI(){

    }
    @Nullable

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

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

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

        setAlert();
        return view;
    }


    void setAlert(){
        alert = new android.app.AlertDialog.Builder(mContext)
                .setTitle("提醒")
                .setMessage("是否确认取件")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d("alert","yes");
                        //add(operation);
                        JSONObject js = new JSONObject();
                        try {
                            js.put("content", "yes");
                            js.put("op", "confirm");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        flag = 1;

                        mButton.setText("确认");

                        client.send(js.toString());
                        Log.d("alert", "send");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d("alert","no");

                        JSONObject js = new JSONObject();
                        try {
                            js.put("confirm", "no");
                            js.put("op", "confirm");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        client.send(js.toString());
                    }
                })
                .create();
        Log.d(TAG, "setAlert");
    }

    void setWebsocket(){
        URI uri = URI.create(ws);
        client = new JWebSocketClient(uri){
            @Override
            public void onMessage(String message) {
                Log.e("JWebSocketClientService", "收到的消息：" + message);
                Log.e("alert",message);
                if(message.equals("confirm")){
                    alert.dismiss();
                    hand2.sendEmptyMessage(3);
                    Log.e("alert","show");
                }
            }

            @Override
            public void onOpen(ServerHandshake handshakedata) {
                super.onOpen(handshakedata);
                Log.e("JWebSocketClientService", "websocket连接成功");
            };
        };
        connect();
    }

    private void connect() {
        new Thread() {
            @Override
            public void run() {
                try {
                    //connectBlocking多出一个等待操作，会先连接再发送，否则未连接发送会报错
                    client.connectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    @SuppressLint("HandlerLeak")
    final Handler hand2 = new Handler(){
        @Override
        public void handleMessage(Message msg){
            alert.show();
        }
    };

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.Pick_Button:
                Log.e(TAG, "onclick");
                if(flag == 1){
                    confirm();
                }else{
                    pickup();
                }


        }
    }

    void confirm(){
        JSONObject js = new JSONObject();
        try {
            js.put("op","finish");
            client.send(js.toString());

            flag = 0;
            mButton.setText("取件");
            client.onClose(1,"close",true);
            Log.d("finish", "over");

        } catch (JSONException jsonException) {
            jsonException.printStackTrace();
        }
    }


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

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

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

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

        alert2 = builder.create();
        alert2.show();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(TAG,"onclick");
                setWebsocket();
                pickupcode = PickUpCode.getText().toString().trim();
                phonenum = PhoneNum.getText().toString().trim();
                Log.d("onclick", "123");
                new Thread() {
                    @Override
                    public void run() {
                        int msg = 0;

                        operationManager operationManager = new operationManager();
                        goodManager goodManager = new goodManager();
                        Bundle bundle = getArguments();

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

                        msg = goodManager.pickup(pickupcode,phonenum);

                        Log.d(TAG, "pickup");
                        if(msg != 1){
                            Log.d(TAG, "pickup,failed");
                            hand1.sendEmptyMessage(msg);
                            return;
                        }

                        Log.d(TAG, "pickup,success");

                        boolean flag1 = operationManager.add(pickupcode, user);
                        boolean flag2 = goodManager.delete(pickupcode);

                        boolean flag = flag1 & flag2;
                        if (flag) {
                            msg = 1;
                        }

                        hand1.sendEmptyMessage(msg);
                    }
                }.start();
            }
        });
    }

    @SuppressLint("HandlerLeak")
    final Handler hand1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0){
                Toast.makeText(mContext, "取件失败", Toast.LENGTH_SHORT).show();
            }else if(msg.what == 1){
                Toast.makeText(mContext, "加入队列成功", Toast.LENGTH_SHORT).show();
                joinQueue();
            }else if(msg.what == 2){
                Toast.makeText(mContext, "手机号错误", Toast.LENGTH_SHORT).show();
            }else if(msg.what == 3){
                Toast.makeText(mContext, "取件码不存在", Toast.LENGTH_SHORT).show();
            }
        }
    };

    void joinQueue(){
        alert2.dismiss();
        if (client != null && client.isOpen()) {

            JSONObject js = new JSONObject();
            JSONObject con = new JSONObject();
            try {
                Log.d(TAG, pickupcode);
                Log.d(TAG, phonenum);

                con.put("code", Integer.parseInt(pickupcode));
                con.put("shelf", shelfnum);
                con.put("floor", floornum);
                con.put("user", "xcr");
                js.put("content", con);
                js.put("op", "connect");
            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
            }

            if (null != client) {
                Log.e("JWebSocketClientService", "发送的消息：" + js.toString());
                client.send(js.toString());
                //暂时将发送的消息加入消息列表，实际以发送成功为准（也就是服务器返回你发的消息时）
            }
        }
    }
}