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

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
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.ItemIDInfo;
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;
import java.util.UUID;

/**
 * 安健环巡查管理-记事列表
 */
public class JsFragment extends BaseFragment {

    EditText et_baq;
    CheckBox cb_qszs;
    CheckBox cb_sw;
    CheckBox cb_zyb;
    CheckBox cb_other;
    EditText et_cs;
    TextView tv_item;
    Button btn_last;
    Button btn_save;
    Button btn_next;
    Button btn_pz;
    ImageView iv;


    private int item = 1;
    private List<JsInfo> lists;

    private List<Qy> qys;
    private List<ItemIDInfo> itemids;

    private String code;
    private boolean nfcorewm;

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

    private boolean history;
    private String areaname;
    private String xwjljsid;

    public JsFragment() {
    }

    public static JsFragment newInstance(String code, boolean nfcorewm, boolean history, String areaname, String xwjljsid) {
        JsFragment fragment = new JsFragment();
        Bundle args = new Bundle();
        args.putString("code", code);
        args.putBoolean("nfcorewm", nfcorewm);
        args.putBoolean("history", history);
        args.putString("areaname", areaname);
        args.putString("xwjljsid", xwjljsid);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            code = bundle.getString("code");
            nfcorewm = bundle.getBoolean("nfcorewm");
            history = bundle.getBoolean("history");
            areaname = bundle.getString("areaname");
            xwjljsid = bundle.getString("xwjljsid");
        }
    }

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

    @Override
    protected void initView() {
        et_baq = view.findViewById(R.id.et_baq);
        cb_qszs = view.findViewById(R.id.cb_qszs);
        cb_sw = view.findViewById(R.id.cb_sw);
        cb_zyb = view.findViewById(R.id.cb_zyb);
        cb_other = view.findViewById(R.id.cb_other);
        et_cs = view.findViewById(R.id.et_cs);
        tv_item = view.findViewById(R.id.tv_item);
        btn_last = view.findViewById(R.id.btn_last);
        btn_save = view.findViewById(R.id.btn_save);
        btn_next = view.findViewById(R.id.btn_next);
        btn_pz = view.findViewById(R.id.btn_pz);
        iv = view.findViewById(R.id.iv);

        btn_last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_next.setText(UiUtlis.getString(context, R.string.next));
                //如果item==icon1，就没有上一条了
                if (item == 1) {
                } else {
                    item--;
                    updataView(lists.get(item - 1));
                }
                tv_item.setText(item + "/" + lists.size());
                if (item < lists.size()) {
                    btn_next.setVisibility(View.VISIBLE);
                } else {
                    btn_next.setVisibility(View.INVISIBLE);
                }
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存第一条的数据
                if (isSave()) {
                    UUID uuid = UUID.randomUUID();
                    String itemid = uuid.toString().replaceAll("-", "").toLowerCase();
                    //如果相等，就添加一个info，不相等,就行修改info
                    if (item == lists.size()) {
                        setJsInfo(lists.get(item - 1), item - 1, itemid, false);
                        JsInfo sj = new JsInfo();
                        sj.setJzcs("");
                        sj.setBaqxw("");
                        sj.setPath("");
                        lists.add(sj);
                        lastFileName = "";
                        updataView(lists.get(item));
                        item++;
                        btn_next.setText("完成");
                    } else {
                        String id = itemids.get(item - 1).getItemid();
                        //修改
                        setJsInfo(lists.get(item - 1), item - 1, id, true);
                    }
                    tv_item.setText(item + "/" + lists.size());
                    if (lists.size() > 1 || item > 1) {
                        btn_last.setVisibility(View.VISIBLE);
                    } else {
                        btn_last.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });
        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item == lists.size() - 1) {
                    btn_next.setText("完成");
                }
                //如果item==集合大小，就没有下一条了
                if (item == lists.size()) {
                    showToast("完成");
                } else {
                    updataView(lists.get(item));
                    item++;
                }
                tv_item.setText(item + "/" + lists.size());
            }
        });
        btn_pz.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);
            }
        });
    }


    public void initData() {

        qys = new ArrayList<>();
        itemids = new ArrayList<>();


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

        if (history) {
            qys = DataSupport.where("areaname= ?", areaname).find(Qy.class);
            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);

                ItemIDInfo info = new ItemIDInfo();
                info.setItemid(js.getItemid());
                itemids.add(info);
            }

            if (lists.size() != 0) {
                updataView(lists.get(0));
                JsInfo info = new JsInfo();
                info.setJzcs("");
                info.setBaqxw("");
                lists.add(info);
            } else {
                lists.add(new JsInfo());
            }

        } else {

            if (nfcorewm) {
                qys = DataSupport.where("txm = ?", code).find(Qy.class);
            } else {
                qys = DataSupport.where("bqbm = ?", code).find(Qy.class);
            }
//            btn_next.setVisibility(View.INVISIBLE);
            lists.add(new JsInfo());
        }

        tv_item.setText(item + "/" + lists.size());
        btn_next.setText("下一条");

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * 更新View
     *
     * @param info
     */
    private void updataView(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());
        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, String itemid, boolean isupload) {
        info.setQt(cb_other.isChecked());
        info.setQszs(cb_qszs.isChecked());
        info.setSw(cb_sw.isChecked());
        info.setZyb(cb_zyb.isChecked());
        info.setBaqxw(et_baq.getText().toString() + "");
        info.setJzcs(et_cs.getText().toString() + "");
        if (!lastFileName.isEmpty()) {
            info.setPath(path + lastFileName);
        }
        saveData(item, itemid, isupload);
    }

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

        //查询计划，如果有多个计划，就保存多个计划的记事
        if (!isupload) {
            List<XwaqgcJh> jhs = DataSupport.findAll(XwaqgcJh.class);
            for (XwaqgcJh jh : jhs) {
                StringBuilder sb = new StringBuilder();
                sb.append(cb_other.isChecked() ? cb_other.getText() + " " : "");
                sb.append(cb_qszs.isChecked() ? cb_qszs.getText() + " " : "");
                sb.append(cb_sw.isChecked() ? cb_sw.getText() + " " : "");
                sb.append(cb_zyb.isChecked() ? cb_zyb.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(et_cs.getText().toString());
                js.setKndz(sb.toString());
                js.setXwzt(et_baq.getText().toString());
                js.setItemid(itemid);
                js.setPath(path + lastFileName);
                js.setXwjljsid(xwjljsid);

                boolean b = js.save();
                if (b) {
                    showToast("保存成功");
                    ItemIDInfo idinfo = new ItemIDInfo();
                    idinfo.setItem(item);
                    idinfo.setItemid(itemid);
                    itemids.add(idinfo);
                }
            }
        } else //更新数据
        {
            List<XwaqgcJh> jhs = DataSupport.findAll(XwaqgcJh.class);
            for (XwaqgcJh jh : jhs) {
                StringBuilder sb = new StringBuilder();
                sb.append(cb_other.isChecked() ? cb_other.getText() + " " : "");
                sb.append(cb_qszs.isChecked() ? cb_qszs.getText() + " " : "");
                sb.append(cb_sw.isChecked() ? cb_sw.getText() + " " : "");
                sb.append(cb_zyb.isChecked() ? cb_zyb.getText() : "");


                ContentValues values = new ContentValues();
                values.put("jzcs", UiUtlis.getText(et_cs));
                values.put("kndz", sb.toString());
                values.put("xwzt", UiUtlis.getText(et_baq));

                //如果图片不为空，就更新图片路径
                if (!lastFileName.isEmpty()) {
                    values.put("path", path + lastFileName);
                }

                int updateCount = DataSupport.updateAll(XwaqgcJs.class, values, "jhid = ? and itemid = ? and areacode = ?", jh.getJHID(), itemid, qys.size() != 0 ? qys.get(0).getAREACODE() : "");

                if (updateCount == 1) {
                    showToast("保存成功");
                    lastFileName = "";
                }
//                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(et_baq).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;
            }
        }
    }
}