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


import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
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.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.LyXcjsInfo;
import com.example.administrator.zhapp.DBModel.LyxcXm;
import com.example.administrator.zhapp.DBModel.LyxcXmJg;
import com.example.administrator.zhapp.DBModel.Lyxcrwqy;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.BaseActivity;
import com.example.administrator.zhapp.contans.Contans;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;


public class XlyxcDetaliActivity extends BaseActivity {

    EditText etPcnr;
    Button btnSave;
    Button btnCancel;
    ImageView iv;
    TextView tvContent;
    RadioButton rb1;
    RadioButton rb2;
    TextView qy;

    private static final int STPZ = 101;
    private String jcnr;
    private String xmid;
    private String qyid;
    private String jhid;

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

    private List<LyxcXm> xms;
    private List<Lyxcrwqy> rws;

    private boolean flag = false;

    private void findView() {
        etPcnr = findViewById(R.id.et_pcnr);
        btnSave = findViewById(R.id.btn_save);
        btnCancel = findViewById(R.id.btn_cancel);
        iv = findViewById(R.id.iv);
        tvContent = findViewById(R.id.tv_content);
        rb1 = findViewById(R.id.rb1);
        rb2 = findViewById(R.id.rb2);
        qy = findViewById(R.id.qy);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //"点击了照相";
                //  6.0之后动态申请权限 摄像头调取权限,SD卡写入权限
                if (ContextCompat.checkSelfPermission(XlyxcDetaliActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(XlyxcDetaliActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(XlyxcDetaliActivity.this,new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, STPZ);
                }  else {
                    //有权限,去打开摄像头
                    cropFromTake();
                }
            }
        });
    }

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

    @Override
    protected void initView() {
        findView();
        setBack();
        setTitle("楼宇巡查");

        rws = new ArrayList<>();
        xms = new ArrayList<>();

        jcnr = getIntent().getExtras().getString("jcnr");
        xmid = getIntent().getExtras().getString("xmid");
        qyid = getIntent().getExtras().getString("qyid");
        jhid = getIntent().getExtras().getString("jhid");

        xms.addAll(DataSupport.where("xmid = ?", xmid).find(LyxcXm.class));
        rws.addAll(DataSupport.where("xmid = ? and qyid = ?", xmid, qyid).find(Lyxcrwqy.class));

        //显示已经保存过的数据，如果没有，就使用默认的
        if (xms.size() != 0) {
            tvContent.setText(jcnr + xms.get(0).getTypename());
            rb1.setText(xms.get(0).getType1());
            rb2.setText(xms.get(0).getType2());
        }
        if (rws.size() != 0) {
            qy.setText(rws.get(0).getQYNAME());
            etPcnr.setText(rws.get(0).getCJJG());
            String iszc = rws.get(0).getISZC() == null ? "1" : rws.get(0).getISZC();
            rb1.setChecked(iszc.equals("1"));
            rb2.setChecked(iszc.equals("0"));
        }
    }

    @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 saveData() {

        List<LyxcXmJg> jgs = DataSupport.where("xmid = ? and jhid = ? and qyid = ?", xmid, jhid, qyid).find(LyxcXmJg.class);

        if (xms.size() != 0) {
            if (jgs.size() == 0) {
                LyxcXmJg jg = new LyxcXmJg();
                jg.setJg(rb1.isChecked());
                jg.setJhid(jhid);
                jg.setQyid(qyid);
                jg.setSsid(xms.get(0).getSsid());
                jg.setType1(xms.get(0).getType1());
                jg.setType2(xms.get(0).getType2());
                jg.setTypename(xms.get(0).getTypename());
                jg.setXmid(xmid);
                jg.save();
            } else {
                ContentValues values = new ContentValues();
                values.put("jg", rb1.isChecked());
                DataSupport.updateAll(LyxcXmJg.class, values, "xmid = ? and jhid = ? and qyid = ? and ssid = ?", xmid, jhid, qyid, xms.get(0).getSsid());
            }
        }


        //保存本条数据，如果数据库中有这条数据，就更新。
        ContentValues values = new ContentValues();
        values.put("iszc", rb1.isChecked() ? "1" : "0");
        values.put("cjjg", UiUtlis.getText(etPcnr));
        values.put("cjsj", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        values.put("checked", 1);
        values.put("cjr", (String) SPUtils.get(context, Contans.NAME, " "));
        int i = DataSupport.updateAll(Lyxcrwqy.class, values, "xmid = ? and qyid = ?", xmid, qyid);
        if (i != 0) {
            showToast("保存成功");
        }

        //说明有图片，就保存现场记事
        if (flag && xms.size() != 0) {

            List<LyXcjsInfo> lyXcjsInfos = DataSupport.where("filename = ?", lastFileName).find(LyXcjsInfo.class);
            if (lyXcjsInfos.size() == 0) {
                LyXcjsInfo info = new LyXcjsInfo();
                info.setDjr((String) SPUtils.get(context, Contans.NAME, "测试"));
                info.setFilename(lastFileName);
                info.setPath(path + lastFileName);
                info.setJhid(xms.get(0).getJhid());
                info.setXfid(xms.get(0).getXmid()+"_"+qyid);
                info.setMs(UiUtlis.getText(etPcnr));
                info.save();
            } else {
                showToast("你已经保存过该图片了");
            }
        }
    }

    @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:
                    flag = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(path + fileName);
                    iv.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("outputX", 400);
//        intent.putExtra("outputY", 400);
        //intent.putExtra("scale", true);
        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);
    }
}