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.core.content.FileProvider;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.administrator.zhapp.BuildConfig;
import com.example.administrator.zhapp.DBModel.Qy;
import com.example.administrator.zhapp.DBModel.XwaqgcJh;
import com.example.administrator.zhapp.DBModel.XwaqgcJs;
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.JsInfo;
import com.example.administrator.zhapp.fragment.BaseFragment;
import com.example.administrator.zhapp.utils.SPUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import org.litepal.crud.DataSupport;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class XwaqgcxgJsFragment extends BaseFragment {

    EditText etBaq;
    CheckBox cbQszs;
    CheckBox cbSw;
    CheckBox cbZyb;
    CheckBox cbOther;
    EditText etCs;
    ImageView iv;
    TextView tvItem;
    Button btnLast;
    Button btnSave;
    Button btnPz;
    Button btnNext;



    private int item = 1;
    private int itemFlag = 0;//用来记录当前是哪一条集合信息
    private List<JsInfo> lists;

    private List<Qy> qys;

    private String areaname;

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

    public static XwaqgcxgJsFragment newInstance(String param1) {
        XwaqgcxgJsFragment fragment = new XwaqgcxgJsFragment();
        Bundle args = new Bundle();
        args.putString("areaname", param1);
        fragment.setArguments(args);
        return fragment;
    }

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

            areaname = getArguments().getString("areaname");
    }

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

    @Override
    protected void initView() {
        etBaq = view.findViewById(R.id.et_baq);
        cbQszs = view.findViewById(R.id.cb_qszs);
        cbSw = view.findViewById(R.id.cb_sw);
        cbZyb = view.findViewById(R.id.cb_zyb);
        cbOther = view.findViewById(R.id.cb_other);
        etCs = view.findViewById(R.id.et_cs);
        iv = view.findViewById(R.id.iv);
        tvItem = view.findViewById(R.id.tv_item);

        btnSave = view.findViewById(R.id.btn_save);
        btnPz = view.findViewById(R.id.btn_pz);
        btnLast = view.findViewById(R.id.btn_last);
        btnNext = view.findViewById(R.id.btn_next);

        btnLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnNext.setText(UiUtlis.getString(context, R.string.next));
                //如果item==icon1，就没有上一条了
                if (item == 1) {
                } else {
                    item--;
                    updataView(lists.get(item - 1));
                }
                tvItem.setText(item + "/" + lists.size());
                if (item < lists.size()) {
                    btnNext.setVisibility(View.VISIBLE);
                } else {
                    btnNext.setVisibility(View.INVISIBLE);
                }
            }
        });

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item == lists.size() - 1) {
                    btnNext.setText("完成");
                }
                //如果item==集合大小，就没有下一条了
                if (item == lists.size()) {
                    showToast("完成");
                } else {
                    updataView(lists.get(item));
                    item++;
                }
                tvItem.setText(item + "/" + lists.size());
            }
        });
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存第一条的数据
                if (isSave()) {
                    //如果相等，就添加一个info，不相等,就行修改info
                    if (item == lists.size()) {
                        setJsInfo(lists.get(item - 1), item, false);
                        JsInfo sj = new JsInfo();
                        sj.setJzcs("");
                        sj.setBaqxw("");
                        sj.setPath("");
                        lists.add(sj);
                        updataView(lists.get(item));
                        item++;
                        btnNext.setText("完成");
                    } else {
                        //修改
                        setJsInfo(lists.get(item - 1), item, true);
                    }
                    tvItem.setText(item + "/" + lists.size());
                    if (lists.size() > 1 || item > 1) {
                        btnLast.setVisibility(View.VISIBLE);
                    } else {
                        btnLast.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });

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

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), PhotoActivity.class);
                intent.putExtra("fileName", lastFileName);
                intent.putExtra("path", imagePath);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {

        qys = DataSupport.where("areaname= ?", areaname).find(Qy.class);

        //初始化，添加一条空的数据
        lists = new ArrayList<>();

        List<XwaqgcJs> jss = new ArrayList<>();
        jss.addAll(DataSupport.where("areacode = ?", qys.size() == 0 ? "" : qys.get(0).getAREACODE()).find(XwaqgcJs.class));
        for (XwaqgcJs js : jss) {
            JsInfo jsInfo = new JsInfo();
            String[] kndz = js.getKndz().split(" ");

            jsInfo.setQt(false);
            jsInfo.setZyb(false);
            jsInfo.setQszs(false);
            jsInfo.setSw(false);

            for (String str : kndz) {
                if (str.equals("轻伤、重伤")) {
                    jsInfo.setQszs(true);
                }
                if (str.equals("死亡")) {
                    jsInfo.setSw(true);
                }

                if (str.equals("职业病")) {
                    jsInfo.setZyb(true);
                }

                if (str.equals("其他")) {
                    jsInfo.setQt(true);
                }
            }
            jsInfo.setBaqxw(js.getXwzt());
            jsInfo.setJzcs(js.getJzcs());
            jsInfo.setPath(js.getPath());
            lists.add(jsInfo);
        }

        if (lists.size() != 0) {
            updataView(lists.get(0));
            JsInfo info = new JsInfo();
            info.setJzcs("");
            info.setBaqxw("");
            lists.add(info);
        } else {
            lists.add(new JsInfo());
        }
        tvItem.setText(item + "/" + lists.size());
        btnNext.setText("下一条");
    }

    /**
     * 更新View
     *
     * @param info
     */
    private void updataView(JsInfo info) {
        etBaq.setText(info.getBaqxw() + "");
        etCs.setText(info.getJzcs() + "");
        cbOther.setChecked(info.isQt());
        cbQszs.setChecked(info.isQszs());
        cbSw.setChecked(info.isSw());
        cbZyb.setChecked(info.isZyb());
        iv.setImageBitmap(BitmapFactory.decodeFile(info.getPath()));
        imagePath = info.getPath();

    }

