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

import android.Manifest;
import android.app.Activity;
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.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.zhapp.BuildConfig;
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.activity.PhotoActivity;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.StatusInfo;
import com.example.administrator.zhapp.entity.Wztpscinfo;
import com.example.administrator.zhapp.entity.wztpBean;
import com.example.administrator.zhapp.utils.BaseCallBack;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.HttpUtils;
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.FileBinary;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;

public class WztpScActivity extends BaseActivity {



    private static final int STPZ = 101;
    private static final int STXC = 102;

    private static final int FJTPZ = 201;
    private static final int FJTXC = 202;

    private static final int STEND = 301;
    private static final int FJTEND = 302;

    private String imagePath = "";

//    @BindView(R.id.et_hgtm)
//    EditText etHgtm;
//    @BindView(R.id.tv_sys)
//    TextView tvSys;
//    @BindView(R.id.btn_it)
//    Button btnIt;
//    @BindView(R.id.btn_query)
//    Button btnQuery;
//    @BindView(R.id.btn_pz)
//    Button btnPz;
//    @BindView(R.id.btn_sc)
//    Button btnSc;
//    @BindView(R.id.tv_ms)
//    TextView tvMs;
//    @BindView(R.id.iv_st)
//    ImageView ivSt;
//    @BindView(R.id.iv_fjt)
//    ImageView ivFjt;
//    @BindView(R.id.ll)
//    LinearLayout ll;

    EditText etHgtm;
    TextView tvSys;
    Button btnIt;
    Button btnQuery;
    Button btnSc;
    Button btn_pzs;
    Button btn_xcs;
    Button btn_pzf;
    Button btn_xcf;
    TextView tvMs;
    ImageView ivSt;
    ImageView ivFjt;
    ImageView ivFlv;
    ImageView iv_del;
    TextView tv_duration;
    RelativeLayout iv_video;
    LinearLayout ll;
    RecyclerView mRecyclerView;
    CheckBox cb_crop;
    CheckBox cb_compress;
    CheckBox cbEditor;

    private WaitDialog dialog;

    private List<Wztpscinfo.Wztp> wztps;

    private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "/com.rehome.ydapp/images/";

    private String fileName;

    private String stFileName;
    private String fjtFileName;

    private String stEndName;//缩图最后名字
    private String fjtEndName;//附件图最后名字
    private String username;

