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.TextUtils;
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.XcjsInfo;
import com.example.administrator.zhapp.DBModel.XfDjjhRwqy;
import com.example.administrator.zhapp.DBModel.XfXcjsInfo;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.ajhxcgl.AjhAndSbjdActivity;
import com.example.administrator.zhapp.activity.sbxdjgl.ScjsjActivity;
import com.example.administrator.zhapp.activity.xfbwxcgl.XXfsDetaliActivity;
import com.example.administrator.zhapp.activity.xfbwxcgl.XfhmAqckdDetaliActivity;
import com.example.administrator.zhapp.activity.xfbwxcgl.XmhqcDetaliActivity;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.fragment.BaseFragment;
import com.example.administrator.zhapp.utils.SPUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import java.io.File;
import java.util.Calendar;
import java.util.Locale;

/**
 * 安健环巡查管理-现场记事
 */
public class XcjsFragment extends BaseFragment {

    ImageView iv;
    EditText et;
    Button btn_pz;
    Button btn_save;



    private XfDjjhRwqy xfDjjhRwqy;


    private boolean isEdit = true;
    private int ACT_FRG_FLAG = -1;

    private String path;
    private String fileName;
    private String lastFileName;

    private String jhid;
    private String pointnum;

    private String xfjhid;
    private String xfid;

    private boolean flag;


    public XcjsFragment() {
    }

    public static XcjsFragment newInstance(boolean b, int flag) {
        Bundle bundle = new Bundle();
        bundle.putBoolean("edit", b);
        bundle.putInt(Contans.ACT_FRG_FLAG, flag);
        XcjsFragment fragment = new XcjsFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            isEdit = bundle.getBoolean("edit");
            ACT_FRG_FLAG = bundle.getInt(Contans.ACT_FRG_FLAG);
        }
    }

    @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);
                    iv.setImageBitmap(bitmap);
                    lastFileName = fileName;
                    flag = true;
                    break;
            }
        }
    }

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

    @Override
    protected void initView() {
        iv = view.findViewById(R.id.iv);
        et = view.findViewById(R.id.et);
        btn_save = view.findViewById(R.id.btn_save);
        btn_pz = view.findViewById(R.id.btn_pz);

        et.setEnabled(isEdit);
        btn_pz.setEnabled(isEdit);
        btn_save.setEnabled(isEdit);

        btn_pz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cropFromTake();
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (ACT_FRG_FLAG) {
                    //消防栓，处理消防栓的数据
                    case Contans.XFSFRG:
                        XXfsDetaliActivity xfsAct = (XXfsDetaliActivity) getActivity();
                        xfsAct.setXcjs();
                        if (!TextUtils.isEmpty(et.getText().toString().trim())) {
                            saveXfData();
                            //UploadFile();
                        } else {
                            showToast("你还没有输入描述");
                        }
                        break;
                    //灭火器材
                    case Contans.MHQCFRG:
                        XmhqcDetaliActivity mhqcAct = (XmhqcDetaliActivity) getActivity();
                        mhqcAct.setXcjs();
                        if (!TextUtils.isEmpty(et.getText().toString().trim())) {
                            saveXfData();
                            //UploadFile();
                        } else {
                            showToast("你还没有输入描述");
                        }
                        break;
                    //防火门及安全出口灯
                    case Contans.FHMFRG:
                        XfhmAqckdDetaliActivity fhmAct = (XfhmAqckdDetaliActivity) getActivity();
                        fhmAct.setXcjs();
                        if (!TextUtils.isEmpty(et.getText().toString().trim())) {
                            saveXfData();
                            //UploadFile();
                        } else {
                            showToast("你还没有输入描述");
                        }
                        break;
                    //点列表
                    case Contans.SDLBACT:
                        ScjsjActivity activity = (ScjsjActivity) getActivity();
                        activity.getJhPoint();
                        if (!TextUtils.isEmpty(et.getText().toString().trim())) {
                            saveData();
                            //UploadFile();
                        } else {
                            showToast("你还没有输入描述");
                        }
                        break;
                    //安建环设备点检
                    case Contans.AjhACT:
                        AjhAndSbjdActivity ajh = (AjhAndSbjdActivity) getActivity();
                        ajh.getJhPoint();
                        if (!TextUtils.isEmpty(et.getText().toString().trim())) {
                            saveData();
                            //UploadFile();
                        } else {
                            showToast("你还没有输入描述");
                        }
                        break;
                }
            }
        });

    }

    public void initData() {

        switch (ACT_FRG_FLAG) {
            //消防栓，处理消防栓的数据
            case Contans.XFSFRG:
                break;
            //灭火器材
            case Contans.MHQCFRG:
                break;
            //防火门及安全出口灯
            case Contans.FHMFRG:
                break;
            //点列表
            case Contans.SDLBACT:
                break;
            //安建环设备点检
            case Contans.AjhACT:
                break;
        }
    }

    //保存数据到本地
    private void saveData() {
        if (!flag) {
            fileName = "";
            path = "";
        }
        XcjsInfo info = new XcjsInfo();
        info.setJhid(jhid);
        info.setMs(UiUtlis.getText(et));
        info.setFilename(path + lastFileName);
        info.setPointnum(pointnum);
        info.setDjr((String) SPUtils.get(getContext(), Contans.USERNAME, ""));
        if (info.save()) {
            showToast("保存成功");
            iv.setImageResource(R.mipmap.nopic);
            et.setText("");
            flag = false;
        }
    }

    private void saveXfData() {

        if (!flag) {
            fileName = "";
            path = "";
        }
        XfXcjsInfo info = new XfXcjsInfo();
        info.setJhid(xfjhid);
        info.setMs(UiUtlis.getText(et));
        info.setFilename(lastFileName);
        info.setPath(path + lastFileName);
        info.setXfid(xfid);
        info.setDjr((String) SPUtils.get(getContext(), Contans.NAME, "测试"));
        if (info.save()) {
            showToast("保存成功");
            iv.setImageResource(R.mipmap.nopic);
            et.setText("");
            flag = false;
        }
    }

