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

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.adapter.HjywAdapter;
import com.example.administrator.zhapp.adapter.SpinnerAdapter;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.HgInfo;
import com.example.administrator.zhapp.entity.HjywInfo;
import com.example.administrator.zhapp.entity.StatusInfo;
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 ShelvesShift extends BaseActivity implements HjywAdapter.CallBack {

    EditText tv_wlbm;
    Button btn_query;
    ListView lv;
    EditText et_zysl;
    TextView tv_yhg;
    EditText et_yrhg;
    Button btn_save;
    Button btn_cancel;
    LinearLayout ll;
    Button btnItqz;
    Spinner sp_hg;


    private View headView;
    private List<HjywInfo.Hjyw> infos;
    private HjywAdapter adapter;
    private EditTextListener editTextListener;
    private String wlbm = "";
    private SpinnerAdapter sAdapter;
    private List<HgInfo.Hg> hgs;

    private void findView() {
        tv_wlbm = findViewById(R.id.tv_wlbm);
        btn_cancel = findViewById(R.id.btn_cancel);
        lv = findViewById(R.id.lv);
        et_zysl = findViewById(R.id.et_zysl);
        tv_yhg = findViewById(R.id.tv_yhg);
        et_yrhg = findViewById(R.id.et_yrhg);
        btn_query = findViewById(R.id.btn_query);
        btn_save = findViewById(R.id.btn_save);
        ll = findViewById(R.id.ll);
        btnItqz = findViewById(R.id.btn_itqz);
        sp_hg = findViewById(R.id.sp_hg);
        btnItqz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_wlbm.setText("IT");
                tv_wlbm.setSelection(2);
            }
        });
        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //隐藏软键盘
                UiUtlis.hideInput(tv_wlbm, context);
                wlbm = tv_wlbm.getText().toString();
                if (!TextUtils.isEmpty(wlbm)) {
                    sendNohttpRequest(wlbm, UiUtlis.getString(context, R.string.loading));
                } else {
                    showToast("请输入物料编码");
                }
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (position != 0) {

                            if (infos.get(position - 1).isChecked() == true) {
                                infos.get(position - 1).setChecked(false);
                                clearView();
                            } else {
                                infos.get(position - 1).setChecked(true);
                                for (int a = 0; a < infos.size(); a++) {
                                    if (a != position - 1) {
                                        infos.get(a).setChecked(false);
                                    }
                                }
                                updataView(position - 1);
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast(UiUtlis.getString(context, R.string.cancel));
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UiUtlis.isEmpty(et_zysl)) {
                    showToast("转移数量不能为空");
                    return;
                }

                HgInfo.Hg hg = (HgInfo.Hg) sp_hg.getSelectedItem();

                if (hg.getLotnum().equals("请选择目标批次")) {
                    showToast("你还没有选择目标批次");
                    return;
                }

                if (UiUtlis.isEmpty(et_yrhg)) {
                    showToast("移入货柜不能为空");
                    return;
                }
                matrTran();
            }
        });
    }

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

    protected void initView() {
        findView();
    }

    public void initData() {

        setTitle("货架移位");
        setBack();

        hgs = new ArrayList<>();
        //tv_wlbm.setText("IT00075");
//        tv_wlbm.setText("IT");

        headView = View.inflate(this, R.layout.ss_item, null);
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
        headView.findViewById(R.id.cb).setEnabled(false);
        infos = new ArrayList<>();
        editTextListener = new EditTextListener(ShelvesShift.this);
        et_zysl.addTextChangedListener(editTextListener);
        et_zysl.setEnabled(false);
    }

    //checkbox点击事件
    @Override
    public void Click(View view) {

        int index = (int) view.getTag();
        CheckBox cb = (CheckBox) view;
        if (cb.isChecked() == false) {
            infos.get(index).setChecked(false);
            clearView();
        } else {
            infos.get(index).setChecked(true);
            for (int a = 0; a < infos.size(); a++) {
                if (a != index) {
                    infos.get(a).setChecked(false);
                }
            }
            updataView(index);
            adapter.notifyDataSetChanged();
        }
    }

    public void sendNohttpRequest(String wlbm, String msg) {

        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.HJYW);
        request.set("itemnum", wlbm);
        NohttpUtils.getInstance().add(ShelvesShift.this, 0, request, callback, true, true, msg);
    }


    //调用webservice 转移接口
    public void matrTran() {

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

        KsoapUtils.callWebService(Contans.CK_BASE_IP + Contans.MATRSER_IP, "matrTran", 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("保存成功");
                        sendNohttpRequest(wlbm, UiUtlis.getString(context, R.string.refresh));
                    } else {
                        showToast("保存失败");
                    }
                } else {
                    showToast(UiUtlis.getString(context, R.string.data_error));
                }
            }
        });
    }

    public void sendNohttpRequestPost(String json) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.HJYWSC, RequestMethod.POST);
        request.setDefineRequestBodyForJson(json);
        NohttpUtils.getInstance().add(ShelvesShift.this, 1, request, callback, true, true, "上传中...");
    }


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

            switch (what) {
                case 0:
                    HjywInfo info = GsonUtils.GsonToBean(response.get(), HjywInfo.class);
                    if (info != null) {
                        if (info.getTotal() != 0) {
                            ll.setVisibility(View.VISIBLE);
                            infos.clear();
                            infos.addAll(info.getRows());
                            if (adapter == null) {
                                adapter = new HjywAdapter(infos, ShelvesShift.this, ShelvesShift.this);
                                lv.addHeaderView(headView, null, false);
                                lv.setAdapter(adapter);
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            ll.setVisibility(View.GONE);
                            showToast("没有查到该条数据");
                            if (infos != null) {
                                infos.clear();
                                if (adapter != null) {
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    clearView();
                    break;
                case 1:
                    StatusInfo statusInfo = GsonUtils.GsonToBean(response.get(), StatusInfo.class);
                    if (statusInfo != null) {
                        String status = statusInfo.getRows().get(0).getStatus();
                        if (status.equals("1")) {
                            showToast(UiUtlis.getString(context, R.string.upload_success));
                            sendNohttpRequest(wlbm, UiUtlis.getString(context, R.string.refresh));
                        } else if (status.equals("0")) {
                            showToast(UiUtlis.getString(context, R.string.upload_error));
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case 2:
                    HgInfo hg = GsonUtils.GsonToBean(response.get(), HgInfo.class);
                    if (hg != null) {
                        hgs.clear();
                        HgInfo.Hg item = new HgInfo.Hg();
                        item.setLotnum("请选择目标批次");
                        hgs.add(item);
                        hgs.addAll(hg.getRows());
                        setSpinnerData();
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
            }
        }

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

        }
    };

    private void setSpinnerData() {

        if (sAdapter == null && hgs.size() != 0) {
            sAdapter = new SpinnerAdapter(hgs, context);
            sAdapter.setType("lotnum");
            sp_hg.setAdapter(sAdapter);
        } else if (sAdapter != null) {
            sAdapter.notifyDataSetChanged();
        }

    }

    private String toJson() {
        String json = "";
        for (int i = 0; i < infos.size(); i++) {
            if (infos.get(i).isChecked()) {
                HjywInfo info = new HjywInfo();
                List<HjywInfo.Hjyw> hjyws = new ArrayList<>();
                HjywInfo.Hjyw hjyw = new HjywInfo.Hjyw();
                hjyw = infos.get(i);
                hjyw.setEnterby((String) SPUtils.get(ShelvesShift.this, Contans.USERNAME, ""));
                hjyw.setMovehg(et_yrhg.getText().toString().trim().toUpperCase());
                hjyw.setZysl(et_zysl.getText().toString().trim());
                hjyws.add(hjyw);
                info.setRows(hjyws);
                info.setTotal(1);
                json = GsonUtils.GsonString(info);
            }
        }
        return json;
    }

    //请求参数
    private List properties() {

        List<String> properties = new ArrayList<>();

        for (int i = 0; i < infos.size(); i++) {
            if (infos.get(i).isChecked()) {
                HjywInfo info = new HjywInfo();
                List<HjywInfo.Hjyw> hjyws = new ArrayList<>();
                HjywInfo.Hjyw hjyw = new HjywInfo.Hjyw();
                hjyw = infos.get(i);

                properties.add(hjyw.getItemnum());//物资编码
                properties.add(hjyw.getLocation());//原仓库
                properties.add(hjyw.getBinnum());//原货柜
                properties.add(hjyw.getLocation());//仓库
                properties.add(UiUtlis.getText(et_yrhg));//货柜
                properties.add(hjyw.getLotnum());//原批次

                HgInfo.Hg hg = (HgInfo.Hg) sp_hg.getSelectedItem();

                properties.add(hg.getLotnum());//新批次

//                properties.add(UiUtlis.getText(etMbpc));//目标批次
                properties.add(UiUtlis.getText(et_zysl));//转移数量
                properties.add((String) SPUtils.get(context, Contans.USERNAME, ""));
            }
        }
        return properties;
    }


    private void clearView() {
        et_zysl.setText("");
        et_yrhg.setText("");
        tv_yhg.setText("");
        et_zysl.setEnabled(false);
//        etMbpc.setText("");
//        etMbpc.setEnabled(false);
        et_yrhg.setText("");
        et_yrhg.setEnabled(false);
        hgs.clear();
        setSpinnerData();
    }

    private void updataView(int index) {
        //加载目标批次
        requestHg(infos.get(index).getBinnum());
        editTextListener.setMsg("转移数量不能大于原数量");
        editTextListener.setNum(infos.get(index).getCurbal());
        tv_yhg.setText(infos.get(index).getBinnum());
        et_zysl.setText("");
        et_zysl.setEnabled(true);
//        etMbpc.setText("");
//        etMbpc.setEnabled(true);
        et_yrhg.setText("");
        et_yrhg.setEnabled(true);
    }

    private void requestHg(String binnum) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.HJYW);
        request.set("tobin", binnum);
        NohttpUtils.getInstance().add(this, 2, request, callback, true, true, "加载目标批次中...");
    }

}