package com.example.administrator.zhapp.activity.ydckgl;

import android.content.DialogInterface;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.BaseActivity;
import com.example.administrator.zhapp.activity.MipcaActivityCapture;
import com.example.administrator.zhapp.adapter.KcpdAdapter;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.KcpdInfo;
import com.example.administrator.zhapp.entity.StatusInfo;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.NohttpUtils;
import com.example.administrator.zhapp.utils.SPUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.PdDialog;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
import java.util.ArrayList;
import java.util.List;



/**
 * 移动仓库管理-库存盘点
 */

public class KcpdActivity extends BaseActivity implements KcpdAdapter.Callback {

    EditText et_hgtm;
    TextView tv_sys;
    Button btn_query;
    ListView lv;
    TextView et_xm;
    TextView et_ms;
    TextView et_sl;
    EditText et_sjsl;
    Button btn_save;
    Button btn_cancel;
    Button btn_itqz;
    LinearLayout ll;
    EditText etXmh;
    TextView tvSyswz;
    Spinner spBz;

    private KcpdAdapter adapter;
    private List<KcpdInfo.kcpd> infos;
    private View headView;

    private String pdid;
    private int selectItem = -1;

    private void findView() {
        et_hgtm = findViewById(R.id.et_hgtm);
        tv_sys = findViewById(R.id.tv_sys);
        btn_query = findViewById(R.id.btn_query);
        lv = findViewById(R.id.lv);
        et_xm = findViewById(R.id.et_xm);
        et_ms = findViewById(R.id.et_ms);
        et_sl = findViewById(R.id.et_sl);
        et_sjsl = findViewById(R.id.et_sjsl);
        btn_save = findViewById(R.id.btn_save);
        btn_cancel = findViewById(R.id.btn_cancel);
        btn_itqz = findViewById(R.id.btn_itqz);
        ll = findViewById(R.id.ll);
        etXmh = findViewById(R.id.et_xmh);
        tvSyswz = findViewById(R.id.tv_syswz);
        spBz = findViewById(R.id.sp_bz);
        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(UiUtlis.getText(etXmh)) || !TextUtils.isEmpty(UiUtlis.getText(et_hgtm))) {
                    requestData("加载中...");
                    UiUtlis.hideInput(et_hgtm, context);
                } else {
                    showToast("请输入货架号或物资号");
                }
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectItem != -1) {
                    if (!TextUtils.isEmpty(et_sjsl.getText().toString())) {
                        for (int i = 0; i < infos.size(); i++) {
                            if (infos.get(i).isFlag()) {
                                //判断是否已经盘点
                                if (infos.get(i).getIspd().equals("1")) {
                                    showPdDialog(false);
                                } else {
                                    //如果没有盘点，就盘点
                                    scData(toJson("1"));
                                }
                            }
                        }
                    } else {
                        showToast("你还没有输入盘点数量");
                    }
                } else {
                    //如果没有选中，点击保存。
                    if (!UiUtlis.getText(et_sjsl).isEmpty() && !UiUtlis.getText(et_hgtm).isEmpty() && !UiUtlis.getText(etXmh).isEmpty()) {
                        boolean ispd = false;
                        if (infos.size() != 0) {
                            for (KcpdInfo.kcpd kcpd : infos) {

                                if (kcpd.getIspd().equals("1") && kcpd.getBinnum().equals(UiUtlis.getText(et_hgtm))) {
                                    ispd = true;
                                    break;
                                }
                            }
                            playSound();
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setCancelable(false);
                            builder.setTitle("提示");
                            builder.setMessage("该物资未在该货架下，确定保存吗？");
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            final boolean finalIspd = ispd;
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    //如果已经盘点。就覆盖。
                                    if (finalIspd) {
                                        showPdDialog(true);
                                    } else {
                                        String json = addJson("4", infos.get(0));
                                        scData(json);
                                    }
                                    dialog.dismiss();

                                }
                            });
                            builder.create().show();
                        }
                    } else {
                        showToast("你还有数据未输入");
                    }
                }
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeView();
            }
        });
        tv_sys.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(KcpdActivity.this, MipcaActivityCapture.class);
                startActivityForResult(intent, 1);
            }
        });
        tvSyswz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(KcpdActivity.this, MipcaActivityCapture.class);
                startActivityForResult(intent1, 2);
            }
        });
        btn_itqz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etXmh.setText("IT");
                etXmh.setSelection(2);
            }
        });
    }

    @Override
    public int getContentViewID() {
        return R.layout.activity_kcpd;
    }

    protected void initView() {
        findView();
    }

    public void initData() {
        pdid = (String) getIntent().getExtras().get(Contans.KEY_PDID);
        setTitle("库存盘点");
        setBack();

//        et_sjsl.setEnabled(false);
//        et_hgtm.setText("IT");
        infos = new ArrayList<>();
        headView = View.inflate(this, R.layout.list_item1, null);
        headView.findViewById(R.id.cb_isprint).setEnabled(false);
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String resultText = bundle.getString("result");
                    et_hgtm.setText(resultText);
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String resultText = bundle.getString("result");
                    etXmh.setText(resultText);
                }
                break;
        }
    }

    //CheckBox点击事件
    @Override
    public void cbClick(View view) {
        int index = (int) view.getTag();
        CheckBox cb = (CheckBox) view;
        if (cb.isChecked() == false) {
            infos.get(index).setFlag(false);
            clearView();
        } else {
            infos.get(index).setFlag(true);
            for (int a = 0; a < infos.size(); a++) {
                if (a != index) {
                    infos.get(a).setFlag(false);
                }
            }
            updateView(index);
            adapter.notifyDataSetChanged();
        }
    }

    private void showPdDialog(final boolean isAdd) {
        final PdDialog dialog = new PdDialog(this);
        dialog.setFgOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!isAdd) {
                    scData(toJson("2"));
                } else {
                    scData(addJson("2", infos.get(0)));
                }
                dialog.close();
            }
        });

        dialog.setXjOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isAdd) {
                    scData(toJson("3"));
                } else {
                    scData(addJson("3", infos.get(0)));
                }
                dialog.close();
            }
        });

        dialog.setQxOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_sjsl.setText("");
                dialog.close();
            }
        });
    }

    private void requestData(String msg) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.PDJH);
        request.add("pdid", pdid);
        request.add("itemnum", UiUtlis.getText(etXmh));
        request.add("binnum", UiUtlis.getText(et_hgtm));
        NohttpUtils.getInstance().add(KcpdActivity.this, 0, request, callback, true, true, msg);
    }

    //上传数据
    private void scData(String json) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.PDJHSC, RequestMethod.POST);
        request.setDefineRequestBodyForJson(json);
        NohttpUtils.getInstance().add(KcpdActivity.this, 1, request, callback, true, true, UiUtlis.getString(context, R.string.upload));
    }

    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {

            switch (what) {
                case 0:
                    KcpdInfo kcpdInfo = GsonUtils.GsonToBean(response.get(), KcpdInfo.class);
                    if (kcpdInfo != null) {
                        if (kcpdInfo.getTotal() != 0) {
                            if (TextUtils.isEmpty(UiUtlis.getText(et_hgtm))) {
                                playSound();
                                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                builder.setCancelable(false);
                                builder.setTitle("提示");
                                builder.setMessage("该货柜下无此物资");
                                builder.setPositiveButton("返回", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                builder.create().show();
                            }
                            infos.clear();
                            infos.addAll(kcpdInfo.getRows());
                            setListData();
                        } else {
                            infos.clear();
                            if (adapter != null) {
                                if (lv.getHeaderViewsCount() == 1) {
                                    lv.removeHeaderView(headView);
                                }
                                adapter.notifyDataSetChanged();
                            }
                            showToast("没有该货柜信息");
                            ll.setVisibility(View.GONE);
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case 1:
                    StatusInfo info = GsonUtils.GsonToBean(response.get(), StatusInfo.class);
                    if (info != null) {
                        String status = info.getRows().get(0).getStatus();
                        if (status.equals("1")) {
                            showToast("盘点成功");
                            if (!UiUtlis.getText(etXmh).isEmpty()) {
                                removeView();
                            } else {
                                requestData("刷新..");
                            }
                            playSound();
                        } else if (status.equals("0")) {
                            showToast("盘点失败");
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {
            System.out.println("错误" + what + "==" + response.get());

        }
    };

    private void setListData() {

        ll.setVisibility(View.VISIBLE);
        if (lv.getHeaderViewsCount() != 1) {
            lv.addHeaderView(headView, null, false);
        }
        if (adapter == null) {
            adapter = new KcpdAdapter(infos, context, KcpdActivity.this);
            lv.setAdapter(adapter);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (i != 0) {
                        if (infos.get(i - 1).isFlag() == true) {
                            infos.get(i - 1).setFlag(false);
                            clearView();
                        } else {
                            infos.get(i - 1).setFlag(true);
                            for (int a = 0; a < infos.size(); a++) {
                                if (a != i - 1) {
                                    infos.get(a).setFlag(false);
                                }
                            }
                            updateView(i - 1);
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            });
        } else {
            clearView();
            adapter.notifyDataSetChanged();
        }
    }

    private void updateView(int index) {
        selectItem = index;
        et_xm.setText(infos.get(index).getItemnum());
        et_ms.setText(infos.get(index).getDescription());
        et_sl.setText(infos.get(index).getCurbal() + "");
        et_sjsl.setText(infos.get(index).getCurbal() + "");
        et_sjsl.setEnabled(true);
        et_hgtm.setText(infos.get(index).getBinnum());
    }

    private void clearView() {
        selectItem = -1;
        spBz.setSelection(0);
        et_xm.setText("");
        et_ms.setText("");
        et_sl.setText("");
        et_sjsl.setText("");
//        et_sjsl.setEnabled(false);
    }

    private void removeView() {
        selectItem = -1;
        et_xm.setText("");
        et_ms.setText("");
        et_sl.setText("");
        et_sjsl.setText("");
//        et_sjsl.setEnabled(false);
        infos.clear();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
            lv.removeHeaderView(headView);
        }
        etXmh.setText("");
        ll.setVisibility(View.INVISIBLE);
    }

    private String toJson(String sjpdzt) {
        String json = "";
        if (selectItem != -1) {
            KcpdInfo info = new KcpdInfo();
            List<KcpdInfo.kcpd> list = new ArrayList<>();
            KcpdInfo.kcpd kcpd = infos.get(selectItem);
            kcpd.setPdsl(et_sjsl.getText().toString());
            kcpd.setPdr((String) SPUtils.get(context, Contans.USERNAME, ""));
            kcpd.setSjpdzt(sjpdzt);
            kcpd.setBz((String) spBz.getSelectedItem());
            kcpd.setUname((String) SPUtils.get(context, Contans.NAME, ""));
            list.add(kcpd);
            info.setRows(list);
            info.setTotal(1);
            json = GsonUtils.GsonString(info);
        }
        return json;
    }

    private String addJson(String sjpdzt, KcpdInfo.kcpd kcpd) {
        String json = "";
        KcpdInfo info = new KcpdInfo();
        List<KcpdInfo.kcpd> list = new ArrayList<>();
        kcpd.setPdsl(et_sjsl.getText().toString());
        kcpd.setPdr((String) SPUtils.get(context, Contans.USERNAME, ""));
        kcpd.setSjpdzt(sjpdzt);
        kcpd.setBz((String) spBz.getSelectedItem());
        kcpd.setUname((String) SPUtils.get(context, Contans.NAME, ""));
        kcpd.setBinnum(UiUtlis.getText(et_hgtm));
        list.add(kcpd);
        info.setRows(list);
        info.setTotal(1);
        json = GsonUtils.GsonString(info);
        return json;
    }

    private void playSound() {
        Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(this, sound);
        r.play();
//        MediaPlayer player= MediaPlayer.create(context, R.raw.ylzs);
//        player.setLooping(false);
//        player.setVolume(1.0f, 1.0f);
//        player.start();
    }
}