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


import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
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.contans.Contans;
import com.example.administrator.zhapp.entity.JstkInfo;
import com.example.administrator.zhapp.entity.WebServiceResult;
import com.example.administrator.zhapp.utils.EditTextListener;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.KsoapUtils;
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.WaitDialog;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
import org.ksoap2.serialization.SoapObject;
import java.util.ArrayList;
import java.util.List;

public class JstkActivity extends BaseActivity {

    EditText etCgdh;
    Button btnQuery;
    ListView lv;
    EditText etZysl;
    Button btnSave;
    Button btnCancel;
    LinearLayout ll;
    TextView tv_ms;

    private List<JstkInfo.Jstk> jstks;
    private CommonAdapter<JstkInfo.Jstk> adapter;

    private View headView;

    private int seletcitem = -1;

    private EditTextListener mEditTextListener;

    private void findView() {
        etCgdh = findViewById(R.id.et_cgdh);
        btnQuery = findViewById(R.id.btn_query);
        lv = findViewById(R.id.lv);
        etZysl = findViewById(R.id.et_zysl);
        btnSave = findViewById(R.id.btn_save);
        btnCancel = findViewById(R.id.btn_cancel);
        ll = findViewById(R.id.ll);
        tv_ms = findViewById(R.id.tv_ms);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seletcitem == -1) {
                    showToast("你还没有选择项目");
                    return;
                }
                if (UiUtlis.isEmpty(etZysl)) {
                    showToast("退回数量不能为空");
                    return;
                }
                matrReturn();

                System.out.println("描述：" + jstks.get(seletcitem).getDescription() + "==" + seletcitem);
            }
        });
        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UiUtlis.hideInput(etCgdh, context);
                if (UiUtlis.isEmpty(etCgdh)) {
                    showToast("采购单不能为空");
                    return;
                }
                requestData();
            }
        });
    }


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

    @Override
    protected void initView() {
        findView();
        setTitle("接收退回");
        setBack();
        headView = View.inflate(context, R.layout.jsth_item, null);
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
        headView.findViewById(R.id.cb).setEnabled(false);
    }

    @Override
    public void initData() {

        jstks = new ArrayList<>();
        mEditTextListener = new EditTextListener(JstkActivity.this);
        etZysl.addTextChangedListener(mEditTextListener);

    }

    private void matrReturn() {


        final WaitDialog dialog = new WaitDialog(context, "保存中...");
        dialog.show();


        List<String> properties = new ArrayList<>();
        JstkInfo.Jstk jstk = jstks.get(seletcitem);
        properties.add(jstk.getPonum());//采购单号
        properties.add(jstk.getMatrectransid());//要退回接收的对应ID
        properties.add(UiUtlis.getText(etZysl));//退回数量
        properties.add((String) SPUtils.get(context, Contans.USERNAME, ""));//请求人

        KsoapUtils.callWebService(Contans.CK_BASE_IP + Contans.MATRSER_IP, "matrReturn", properties, new KsoapUtils.CallBack() {
            @Override
            public void callBack(SoapObject result) {
                dialog.dismiss();
                if (result != null) {
                    WebServiceResult webServiceResult = GsonUtils.GsonToBean(result.getProperty(0).toString(), WebServiceResult.class);

                    if (webServiceResult.getStatus().equals("success")) {
                        showToast("保存成功");
                        requestData();
                    } else {
                        showToast("保存失败");
                    }
                } else {
                    showToast(UiUtlis.getString(context, R.string.data_error));
                }
            }
        });

    }

    private void requestData() {


        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.JSTH, RequestMethod.GET);
        request.add("PONUM", UiUtlis.getText(etCgdh));
        request.add("siteid", "");
        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) {

            try {
                switch (what) {
                    case 0:
//                        String json = "{\"Rows\":[{\"ponum\":\"P1800\",\"itemnum\":\"IT02890\",\"description\":\"高钠电极 100045\",\"quantity\":\"10\",\"matrectransid\":\"114044\",\"returnnum\":\"10\"},{\"ponum\":\"P1800\",\"itemnum\":\"IT01109\",\"description\":\"层压钢锁38mm\",\"quantity\":\"2\",\"matrectransid\":\"114054\",\"returnnum\":\"1\"},{\"ponum\":\"P1800\",\"itemnum\":\"IT01109\",\"description\":\"层压钢锁38mm\",\"quantity\":\"1\",\"matrectransid\":\"114058\",\"returnnum\":\"1\"},{\"ponum\":\"P1800\",\"itemnum\":\"IT01109\",\"description\":\"层压钢锁38mm\",\"quantity\":\"1\",\"matrectransid\":\"114063\",\"returnnum\":\"1\"}],\"Total\":\"4\"}";
                        JstkInfo info = GsonUtils.GsonToBean(response.get(), JstkInfo.class);
                        if (info != null) {
                            if (!info.getTotal().equals("0")) {
                                jstks.clear();
                                jstks.addAll(info.getRows());
                                setListAdapter();
                                clearView();
                            } else {
                                ll.setVisibility(View.GONE);
                                jstks.clear();
                                if (adapter != null) {
                                    adapter.notifyDataSetChanged();
                                }
                                showToast("未查询到该采购单数据");
                            }
                        }
                        break;
                }
            } catch (Exception e) {
                showToast("数据出错");
                e.printStackTrace();
            }
        }

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

        }
    };

    //加载列表
    private void setListAdapter() {

        ll.setVisibility(View.VISIBLE);

        if (adapter != null) {
            adapter.notifyDataSetChanged();
            return;
        }

        adapter = new CommonAdapter<JstkInfo.Jstk>(this, R.layout.jsth_item, jstks) {
            @Override
            protected void convert(ViewHolder viewHolder, JstkInfo.Jstk item, final int position) {

                viewHolder.setText(R.id.tv_ponum, item.getPonum());
                viewHolder.setText(R.id.tv_itemnum, item.getItemnum());
                viewHolder.setText(R.id.tv_description, item.getDescription());
                viewHolder.setText(R.id.tv_quantity, item.getQuantity());
                viewHolder.setText(R.id.tv_returnnum, item.getReturnnum());
                viewHolder.setChecked(R.id.cb, item.isChecked());

                viewHolder.setOnClickListener(R.id.cb, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CheckBox cb = (CheckBox) v;
                        //如果没有选中。
                        if (!cb.isChecked()) {
                            jstks.get(position).setChecked(false);
                            clearView();
                        } else {
                            jstks.get(position).setChecked(true);
                            for (int a = 0; a < jstks.size(); a++) {
                                if (a != position) {
                                    jstks.get(a).setChecked(false);
                                }
                            }
                            updateView(position);
                            etZysl.setEnabled(true);
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        };
        if (lv.getHeaderViewsCount() == 0) {
            lv.addHeaderView(headView, null, false);
        }
        lv.setAdapter(adapter);
    }


    private void clearView() {
        seletcitem = -1;
        etZysl.setText("");
        etZysl.setEnabled(false);
        tv_ms.setText("");
    }

    private void updateView(int position) {

        seletcitem = position;
        etZysl.setEnabled(true);
        mEditTextListener.setMsg("退回数量不能大于可退回数量");
        mEditTextListener.setNum(jstks.get(position).getReturnnum());

        tv_ms.setText("项目：" + jstks.get(position).getItemnum() + "   描述：" + jstks.get(position).getDescription());

    }
}
