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

import android.app.Activity;
import android.content.Intent;
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 androidx.core.content.FileProvider;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.administrator.zhapp.BuildConfig;
import com.example.administrator.zhapp.DBModel.Ajhxzrwqy;
import com.example.administrator.zhapp.DBModel.YhpcInfo;
import com.example.administrator.zhapp.DBModel.Yhpctp;
import com.example.administrator.zhapp.R;
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.fragment.BaseFragment;
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.SPUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.orhanobut.logger.Logger;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 * 安健环隐患排查录入
 */
public class YhpcFragment extends BaseFragment {

    EditText et_pcnr;
    EditText et_fxwt;
    Button btn_save;
    Button btn_cancel;
    Button sc;
    Button pz;
    ImageView ivResult;


    private String ewm = "";
    private boolean nfcorewm;

    private List<Ajhxzrwqy> qys;

    private String qycode = "";

    private String path = "";
    private String fileName = "";
    private String lastFileName = "";
    private String guid = "";


    public YhpcFragment() {
    }

    /**
     * 初始化fragmeng传过来的参数
     *
     * @param param1
     * @param param2
     * @return
     */
    public static YhpcFragment newInstance(String param1, String param2) {
        YhpcFragment fragment = new YhpcFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }

        Bundle bundle = getActivity().getIntent().getExtras();
        if (bundle != null) {
            nfcorewm = bundle.getBoolean(Contans.NFCOREWM);
            ewm = bundle.getString(Contans.KEY_BQBM);
            ewm = ewm == null ? "" : ewm;
        }
    }

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

    @Override
    protected void initView() {
        et_pcnr = view.findViewById(R.id.et_pcnr);
        et_fxwt = view.findViewById(R.id.et_fxwt);
        btn_save = view.findViewById(R.id.btn_save);
        btn_cancel = view.findViewById(R.id.btn_cancel);
        sc = view.findViewById(R.id.sc);
        pz = view.findViewById(R.id.btn_pz);
        ivResult = view.findViewById(R.id.iv_result);

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UUID uuid = UUID.randomUUID();
                guid = uuid.toString().replace("-", "").toUpperCase();
                if (qys.size() != 0) {
                    //保存数据
                    YhpcInfo info = new YhpcInfo();
                    info.setFXR((String) SPUtils.get(context, Contans.USERNAME, ""));
                    info.setFXSJ(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    info.setWT(UiUtlis.getText(et_fxwt));
                    info.setNR(UiUtlis.getText(et_pcnr));
                    info.setAREACODE(qycode);
                    info.setGUID(guid);
                    boolean save = info.save();
                    if (save) {
                        showToast("保存成功");
                        et_fxwt.setText("");
                        et_pcnr.setText("");
                    }

                    if (!lastFileName.isEmpty()) {
                        Yhpctp tp = new Yhpctp();
                        tp.setGuid(guid);
                        tp.setPath(path + lastFileName);
                        boolean save1 = tp.save();
                        if (save1) {
                            lastFileName = "";
                            Bitmap bitmap = BitmapFactory.decodeFile(path + lastFileName);
                            ivResult.setImageBitmap(bitmap);
                        }
                    }

                } else {
                    showToast("没有该区域任务，不能保存");
                }
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_pcnr.setText("");
                et_fxwt.setText("");
            }
        });
        sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scData();
            }
        });
        pz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cropFromTake();
            }
        });
        ivResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(getActivity(), PhotoActivity.class);
                intent1.putExtra("fileName", lastFileName);
                intent1.putExtra("path", path + lastFileName);
                startActivity(intent1);
            }
        });
    }

    public void initData() {

        if (nfcorewm) {
            qys = DataSupport.where("bqbm = ?", ewm).find(Ajhxzrwqy.class);
        } else {
            qys = DataSupport.where("nfcbh = ?", ewm).find(Ajhxzrwqy.class);
        }

        if (qys.size() != 0) {
            qycode = qys.get(0).getAREACODE();
        }

    }

    private void cropFromTake() {

        fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CANADA)) + ".jpg";
        // 跳转至拍照界面
        path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "/com.rehome.ydapp/images/";
        File fos = new File(path + fileName);
        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);
    }

    /**
     * 剪切图片
     */
    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", 3);
        intent.putExtra("aspectY", 4);
        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 onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            switch (requestCode) {
                case 9:
                    carpImageUri();
                    break;
                case 8:
                    Bitmap bitmap = BitmapFactory.decodeFile(path + fileName);
                    ivResult.setImageBitmap(bitmap);
                    lastFileName = fileName;
                    break;
            }
        }
    }

    private void scData() {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.YHPC, RequestMethod.POST);
        List<YhpcInfo> infos = DataSupport.findAll(YhpcInfo.class);
        if (infos.size() != 0) {
            String json = "{\"Rows\":" + GsonUtils.GsonString(infos) + ",\"Total\": " + infos.size() + "}";
            System.out.println("json" + json);
            request.setDefineRequestBodyForJson(json);
            NohttpUtils.getInstance().add(getActivity(), 0, request, callback, true, true, "上传中...");
        } else {
            showToast("没有数据");
        }
    }

    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {
            System.out.println("json" + response.get());
            Logger.json(response.get());
            try {
                StatusInfo info = GsonUtils.GsonToBean(response.get(), StatusInfo.class);
                if (info != null) {
                    if (info.getRows().get(0).getStatus().equals("1")) {
                        showToast("上传成功");
                        DataSupport.deleteAll(YhpcInfo.class);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                showToast("数据异常");
            }
        }

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

        }
    };

    public void setQycode(String qycode) {
        this.qycode = qycode;
    }
}