//    private void initJsInfo(JsInfo info) {
//        et_baq.setText(info.getBaqxw() + "");
//        et_cs.setText(info.getJzcs() + "");
//        cb_other.setChecked(info.isQt());
//        cb_qszs.setChecked(info.isQszs());
//        cb_sw.setChecked(info.isSw());
//        cb_zyb.setChecked(info.isZyb());
//    }

    /**
     * 设置集合的信息
     *
     * @param info
     */
    private void setJsInfo(JsInfo info, int item, boolean isupload) {
        info.setQt(cbOther.isChecked());
        info.setQszs(cbQszs.isChecked());
        info.setSw(cbSw.isChecked());
        info.setZyb(cbZyb.isChecked());
        info.setBaqxw(etBaq.getText().toString() + "");
        info.setJzcs(etCs.getText().toString() + "");
        info.setPath(path + lastFileName);
        saveData(item, isupload);
    }

    /**
     * @param item     保存的item
     * @param isupload 是否更新数据
     */
    private void saveData(int item, boolean isupload) {

        //查询计划，如果有多个计划，就保存多个计划的记事
        if (!isupload) {
            List<XwaqgcJh> jhs = DataSupport.findAll(XwaqgcJh.class);
            for (XwaqgcJh jh : jhs) {
                StringBuilder sb = new StringBuilder();
                sb.append(cbOther.isChecked() ? cbOther.getText() + " " : "");
                sb.append(cbQszs.isChecked() ? cbQszs.getText() + " " : "");
                sb.append(cbSw.isChecked() ? cbSw.getText() + " " : "");
                sb.append(cbZyb.isChecked() ? cbZyb.getText() : "");
                XwaqgcJs js = new XwaqgcJs();
                js.setJhid(jh.getJHID());
                js.setAreacode(qys.size() != 0 ? qys.get(0).getAREACODE() : "");
                js.setJsr((String) SPUtils.get(context, Contans.USERNAME, ""));
                js.setJzcs(etCs.getText().toString());
                js.setKndz(sb.toString());
                js.setXwzt(etBaq.getText().toString());
                js.setItemid(item + "");
                js.setPath(path + lastFileName);
                boolean b = js.save();
                if (b) {
                    showToast("保存成功");
                }
            }
        } else //更新数据
        {
            List<XwaqgcJh> jhs = DataSupport.findAll(XwaqgcJh.class);
            for (XwaqgcJh jh : jhs) {
                StringBuilder sb = new StringBuilder();
                sb.append(cbOther.isChecked() ? cbOther.getText() + " " : "");
                sb.append(cbQszs.isChecked() ? cbQszs.getText() + " " : "");
                sb.append(cbSw.isChecked() ? cbSw.getText() + " " : "");
                sb.append(cbZyb.isChecked() ? cbZyb.getText() : "");

                ContentValues values = new ContentValues();
                values.put("jzcs", UiUtlis.getText(etCs));
                values.put("kndz", sb.toString());
                values.put("xwzt", UiUtlis.getText(etBaq));
                values.put("path", path + lastFileName);
                int updateCount = DataSupport.updateAll(XwaqgcJs.class, values, "jhid = ? and itemid = ? and areacode = ?", jh.getJHID(), item + "", qys.size() != 0 ? qys.get(0).getAREACODE() : "");

                if (updateCount == 1) {
                    showToast("保存成功");
                }
//                XwaqgcJs js = new XwaqgcJs();
//                js.setJhid(jh.getJHID());
//                js.setKndz(sb.toString());
//                js.setXwzt(et_baq.getText().toString());
//                boolean b = js.save();
//                if (b) {
//                    showToast("保存成功");
//                }
            }
        }
    }

    private boolean isSave() {
        if (UiUtlis.getText(etBaq).isEmpty()) {
            showToast("你还没有输入观察到的不安全行为和状态");
            return false;
        }
        return true;
    }

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

    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);
                    iv.setImageBitmap(bitmap);
                    lastFileName = fileName;
                    imagePath = path + lastFileName;
                    break;
            }
        }
    }
}
