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

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.administrator.zhapp.BaseListViewAdapter.CommonAdapter;
import com.example.administrator.zhapp.BaseListViewAdapter.ViewHolder;
import com.example.administrator.zhapp.BuildConfig;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.PhotoActivity;
import com.example.administrator.zhapp.activity.ydckgl.MateLablePrint;
import com.example.administrator.zhapp.adapter.YsPzAdapter;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.JsjlInfo;
import com.example.administrator.zhapp.entity.StatusInfo;
import com.example.administrator.zhapp.entity.WebServiceResult;
import com.example.administrator.zhapp.entity.YsPzjsInfo;
import com.example.administrator.zhapp.fragment.BaseFragment;
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.orhanobut.logger.Logger;
import com.yolanda.nohttp.FileBinary;
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.io.File;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;


/**
 * 移动仓库管理-验收与批准接收
 */
public class YsAndPzFragment extends BaseFragment implements YsPzAdapter.CallBack {

    EditText cgd;
    Button btn_query;
    ListView lv;
    EditText et_jssl;
    EditText et_mbwz;
    EditText et_mbhg;
    Button btn_save;
    Button btn_cancel;
    Button btn_pz;
    Button btn_sc;
    ImageView iv_result;
    LinearLayout ll;
    TextView tv_ms;
    Button btn_jsjl;
    EditText etItemnum;
    Button btnIt;
    ScrollView sv;

    private MateLablePrint mActivity;
    private View headView;
    private YsPzAdapter adapter;
    private YsPzjsInfo info;
    private List<YsPzjsInfo.YsPzjs> lists;
    private String path;
    private String fileName = "";
    private int selectItem = -1;
    private int index = -1;
    private EditTextListener editTextListener;
    private boolean flag = false;//拍照的标志

    private WaitDialog loading;

    private String itemnum = "";

    private String lastFileName;

    private List<JsjlInfo.Jsjl> jsjls;


    public YsAndPzFragment() {
    }

    public static YsAndPzFragment newInstance() {
        YsAndPzFragment fragment = new YsAndPzFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_ys_and_pz;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {
        cgd = view.findViewById(R.id.cgd);
        btn_query = view.findViewById(R.id.btn_query);
        lv = view.findViewById(R.id.lv);
        et_jssl = view.findViewById(R.id.et_jssl);
        et_mbwz = view.findViewById(R.id.et_mbwz);
        et_mbhg = view.findViewById(R.id.et_mbhg);
        btn_save = view.findViewById(R.id.btn_save);
        btn_cancel = view.findViewById(R.id.btn_cancel);
        btn_pz = view.findViewById(R.id.btn_pz);
        btn_sc = view.findViewById(R.id.btn_sc);
        iv_result = view.findViewById(R.id.iv_result);
        ll = view.findViewById(R.id.ll);
        tv_ms = view.findViewById(R.id.tv_ms);
        btn_jsjl = view.findViewById(R.id.btn_jsjl);
        etItemnum = view.findViewById(R.id.et_itemnum);
        btnIt = view.findViewById(R.id.btn_it);
        sv = view.findViewById(R.id.sv);

        btn_pz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cropFromTake();
            }
        });
        btn_sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag) {
                    UploadFile();
                } else {
                    showToast("你还没有拍照");
                }
            }
        });
        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //隐藏软键盘
                UiUtlis.hideInput(cgd, context);
                String str = cgd.getText().toString().trim();
                if (!TextUtils.isEmpty(str)) {
                    sendNohttpRequest(str);
                } else {
                    showToast("请输入采购单");
                }
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectItem == -1) {
                    showToast("你还没有选择项目");
                } else {
                    if (TextUtils.isEmpty(UiUtlis.getText(et_jssl))) {
                        showToast("接收数量不能为空");
                        return;
                    }
                    matrRec();
                }
            }
        });
        iv_result.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), PhotoActivity.class);
                intent.putExtra("fileName", fileName);
                intent.putExtra("path", path + fileName);
                startActivity(intent);
            }
        });
        btn_jsjl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectItem != -1 && lists.size() != 0) {
                    requestJsjl(lists.get(selectItem).getPonum(), lists.get(selectItem).getItemnum());
                } else {
                    requestJsjl("", UiUtlis.getText(etItemnum));
                }
                UiUtlis.hideInput(etItemnum, context);
            }
        });
        btnIt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etItemnum.setText("IT");
                etItemnum.setSelection(2);
            }
        });


        jsjls = new ArrayList<>();

        mActivity = (MateLablePrint) getActivity();
        mActivity.getToolbar().setText("验收与批准接收");
        headView = View.inflate(getContext(), R.layout.receive_list, null);
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
        TextView tv = (TextView) headView.findViewById(R.id.tv_attr);
        tv.setText("公司");
        TextView tv1 = (TextView) headView.findViewById(R.id.tv_kjs);
        tv1.setText("接收数量");
        TextView tv2 = (TextView) headView.findViewById(R.id.tv_count);
        tv2.setText("已检验数量");

        headView.findViewById(R.id.cb_isprint).setEnabled(false);