    private void findView() {
        etHgtm = findViewById(R.id.et_hgtm);
        tvSys = findViewById(R.id.tv_sys);
        btnIt = findViewById(R.id.btn_it);
        btnQuery = findViewById(R.id.btn_query);
        btn_pzs = findViewById(R.id.btn_pzs);
        btn_xcs = findViewById(R.id.btn_xcs);
        btnSc = findViewById(R.id.btn_sc);
        btn_pzf = findViewById(R.id.btn_pzf);
        btn_xcf = findViewById(R.id.btn_xcf);
        tvMs = findViewById(R.id.tv_ms);
        ivSt = findViewById(R.id.iv_st);
        ivFjt = findViewById(R.id.iv_fjt);
        ll = findViewById(R.id.ll);
//        mRecyclerView = findViewById(R.id.recycler);
//        cb_crop = findViewById(R.id.cb_crop);
//        cb_compress = findViewById(R.id.cb_compress);
//        cbEditor = findViewById(R.id.cb_editor);
//
//        ivFlv = findViewById(R.id.fiv);
//        iv_del = findViewById(R.id.iv_del);
//        tv_duration = findViewById(R.id.tv_duration);
//        iv_video = findViewById(R.id.iv_video);


        //上传
        btnSc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(UiUtlis.getText(etHgtm)) && wztps.size() != 0 && !TextUtils.isEmpty(fileName)) {
                    dialog.show();
                    if (!TextUtils.isEmpty(stEndName)) {
                        uploadWZTP(stEndName);
                    } else if (!TextUtils.isEmpty(fjtEndName)) {
                        scData("2", 2, fjtEndName);
                    } else {
                        showToast("你还没有拍照，不能上传");
                    }
                } else {
                    showToast("数据错误，不能上传");
                }
            }
        });
        //IT前缀
        btnIt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etHgtm.setText("IT");
                etHgtm.setSelection(2);
            }
        });
        //查询
        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UiUtlis.hideInput(etHgtm, context);
                requestData();
            }
        });
        //扫码
        tvSys.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WztpScActivity.this, MipcaActivityCapture.class);
                startActivityForResult(intent, 1);
            }
        });
        iv_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_video.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.VISIBLE);
            }
        });
        //缩图预览
        ivSt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //缩图点击事件
                Intent st = new Intent(context, PhotoActivity.class);
                st.putExtra("fileName", stEndName);
                st.putExtra("path", path + stEndName);
                startActivity(st);
            }
        });
        //缩图拍照
        btn_pzs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //缩图拍照
                cropFromTake(UiUtlis.getText(etHgtm), STPZ);
            }
        });
        //缩图选择
        btn_xcs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent stxc = new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(stxc, STXC);
                //缩图相册
            }
        });
        //附件图预览
        ivFjt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //附件图
                Intent fjt = new Intent(context, PhotoActivity.class);
                fjt.putExtra("fileName", fjtEndName);
                fjt.putExtra("path", path + fjtEndName);
                startActivity(fjt);
            }
        });
        //附件图拍照
        btn_pzf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //附件图拍照
                cropFromTake(UiUtlis.getText(etHgtm) + "FJT", FJTPZ);
            }
        });
        //附件图选择
        btn_xcf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //相册附件图
                Intent fjtxc = new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(fjtxc, FJTXC);
            }
        });
    }

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

    @Override
    protected void initView() {
        findView();
        setBack();
        setTitle("物资图片上传");
        username = (String) SPUtils.get(context, Contans.USERNAME, "");
        wztps = new ArrayList<>();
        dialog = new WaitDialog(context, "上传中...");
    }

    @Override
    protected void initData() {

    }

    private void uploadWZTP(String stEndName) {
        Wztpscinfo.Wztp wztp = wztps.get(0);
        File wztpuploadfile = new File(path + stEndName);
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), wztpuploadfile);
        MultipartBody.Part body = MultipartBody.Part.createFormData("fileps", wztpuploadfile.getName(), requestFile);
        HttpUtils.getApi(context).uploadwztp(
                wztp.getItemnum(),
                wztp.getItemid(),
                username,
                "1",
                stEndName,
                body).enqueue(new BaseCallBack<wztpBean>(context) {
            @Override
            public void onSuccess(Call<wztpBean> call, retrofit2.Response<wztpBean> response) {
                wztpBean bean = response.body();
                if (bean != null) {
                    if (bean.getRows().get(0).getStatus().equals("1")) {
                        showToast("上传成功");
                        finish();
                    } else {
                        showToast("上传失败");
                    }
                }
            }

            @Override
            public void onError(Call<wztpBean> call, Throwable t) {

            }
        });

    }
    private void requestData() {

        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.WZTP);
        request.add("itemnum", UiUtlis.getText(etHgtm));
        NohttpUtils.getInstance().add(this, 0, request, callback, true, true, "加载中...");

    }



    private void scData(String type, int what, String name) {



        Wztpscinfo.Wztp wztp = wztps.get(0);
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.WZTPSC +
                        "?itemnum=" + wztp.getItemnum() +
                        "&itemid=" + wztp.getItemid() +
                        "&operid=" + SPUtils.get(context, Contans.USERNAME, "") +
                        "&type=" + type +
                        "&fname=" + name,
                RequestMethod.POST);
        request.add(Contans.FILEPS, new FileBinary(new File(path + name)));
        NohttpUtils.getInstance().add(this, what, request, callback, false, false, "上传中...");
    }




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

            System.out.println("上传图片json" + response.get());

            try {
                switch (what) {
                    case 0:
                        Wztpscinfo wztp = GsonUtils.GsonToBean(response.get(), Wztpscinfo.class);
                        if (wztp != null) {
                            if (!wztp.getTotal().equals("0")) {
                                wztps = wztp.getRows();
                                tvMs.setText("描述：" + wztps.get(0).getDescription());
                                resetData();
                                ll.setVisibility(View.VISIBLE);
                            } else {
                                showToast("暂无数据");
                                tvMs.setText("");
                                resetData();
                                ll.setVisibility(View.GONE);
                            }
                        } else {
                            showToast("暂无数据");
                            tvMs.setText("");
                            resetData();
                            ll.setVisibility(View.GONE);
                        }
                        break;
                    case 1:
                        System.out.println("图片大小：" + response.get());
                        StatusInfo info = GsonUtils.GsonToBean(response.get(), StatusInfo.class);
                        if (info != null) {
                            if (info.getRows().get(0).getStatus().equals("1")) {

                                File file = new File(path + stEndName);
                                if (file.isFile()) {
                                    file.delete();
                                }

                                stEndName = "";
                                ivSt.setImageBitmap(null);

                                showToast("上传缩图成功");

                                if (!TextUtils.isEmpty(fjtEndName)) {
                                    scData("2", 2, fjtEndName);
                                } else {
                                    dialog.dismiss();
                                    tvMs.setText("");
                                    etHgtm.setText("");
                                    fileName = "";
                                    ll.setVisibility(View.GONE);
                                }

                            } else {
                                showToast("上传缩图失败");
                                if (!TextUtils.isEmpty(fjtEndName)) {
                                    scData("2", 2, fjtEndName);
                                }
                            }
                        }
                        break;
                    case 2:
                        StatusInfo info1 = GsonUtils.GsonToBean(response.get(), StatusInfo.class);
                        if (info1 != null) {
                            if (info1.getRows().get(0).getStatus().equals("1")) {

                                File file = new File(path + fjtEndName);
                                if (file.isFile()) {
                                    file.delete();
                                }

                                showToast("上传附件图成功");
                                tvMs.setText("");
                                etHgtm.setText("");
                                fjtEndName = "";
                                ivFjt.setImageBitmap(null);
                                fileName = "";
                                dialog.dismiss();

                                ll.setVisibility(View.GONE);

                            } else {
                                showToast("上传附件图失败");
                                dialog.dismiss();
                            }
                        }
                        break;
                }

            } catch (Exception e) {
                showToast("暂无数据");
                tvMs.setText("");
                e.printStackTrace();
                dialog.dismiss();
            }

        }

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

        }
    };

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

        if (resultCode == Activity.RESULT_OK) {

            switch (requestCode) {
                case 1:
                    if (resultCode == RESULT_OK) {
                        Bundle bundle = data.getExtras();
                        String resultText = bundle.getString("result");
                        etHgtm.setText(resultText);
                    }
                    break;
                case 9:

                    File file = new File(path + fileName);
                    System.out.println("图片大小：" + file.length());
                    break;
                case 8:
                    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                    ivSt.setImageBitmap(bitmap);
                    break;

                case STPZ:
                    carpImageUri(stFileName, STEND);
                    break;

                case FJTPZ:
                    carpImageUri(fjtFileName, FJTEND);
                    break;

                case FJTXC:
                    if (data != null) {
                        carpImageUri(data.getData(), UiUtlis.getText(etHgtm) + "FJT", FJTEND);
                    }
                    break;

                case STXC:
                    if (data != null) {
                        carpImageUri(data.getData(), UiUtlis.getText(etHgtm), STEND);
                    }
                    break;

                case STEND:
                    Bitmap st = BitmapFactory.decodeFile(path + stFileName);
                    stEndName = stFileName;
                    ivSt.setImageBitmap(st);
                    break;
                case FJTEND:
                    Bitmap fjt = BitmapFactory.decodeFile(path + fjtFileName);
                    fjtEndName = fjtFileName;
                    ivFjt.setImageBitmap(fjt);
                    break;

            }
        }
    }


    //拍照
    private void cropFromTake(String name, int flag) {

        if (flag == STPZ) {
            stFileName = name + ".jpg";
        } else {
            fjtFileName = name + ".jpg";
        }

        fileName = UiUtlis.getText(etHgtm) + ".jpg";
        // 跳转至拍照界面
        File fos = new File(path + name + ".jpg");
//        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, flag);
    }



    private void carpImageUri(Uri uri, String name, int flag) {

        if (flag == STEND) {
            stFileName = name + ".jpg";
        } else {
            fjtFileName = name + ".jpg";
        }

        fileName = UiUtlis.getText(etHgtm) + ".jpg";
        imagePath = path + name + ".jpg";
        Uri outPutUri = Uri.fromFile(new File(imagePath));
        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("outputX", 450);
//        intent.putExtra("outputY", 300);
//        intent.putExtra("aspectX", 450);
//        intent.putExtra("aspectY", 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, flag);
    }

    private void carpImageUri(String name, int flag) {

        fileName = UiUtlis.getText(etHgtm) + ".jpg";

//        Uri uri = Uri.fromFile(new File(path + fileName));
        Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", new File(path + name));
        Uri outPutUri = Uri.fromFile(new File(path + name));
        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("outputX", 450);
//        intent.putExtra("outputY", 300);
//        intent.putExtra("aspectX", 450);
//        intent.putExtra("aspectY", 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, flag);
    }

    private void resetData() {


        File fjt = new File(path + fjtEndName);
        if (fjt.isFile()) {
            fjt.delete();
        }

        File st = new File(path + stEndName);
        if (st.isFile()) {
            st.delete();
        }

        fileName = "";
        fjtEndName = "";
        stEndName = "";
        ivFjt.setImageBitmap(null);
        ivSt.setImageBitmap(null);
    }
}
