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


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
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.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
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 android.widget.TextView;
import com.example.administrator.zhapp.BuildConfig;

import com.example.administrator.zhapp.DBModel.Qy;
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.BaseActivity;
import com.example.administrator.zhapp.activity.MipcaActivityCapture;
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.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.example.administrator.zhapp.weight.WaitDialog;
import com.orhanobut.logger.Logger;
import com.yolanda.nohttp.FileBinary;
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.nio.charset.StandardCharsets;
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 YhpclrActivity extends BaseActivity {

    private static final int STPZ = 101;

    TextView tvQy;
    EditText etPcnr;
    EditText etFxwt;
    Button btnSave;
    Button btnCancel;
    ImageView ivResult;
    Button btnSm;
    Button btnPz;
    Button btnSc;
    Button btnDel;

    private String qycode = "";

    private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "/com.rehome.ydapp/images/";

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

    private int requestCount;
    private int successCount;

    private WaitDialog dialog;

    private boolean isUpdate;

    private String id;

    private YhpcInfo info;
    private Yhpctp tp = null;

    private void findView() {
        tvQy = findViewById(R.id.tv_qy);
        etPcnr = findViewById(R.id.et_pcnr);
        etFxwt = findViewById(R.id.et_fxwt);
        btnSave = findViewById(R.id.btn_save);
        btnCancel = findViewById(R.id.btn_cancel);
        ivResult = findViewById(R.id.iv_result);
        btnSm = findViewById(R.id.btn_sm);
        btnPz = findViewById(R.id.btn_pz);
        btnSc = findViewById(R.id.btn_sc);
        btnDel = findViewById(R.id.btn_del);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpdate) {
                    updateData(false);
                } else {
                    saveData();
                }
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPcnr.setText("");
                etFxwt.setText("");
                tvQy.setText("");
            }
        });
        btnSc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateData(true);
            }
        });
        btnSm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MipcaActivityCapture.class);
                startActivityForResult(intent, 1);
            }
        });
        btnPz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //"点击了照相";
                //  6.0之后动态申请权限 摄像头调取权限,SD卡写入权限
                if (ContextCompat.checkSelfPermission(YhpclrActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(YhpclrActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(YhpclrActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, STPZ);
                } else {
                    //有权限,去打开摄像头
                    cropFromTake();
                }
            }
        });
        ivResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(context, PhotoActivity.class);
                intent1.putExtra("fileName", lastFileName);
                if (tp != null) {
                    intent1.putExtra("path", tp.getPath());
                } else {
                    intent1.putExtra("path", path + lastFileName);
                }
                startActivity(intent1);
            }
        });
        btnDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("提示");
                builder.setMessage("删除后不可以恢复，你确定要删除吗？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        removeData();
                        showToast("删除成功");
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
    }

    @Override
    public int getContentViewID() {
        return R.layout.activity_yhpclr;
    }

    @Override
    protected void initView() {
        findView();
        setBack();
        setTitle("隐患排查录入");
        initNFC();

        isUpdate = getIntent().getExtras().getBoolean("isUpdate");
        id = getIntent().getStringExtra("guid");

        if (isUpdate) {

            List<YhpcInfo> yhpcs = DataSupport.where("guid=?", id).find(YhpcInfo.class);
            if (yhpcs.size() != 0) {
                info = yhpcs.get(0);
            }

            List<Qy> qys = DataSupport.where("areacode = ?", info.getAREACODE()).find(Qy.class);
//                    List<Qy> qys = DataSupport.where("txm = ?", "HX0001").find(Qy.class);
            if (qys.size() != 0) {
                tvQy.setText(qys.get(0).getAREANAME());
            }

            List<Yhpctp> tps = DataSupport.where("guid = ?", id).find(Yhpctp.class);
            if (tps.size() != 0) {
                tp = tps.get(0);
                Bitmap bitmap = BitmapFactory.decodeFile(tp.getPath());
                ivResult.setImageBitmap(bitmap);
            }

            etFxwt.setText(info.getWT());
            etPcnr.setText(info.getNR());
            btnSm.setVisibility(View.GONE);
            btnDel.setVisibility(View.VISIBLE);
        } else {
            btnSc.setVisibility(View.GONE);
        }

        dialog = new WaitDialog(context, "上传中...");
    }

    @Override
    protected void initData() {

    }

    /**
     * 申请权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == STPZ) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                cropFromTake();
            } else {
                //"权限拒绝");
                // TODO: 2018/12/4 这里可以给用户一个提示,请求权限被拒绝了
                showToast("拍照请求权限被拒绝，请手动打开后重试");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //修改数据
    private void updateData(boolean isSc) {

        int flag = 0;

        ContentValues values = new ContentValues();
        values.put("wt", etFxwt.getText().toString());
        values.put("nr", etPcnr.getText().toString());
        int count = DataSupport.updateAll(YhpcInfo.class, values, "guid = ?", id);
        if (count == 1) {
            flag++;
        }

        if (tp != null) {

            if (!TextUtils.isEmpty(lastFileName)) {

                File file = new File(tp.getPath());
                if (file.isFile()) {
                    file.delete();
                }

                ContentValues values1 = new ContentValues();
                values1.put("path", path + lastFileName);
                int count1 = DataSupport.updateAll(Yhpctp.class, values1, "guid = ?", id);
                if (count1 == 1) {
                    flag++;
                }
            }

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

        if (flag >= 1) {
            if (isSc) {
                scData();
            } else {
                showToast("保存成功");
//                setResult(200);
//                finish();
            }
        }
    }

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

        int flag = 0;

        UUID uuid = UUID.randomUUID();
        guid = uuid.toString().replace("-", "").toUpperCase();
        //保存数据
        if (!qycode.isEmpty()) {
            if (isSave()) {
                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(etFxwt));
                info.setNR(UiUtlis.getText(etPcnr));
                info.setAREACODE(qycode);
                info.setGUID(guid);
                boolean save = info.save();
                if (save) {
                    flag++;
                }

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

                if (flag >= 1) {
                    showToast("保存成功");
                    etFxwt.setText("");
                    etPcnr.setText("");
                    setResult(100);
                    finish();
                }

            } else {
                showToast("你还没有输入内容");
            }
        } else {
            showToast("你还没有扫描区域");
        }
    }

    private void cropFromTake() {

        fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CANADA)) + ".jpg";
        // 跳转至拍照界面
        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 1:
                    Bundle bundle = data.getExtras();
                    List<Qy> qys = DataSupport.where("txm = ?", (String) bundle.get("result")).find(Qy.class);
//                    List<Qy> qys = DataSupport.where("txm = ?", "HX0001").find(Qy.class);
                    if (qys.size() != 0) {
                        qycode = qys.get(0).getAREACODE();
                        tvQy.setText(qys.get(0).getAREANAME());
                    } else {
                        qycode = "";
                        tvQy.setText("");
                    }
                    break;
                case 9:
                    carpImageUri();
                    break;
                case 8:
                    Bitmap bitmap = BitmapFactory.decodeFile(path + fileName);
                    ivResult.setImageBitmap(bitmap);
                    lastFileName = fileName;
                    break;
            }
        }
    }

    private void scData() {

        requestCount = 0;
        successCount = 0;

        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.YHPC, RequestMethod.POST);
        List<YhpcInfo> infos = DataSupport.where("guid = ?", id).find(YhpcInfo.class);
        if (infos.size() != 0) {
            dialog.show();
            requestCount++;
            String json = "{\"Rows\":" + GsonUtils.GsonString(infos) + ",\"Total\": " + infos.size() + "}";
            System.out.println("json" + json);
            json = new String(json.getBytes(), StandardCharsets.UTF_8);
            request.setDefineRequestBodyForJson(UiUtlis.encoder(json));
            NohttpUtils.getInstance().add(this, 0, request, callback, false, false, "上传中...");


            List<Yhpctp> tps = DataSupport.where("guid = ?", id).find(Yhpctp.class);

            if (tps.size() != 0) {
                for (Yhpctp tp : tps) {
                    requestCount++;
                    Request<String> request1 = NoHttp.createStringRequest(Contans.IP + Contans.YHPCTP + "?guid=" + tp.getGuid(), RequestMethod.POST);
                    request1.add(Contans.FILEPS, new FileBinary(new File(tp.getPath())));
                    NohttpUtils.getInstance().add(this, 1, request1, callback, false, false, "上传中...");
                }
            }
        } 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("上传成功");
                        successCount++;
                    } else {
                        showToast("上传失败");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                showToast("数据异常");
                dialog.dismiss();
            }

            if (requestCount == successCount) {
                removeData();
                dialog.dismiss();
            }

        }

        @Override
        public void onFailed(int what, Response<String> response) {
            dialog.dismiss();
        }
    };

    private void removeData() {

        DataSupport.deleteAll(YhpcInfo.class, "guid = ?", id);

        List<Yhpctp> tps = DataSupport.where("guid = ?", id).find(Yhpctp.class);
        for (Yhpctp tp : tps) {
            File file = new File(tp.getPath());
            if (file.isFile()) {
                file.delete();
            }
        }
        DataSupport.deleteAll(Yhpctp.class, "guid = ?", id);

        setResult(200);
        finish();

    }

    @Override
    public void handleNfc(String result) {
        super.handleNfc(result);
        if (isUpdate) {
        } else {
            List<Qy> qys = DataSupport.where("bqbm = ?", result).find(Qy.class);
            if (qys.size() != 0) {
                qycode = qys.get(0).getAREACODE();
                tvQy.setText(qys.get(0).getAREANAME());
            } else {
                qycode = "";
                tvQy.setText("");
            }
        }
    }

    private boolean isSave() {
        boolean issave = true;
        if (etPcnr.getText().toString().isEmpty()) {
            issave = false;
        }
        if (etFxwt.getText().toString().isEmpty()) {
            issave = false;
        }
        return issave;
    }

    @Override
    public void setBack() {
        mToolbar.setNavigationIcon(R.mipmap.back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isUpdate) {
                    setResult(200);
                } else {
                    setResult(100);
                }
                finish();
            }
        });
    }
}