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

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.zhapp.BaseListViewAdapter.CommonAdapter;
import com.example.administrator.zhapp.BaseListViewAdapter.ViewHolder;
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.contans.Contans;
import com.example.administrator.zhapp.entity.KccxImgInfo;
import com.example.administrator.zhapp.entity.KccxInfo;
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.UiUtlis;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import androidx.appcompat.app.AlertDialog;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;


public class KccxActivity extends BaseActivity {
    EditText etBm;
    EditText etMs;
    EditText etHjh;
    TextView tv_sysit;
    TextView tv_syshgh;
    Button btnQuery;
    Button btn_it;
    ListView lv;
    ViewPager vp;

    private List<KccxInfo.Kccx> lists;

    private View headView;
    private CommonAdapter<KccxInfo.Kccx> adapter;
    private List<KccxImgInfo> imgs;

    private ViewPagerAdapter vpAdapter;

    private Bitmap bitmap;
    private void findView() {
        etBm = findViewById(R.id.et_bm);
        etMs = findViewById(R.id.et_ms);
        tv_sysit = findViewById(R.id.tv_sysit);
        etHjh = findViewById(R.id.et_hjh);
        tv_syshgh = findViewById(R.id.tv_syshgh);
        btnQuery = findViewById(R.id.btn_query);
        lv = findViewById(R.id.lv);
        vp = findViewById(R.id.vp);
        btn_it = findViewById(R.id.btn_it);
        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isQuery()) {
                    UiUtlis.hideInput(etHjh, context);
                    UiUtlis.hideInput(etMs, context);
                    UiUtlis.hideInput(etBm, context);
                    requestData();
                }
            }
        });
        btn_it.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etBm.setText("IT");
                etBm.setSelection(2);
            }
        });
        tv_sysit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(KccxActivity.this, MipcaActivityCapture.class);
                startActivityForResult(intent, 1);
            }
        });
        tv_syshgh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(KccxActivity.this, MipcaActivityCapture.class);
                startActivityForResult(intent1, 2);
            }
        });
    }

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

    @Override
    protected void initView() {
        findView();
        setBack();
        setTitle("库存查询");
    }

    @Override
    public void initData() {
        lists = new ArrayList<>();
        imgs = new ArrayList<>();
        headView = View.inflate(context, R.layout.kccx_item, null);
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
    }

    private void requestData() {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.KCCX);
        request.set("itemnum", UiUtlis.getText(etBm));
        request.set("description", UiUtlis.getText(etMs));
        request.set("binnum", UiUtlis.getText(etHjh));
        NohttpUtils.getInstance().add(this, 0, request, callback, true, true, "加载中...");
    }

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

            KccxInfo info = GsonUtils.GsonToBean(response.get(), KccxInfo.class);
            if (info != null) {
                if (!info.getTotal().equals("0")) {
                    lists.clear();
                    imgs.clear();
                    lists.addAll(info.getRows());

                    for (KccxInfo.Kccx kccx : lists) {

                        if (!kccx.getImglist().isEmpty()) {
                            KccxImgInfo imgInfo = new KccxImgInfo();
                            imgInfo.setTitle(kccx.getItemnum());
                            imgInfo.setImgUrl(kccx.getImglist());
                            imgs.add(imgInfo);
                        }
                    }

                    Set<KccxImgInfo> imgInfos = new HashSet<>();
                    imgInfos.addAll(imgs);
                    imgs.clear();
                    imgs.addAll(imgInfos);

                    setViewPagerImage();

                    System.out.println(imgs.size());

//                    byte[] img = info.getRows().get(0).getImglist().getBytes();
//                    Bitmap bitmap = getBitmapFromByte(img);
//                    iv.setImageBitmap(bitmap);

                    setList();
                } else {
                    lists.clear();
                    imgs.clear();
                    if (adapter != null) {
                        if (lv.getHeaderViewsCount() != 0) {
                            lv.removeHeaderView(headView);
                        }
                        adapter.notifyDataSetChanged();
                    }

                    if (vpAdapter != null) {
                        vp.setVisibility(View.GONE);
                        vpAdapter.notifyDataSetChanged();
                    }

                    showToast("没有查到符合条件记录");
                }
            } else {
                showToast("数据异常");
            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {

        }
    };

    private void setViewPagerImage() {

        if (imgs.size() != 0) {
            vp.setVisibility(View.VISIBLE);
            if (vpAdapter == null) {
                vpAdapter = new ViewPagerAdapter();
                vp.setAdapter(vpAdapter);
            } else {
                vpAdapter.notifyDataSetChanged();
            }
        } else {
            vp.setVisibility(View.GONE);

            if (vpAdapter != null) {
                vpAdapter.notifyDataSetChanged();
            }
            showToast("暂无图片数据");
        }
    }

    private void setList() {

        if (lv.getHeaderViewsCount() == 0) {
            lv.addHeaderView(headView, null, false);
        }

        if (adapter == null) {
            adapter = new CommonAdapter<KccxInfo.Kccx>(context, R.layout.kccx_item, lists) {
                @Override
                protected void convert(ViewHolder viewHolder, KccxInfo.Kccx item, int position) {
                    viewHolder.setText(R.id.tv_item, (position + 1) + "");
                    viewHolder.setText(R.id.tv_bm, item.getItemnum());
                    viewHolder.setText(R.id.tv_ms, item.getDescription());
                    viewHolder.setText(R.id.tv_xh, item.getIn19());
                    viewHolder.setText(R.id.tv_dw, item.getOrderunit());
                    viewHolder.setText(R.id.tv_hjh, item.getBinnum());
                    viewHolder.setText(R.id.tv_xgzy, item.getIn6());
                    viewHolder.setText(R.id.tv_hjzysx, item.getStocktype());
                    viewHolder.setText(R.id.tv_dqyl, item.getCurbal());
                    viewHolder.setText(R.id.tv_dqylsl, item.getReservedqty());
                }
            };
            lv.setAdapter(adapter);

            //不需要点击事件
//            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
////                    Request<Bitmap> bitmapRequest = NoHttp.createImageRequest("http://10.19.0.113:7004/maximo/webclient/skins/skins-20160720-2348/tivoli09/images/img_placeholderEnlarged.jpg?uisessionid=32");
//                    if (!lists.get(position - 1).getImglist().isEmpty()) {
//                        Request<Bitmap> bitmapRequest = NoHttp.createImageRequest(lists.get(position - 1).getImglist());
//                        NohttpUtils.getInstance().add(KccxActivity.this, position, bitmapRequest, bitmapCallback, true, true, "加载中...");
//                    } else {
//                        showToast("该物资暂无图片");
//                    }
//                }
//            });

        } else {
            adapter.notifyDataSetChanged();
        }
    }

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

            Bitmap bitmap = response.get();
            if (bitmap != null) {
                //显示一个Dialog
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                ImageView iv = new ImageView(context);
                iv.setImageBitmap(bitmap);
                builder.setView(iv);
//                builder.setTitle("图片信息");
                builder.setMessage("项目号:" + lists.get(what - 1).getItemnum());
                builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();
            } else {
                showToast("该物资没有图片");
            }
        }

        @Override
        public void onFailed(int what, Response<Bitmap> response) {

        }
    };

    private boolean isQuery() {

        if (!TextUtils.isEmpty(UiUtlis.getText(etBm)) || !TextUtils.isEmpty(UiUtlis.getText(etMs)) || !TextUtils.isEmpty(UiUtlis.getText(etHjh))) {
            return true;
        } else {
            showToast("请输入编码或描述或货架号");
            return false;
        }
    }

    @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");
                    etBm.setText(resultText);
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String resultText = bundle.getString("result");
                    etHjh.setText(resultText);
                }
                break;
        }
    }

    class ViewPagerAdapter extends PagerAdapter {

        private int mChildCount = 0;

        @Override
        public void notifyDataSetChanged() {
            mChildCount = getCount();
            super.notifyDataSetChanged();
        }

        /**
         * 重写getItemPosition，使得viewpager刷新
         *
         * @param object
         * @return
         */
        @Override
        public int getItemPosition(Object object) {
            if (mChildCount > 0) {
                mChildCount--;
                return POSITION_NONE;
            }
            return super.getItemPosition(object);
        }

        @Override
        public int getCount() {
            return imgs.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {

            View view = View.inflate(context, R.layout.kccx_img, null);
            final ImageView iv = (ImageView) view.findViewById(R.id.iv);
            TextView tv_item = (TextView) view.findViewById(R.id.tv_item);
            TextView tv_index = (TextView) view.findViewById(R.id.tv_index);

            tv_item.setText(imgs.get(position).getTitle());
            tv_index.setText(position + 1 + "/" + imgs.size());

            Request<Bitmap> bitmapRequest = NoHttp.createImageRequest(imgs.get(position).getImgUrl());
            NohttpUtils.getInstance().add(KccxActivity.this, 2, bitmapRequest, new HttpListener<Bitmap>() {
                @Override
                public void onSucceed(int what, Response<Bitmap> response) {

                    bitmap = response.get();
                    if (bitmap != null) {
                        iv.setImageBitmap(bitmap);
                    }
                }

                @Override
                public void onFailed(int what, Response<Bitmap> response) {

                }
            }, true, true, "加载图片中...");

            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(KccxActivity.this, CKPhotoActivity.class);
                    intent.putExtra("url", imgs.get(position).getImgUrl());
                    startActivity(intent);

                }
            });

            container.addView(view);
            return view;
        }
    }
}