//        ll.setVisibility(View.VISIBLE);

        //设置事件冲突
        lv.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    sv.requestDisallowInterceptTouchEvent(false);
                } else {
                    sv.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
    }

    @Override
    public void initData() {

        loading = new WaitDialog(context, "加载中...");


        editTextListener = new EditTextListener(context);
        et_jssl.addTextChangedListener(editTextListener);
        et_jssl.setEnabled(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            flag = true;//拍照的标志
            switch (requestCode) {
                case 9:
                    carpImageUri();
//                    Bitmap bitmap = BitmapFactory.decodeFile(path + fileName);
//                    iv_result.setImageBitmap(bitmap);
//                    lastFileName = fileName;
                    break;
                case 8:
                    Bitmap bitmap = BitmapFactory.decodeFile(path + fileName);
                    iv_result.setImageBitmap(bitmap);
                    lastFileName = fileName;
                    break;
            }
        }
    }

    private void carpImageUri() {

//        Uri uri = Uri.fromFile(new File(path + fileName));
        Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", new File(path + fileName));
        Uri outPutUri = Uri.fromFile(new File(path + fileName));
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
//        intent.putExtra("aspectX", 450);
//        intent.putExtra("aspectY", 300);
//        intent.putExtra("outputX", 450);
//        intent.putExtra("outputY", 300);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 8);
    }

    @Override
    public void Click(View v) {
        index = (int) v.getTag();
        CheckBox cb = (CheckBox) v;

        if (!cb.isChecked()) {
            lists.get(index).setChecked(false);
            clearView();
            selectItem = -1;
        } else {
            lists.get(index).setChecked(true);
            for (int a = 0; a < lists.size(); a++) {
                if (a != index) {
                    lists.get(a).setChecked(false);
                }
            }
            updataView(index);
            selectItem = index;
        }
        adapter.notifyDataSetChanged();
    }

    //调用webservice 接收接口
    private void matrRec() {

        List<String> properties = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i).isChecked()) {
                properties.add(lists.get(i).getPonum());//采购单号
                properties.add(lists.get(i).getItemnum());//物资编码
                properties.add(UiUtlis.getText(et_mbhg));//目标货柜
                properties.add(UiUtlis.getText(et_jssl));//检验数量
                properties.add((String) SPUtils.get(context, Contans.USERNAME, ""));
            }
        }
        final WaitDialog dialog = new WaitDialog(context, "保存中...");
        dialog.show();


        KsoapUtils.callWebService(Contans.CK_BASE_IP + Contans.MATRSER_IP, "matrRec", 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(UiUtlis.getText(cgd));
                    } else {
                        showToast("保存失败");
                    }
                } else {
                    showToast(UiUtlis.getString(context, R.string.data_error));
                }
            }
        });
    }


    private void upload() {
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i).isChecked()) {
                lists.get(i).setAcceptedqty(et_jssl.getText().toString().trim());
                lists.get(i).setTostoreloc(et_mbwz.getText().toString().trim());
                lists.get(i).setTobin(et_mbhg.getText().toString().trim().toUpperCase());
                lists.get(i).setEnterby((String) SPUtils.get(getContext(), Contans.USERNAME, ""));
                YsPzjsInfo yspz = new YsPzjsInfo();
                List<YsPzjsInfo.YsPzjs> list = new ArrayList<>();
                list.add(lists.get(i));
                yspz.setRows(list);
                yspz.setTotal(list.size());
                String json = GsonUtils.GsonString(yspz);
                sendNohttpRequestPost(json);
                Logger.v("json" + json);
            }
        }
    }

    private void cropFromTake() {


        if (itemnum.equals("")) {
            showToast("你还没有选择项目");
            return;
        }

        fileName = itemnum + ".jpg";
        // 跳转至拍照界面
        path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "/com.rehome.ydapp/images/";
        File fos = new File(path + fileName);
//        Uri u = Uri.fromFile(fos);
        Uri u = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", fos);
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        i.putExtra(MediaStore.EXTRA_OUTPUT, u);
        startActivityForResult(i, 9);
    }

    /**
     * 查询
     *
     * @param cgd
     */
    public void sendNohttpRequest(String cgd) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.YSPZJS);
        request.set("ponum", cgd);
        request.set("siteid",  "");
        NohttpUtils.getInstance().add(getActivity(), CX_FLAG, request, mListener, true, true, UiUtlis.getString(getContext(), R.string.loading));
    }

    /**
     * 上传
     *
     * @param json
     */
    public void sendNohttpRequestPost(String json) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.YSPZJSSC, RequestMethod.POST);
        request.setDefineRequestBodyForJson(json);
        Logger.json(json);
        NohttpUtils.getInstance().add(getActivity(), SC_FLAG, request, mListener, true, true, "上传中...");
    }

    public void UploadFile() {

        if (selectItem == -1) {
            showToast("你没有选择项目，不能上传图片");
        } else {

            if (!TextUtils.isEmpty(lastFileName)) {
                Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.WZTPSC +
                        "?fname=" + lastFileName +
                        "&itemid=" + lists.get(selectItem).getItemid() +
                        "&operid=" + SPUtils.get(context, Contans.USERNAME, "") +
                        "&type=1" +
                        "&itemnum=" + lists.get(selectItem).getItemnum(), RequestMethod.POST);
                request.add(Contans.FILEPS, new FileBinary(new File(path + lastFileName)));
                NohttpUtils.getInstance().add(getActivity(), 2, request, mListener, true, true, "上传图片中");
            } else {
                showToast("你还没有拍照");
            }
        }
    }

    private HttpListener<String> mListener = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {
            String json;
            switch (what) {
                case CX_FLAG:
                    json = response.get();
                    info = GsonUtils.GsonToBean(json, YsPzjsInfo.class);
                    if (info != null) {
                        lastFileName = "";
                        iv_result.setImageBitmap(null);
                        if (info.getTotal() == 0) {
                            showToast("没有查到该条数据");
                            ll.setVisibility(View.GONE);
                            cgd.setText("");
                            if (adapter != null) {
                                if (lv.getHeaderViewsCount() == 1) {
                                    lv.removeHeaderView(headView);
                                }
                                lists.clear();
                                selectItem = -1;
                                adapter.notifyDataSetChanged();
                            }
                        } else {
                            clearView();
                            lists = new ArrayList<>();
                            lists = info.getRows();
                            ll.setVisibility(View.VISIBLE);
                            adapter = new YsPzAdapter(lists, getContext(), YsAndPzFragment.this);
                            if (lv.getHeaderViewsCount() != 1) {
                                lv.addHeaderView(headView, null, false);
                            }
                            lv.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                            listViewOnItemClick();
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case SC_FLAG:
                    json = response.get();
                    System.out.println(json + "测试");
                    StatusInfo info = GsonUtils.GsonToBean(json, StatusInfo.class);
                    if (info != null) {
                        String status = info.getRows().get(0).getStatus();
                        if (status.equals("1")) {
                            showToast("保存成功");
                            sendNohttpRequest(UiUtlis.getText(cgd));
                        } else if (status.equals("0")) {
                            showToast("保存失败");
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case 2:
                    json = response.get();
                    StatusInfo info1 = GsonUtils.GsonToBean(json, StatusInfo.class);
                    if (info1 != null) {
                        String status1 = info1.getRows().get(0).getStatus();
                        if (status1.equals("1")) {
                            showToast("上传成功");
                            File file = new File(path + lastFileName);
                            //上传成功，就删除文件
                            if (file.isFile()) {
                                file.delete();
                            }
                            iv_result.setImageBitmap(null);
                        } else if (status1.equals("0")) {
                            showToast("上传失败");
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;

                case 3:

                    JsjlInfo jsjlInfo = GsonUtils.GsonToBean(response.get(), JsjlInfo.class);
                    if (jsjlInfo != null) {
                        if (!jsjlInfo.getTotal().equals("0")) {
                            jsjls.clear();
                            jsjls.addAll(jsjlInfo.getRows());
                            showjsjl();
                        } else {
                            showToast("没有接收记录");
                            loading.dismiss();
                        }

                    } else {
                        showToast("数据出错");
                        loading.dismiss();
                    }
                    break;
            }
        }

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

        }
    };

    private void listViewOnItemClick() {

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    if (lists.get(position - 1).isChecked()) {
                        lists.get(position - 1).setChecked(false);
                        clearView();
                        selectItem = -1;
                    } else {
                        lists.get(position - 1).setChecked(true);
                        for (int a = 0; a < lists.size(); a++) {
                            if (a != position - 1) {
                                lists.get(a).setChecked(false);
                            }
                        }
                        selectItem = position - 1;
                        updataView(position - 1);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void updataView(int i) {
        double num = UiUtlis.getNum(lists.get(i).getAcceptedqty());
        editTextListener.setNum(num + "");
        editTextListener.setMsg("接收数量不能大于已检验数量");
        et_mbwz.setText(lists.get(i).getTostoreloc());
        //et_mbhg.setText(lists.get(i).getTobin());
        et_jssl.setEnabled(true);
        itemnum = lists.get(i).getItemnum();
        tv_ms.setText("项目：" + lists.get(i).getItemnum() + "  描述：" + lists.get(i).getDescription1());

    }

    private void clearView() {
        et_mbhg.setText("");
        et_mbwz.setText("");
        et_jssl.setText("");
        et_jssl.setEnabled(false);
        tv_ms.setText("");
        iv_result.setImageBitmap(null);
        itemnum = "";
        fileName = "";
        lastFileName = "";
    }

    private void requestJsjl(String ponum, String itemnum) {
        loading.show();
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.YSPZJSJL);
        request.set("ponum", ponum);
        request.set("itemnum", itemnum);
        request.set("status", "1");
        NohttpUtils.getInstance().add(getActivity(), 3, request, mListener, true, true, "加载中...");
    }

    private void showjsjl() {
        final View view = View.inflate(context, R.layout.fljl_list, null);
        ListView lv = (ListView) view.findViewById(R.id.lv);

        loading.dismiss();

        CommonAdapter<JsjlInfo.Jsjl> ffjhadapter = new CommonAdapter<JsjlInfo.Jsjl>(context, R.layout.jsjl_item, jsjls) {
            @Override
            protected void convert(ViewHolder viewHolder, JsjlInfo.Jsjl item, int position) {

                viewHolder.setText(R.id.tv_xh, (position + 1) + "");
                viewHolder.setText(R.id.tv_itemnum, item.getItemnum());
                viewHolder.setText(R.id.tv_description, item.getDescription());
                viewHolder.setText(R.id.tv_actualdate, item.getActualdate());
                viewHolder.setText(R.id.tv_statusdate, item.getStatusdate());
                viewHolder.setText(R.id.tv_transdate, item.getTransdate());
                viewHolder.setText(R.id.tv_ponum, item.getPonum());
                viewHolder.setText(R.id.tv_quantity, item.getQuantity());
                viewHolder.setText(R.id.tv_receivedunit, item.getReceivedunit());
                viewHolder.setText(R.id.tv_unitcost, item.getUnitcost());
                viewHolder.setText(R.id.tv_linecost, item.getLinecost());
                viewHolder.setText(R.id.tv_issuetype, item.getIssuetype());
                viewHolder.setText(R.id.tv_tostoreloc, item.getTostoreloc());
                viewHolder.setText(R.id.tv_frombin, item.getFrombin());
                viewHolder.setText(R.id.tv_tobin, item.getTobin());
                viewHolder.setText(R.id.tv_enterby, item.getEnterby());
                viewHolder.setText(R.id.tv_statuschangeby, item.getStatuschangeby());
                viewHolder.setText(R.id.tv_remark, item.getRemark());
            }
        };
        View head = View.inflate(context, R.layout.jsjl_item, null);
        head.findViewById(R.id.head).setVisibility(View.VISIBLE);
        lv.addHeaderView(head, null, false);
        lv.setAdapter(ffjhadapter);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setView(view);
        builder.setCancelable(false);
        builder.setTitle("接收记录");
        builder.setPositiveButton("返回", (dialog, which) -> dialog.dismiss());
        builder.create().show();
    }
}