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

import android.app.Activity;
import android.content.ContentValues;
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.annotation.Nullable;
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 android.widget.RadioButton;
import android.widget.TextView;
import com.example.administrator.zhapp.BuildConfig;
import com.example.administrator.zhapp.DBModel.Ajhxcjs;
import com.example.administrator.zhapp.DBModel.Ajhxzrwqy;
import com.example.administrator.zhapp.R;
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.weight.AutoRadioGroup;
import org.litepal.crud.DataSupport;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 安健环巡查管理-安健环巡查-安健环巡查
 */
public class AjhxcDetaliFragment extends BaseFragment {

    TextView tv_qy;
    TextView textView;
    TextView tv_jcnr;
    TextView tv_zy;
    TextView tv_pl;
    RadioButton rb1;
    RadioButton rb2;
    AutoRadioGroup rg;
    EditText et_ms;
    ImageView ll_image;
    Button btn_last;
    Button btn_pz;
    Button btn_next;


    private ArrayList<Ajhxzrwqy> rwqys;
    private int item;

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

//    private List<String> files;

    public AjhxcDetaliFragment() {
    }

    public static AjhxcDetaliFragment newInstance(int itemid, ArrayList<Ajhxzrwqy> lists) {
        AjhxcDetaliFragment fragment = new AjhxcDetaliFragment();
        Bundle args = new Bundle();
        args.putInt(Contans.KEY_ITEMID, itemid);
        args.putParcelableArrayList(Contans.KEY_SBDJLIST, lists);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            item = getArguments().getInt(Contans.KEY_ITEMID);
            rwqys = getArguments().getParcelableArrayList(Contans.KEY_SBDJLIST);
        }
    }



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

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    protected void initView() {
        tv_qy = view.findViewById(R.id.tv_qy);
        textView = view.findViewById(R.id.textView);
        tv_jcnr = view.findViewById(R.id.tv_jcnr);
        tv_zy = view.findViewById(R.id.tv_zy);
        tv_pl = view.findViewById(R.id.tv_pl);
        rb1 = view.findViewById(R.id.rb1);
        rb2 = view.findViewById(R.id.rb2);
        rg = view.findViewById(R.id.rg);
        et_ms = view.findViewById(R.id.et_ms);
        ll_image = view.findViewById(R.id.ll_image);
        btn_last = view.findViewById(R.id.btn_last);
        btn_pz = view.findViewById(R.id.btn_pz);
        btn_next = view.findViewById(R.id.btn_next);

        btn_last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_next.setEnabled(true);
                item--;
                if (item == -1) {
                    item++;
                    btn_last.setEnabled(false);
                } else {
                    setTextInfo(rwqys.get(item));
                }
            }
        });

        btn_pz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cropFromTake();
            }
        });

        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
                rwqys.get(item).setMS(et_ms.getText().toString());
                rwqys.get(item).setSFHG(rb1.isChecked());
                btn_last.setEnabled(true);
                if (item == rwqys.size()) {
                    btn_next.setEnabled(false);
                }
                item++;
                if (item == rwqys.size()) {
                    item--;
                } else {
                    setTextInfo(rwqys.get(item));
                }
            }
        });
    }

    @Override
    public void initData() {
        setTextInfo(rwqys.get(item));
    }

    //保存数据
    private void saveData() {

        //保存现场记事
//        for (int i = 0; i < files.size(); i++) {
        //判断是否为空，如果为空，表示没有图片，就不保存
        if (!lastFileName.isEmpty()) {
            Ajhxcjs xcjs = new Ajhxcjs();
            xcjs.setAreacode(rwqys.get(item).getAREACODE());
            xcjs.setFile(path + lastFileName);
            xcjs.setJhid(rwqys.get(item).getJHID());
            xcjs.setJsr((String) SPUtils.get(context, Contans.USERNAME, ""));
            xcjs.setBz(et_ms.getText().toString());
            boolean save = xcjs.save();
            if (save) {
                lastFileName = "";
            }
        }

//        }

        //保存安健环检查数据
        ContentValues values = new ContentValues();
        values.put("checked", 1);
        values.put("scrn", rb1.isChecked() ? "是" : "否");
        values.put("sfhg", rb1.isChecked() ? 1 : 0);
        values.put("ms", et_ms.getText().toString());
        values.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int i = DataSupport.updateAll(Ajhxzrwqy.class, values, "ysid = ?", rwqys.get(item).getYSID());

        if (i != 0) {
            showToast("保存成功");
        }
    }

    /**
     * 设置文本的信息
     *
     * @param info
     */
    private void setTextInfo(Ajhxzrwqy info) {
        tv_qy.setText(info.getAREANAME());
        tv_jcnr.setText(info.getJCNY());
        et_ms.setText(info.getMS());
        rb1.setChecked(info.isSFHG());
        rb2.setChecked(!info.isSFHG());
//        files.clear();
        ll_image.setImageBitmap(BitmapFactory.decodeFile(""));
    }

    @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);
                    ll_image.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", 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);
    }
}