//    //上传文件
//    public void UploadFile() {
//        Request<String> request = NoHttp.createStringRequest(Contans.DJJHXCJSSC + "ms=" + et.getText().toString().trim() +
//                "&jhid=" + jhid + "&pointnum=" + pointnum +
//                "&djr=" + SPUtils.get(getContext(), Contans.USERNAME, ""), RequestMethod.POST);
//        request.add(Contans.FILEPS, new FileBinary(new File(path + fileName)));
//        NohttpUtils.getInstance().add(getActivity(), 0, request, mListener, true, true, "上传中..");
//    }
//
//    private HttpListener<String> mListener = new HttpListener<String>() {
//        @Override
//        public void onSucceed(int what, Response<String> response) {
//
//            StatusInfo info = GsonUtils.GsonToBean(response.get(), StatusInfo.class);
//            if (info != null) {
//                if (info.getRows().get(0).getStatus().equals(1)) {
//                    showToast("上传成功");
//                } else {
//                    showToast("上传失败");
//                }
//            } else {
//                showToast("解析数据出错");
//            }
//        }
//
//        @Override
//        public void onFailed(int what, Response<String> response) {
//
//        }
//    };

    /**
     * 剪切图片
     */

    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);
    }

    /**
     * 打开拍照界面
     */
    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 = 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);
    }

    public void setJhPoin(String jhid, String pointnum) {
        this.pointnum = pointnum;
        this.jhid = jhid;
    }

    public void setXfjhdXfid(String xfjhid, String xfid) {
        this.xfjhid = xfjhid;
        this.xfid = xfid;
    }

    public void setRwqy(XfDjjhRwqy rwqy) {
        xfDjjhRwqy = rwqy;
    }
}
