package com.ahau.againstpest.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ahau.againstpest.MyView.SpinnerEditText;
import com.ahau.againstpest.R;
import com.ahau.againstpest.bean.PestBean;
import com.ahau.againstpest.presenter.PestPresenter;
import com.ahau.againstpest.utils.TakingPhotoUtils;
import com.ahau.againstpest.utils.TakingPhotoUtils.onGetTypeClckListener;
import com.ahau.againstpest.utils.URLUtils;
import com.ahau.againstpest.view.BaseActivity;
import com.ahau.againstpest.view.IPestView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.utils.UrlSafeBase64;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.TextUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import static com.ahau.againstpest.R.id.addpestpic;


public class AgainPestActivity extends BaseActivity<IPestView, PestPresenter<IPestView>> implements OnClickListener, IPestView {

    private static final int Adressrequest = 0;
    private static final int Pestrequest = 5;
    private static final int Genderrequest = 4;


    private TextView tv_date, jingduTV, weiduTV;
    private Button tijiaobtn;
    private String adddate, adressid, pestname, pestfirstgrade, pestsecondgrade, researchpeople, remark,gaodejingdu, gaodeweidu;;
    String AccessKey = "UeKrDBz5wknxCwwob0IffRIIQm43EYMbWtiGgIDn";
    String SecretKey = "KHtAQ8-HQYejTPjIRq5a9aH-wZcsJIcrDrfie0vI";
    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";
    private RelativeLayout addpicLO, addpicLO2;
    private Bitmap bitmap = null;
    private EditText remark_ET;
    private TextView researchpeople_TV;
    private ImageView addpicIV, addpicIV2;
    private TextView sptadressid;
    private File file;
    private Uri ImgUri;

    private Type type;

    private TakingPhotoUtils puWindow;
    private SpinnerEditText<PestBean.Pest> v_pestname;
    private SpinnerEditText<PestBean.Pest.PestGrade> v_firstgrade;
    private SpinnerEditText<PestBean.Pest.PestGrade.SecondGrade> v_secondgrade;


    public enum Type {
        PHONE, CAMERA
    }

    private String Httpnet;
    private Object Httpnet2;
    private int k;


    /**
     * 获取害虫的名字
     *
     * @param pest
     */
    @Override
    public void showPest(List<PestBean.Pest> pest) {

        v_pestname.setList(pest);
        v_pestname.setSelection(0);
        v_pestname.setOnItemClickListener(new SpinnerEditText.OnItemClickListener<PestBean.Pest>() {
            @Override
            public void onItemClick(PestBean.Pest pest, SpinnerEditText<PestBean.Pest> spinnerEditText, View view, int i, long l, String s) {

                Log.d("pestgrade", pest.grade + "");
                if (!((pest.grade + "").equals("null"))) {
                    v_firstgrade.setList(pest.grade);
                    v_firstgrade.setSelection(0);
                    v_firstgrade.setOnItemClickListener(new SpinnerEditText.OnItemClickListener<PestBean.Pest.PestGrade>() {
                        @Override
                        public void onItemClick(PestBean.Pest.PestGrade pestGrade, SpinnerEditText<PestBean.Pest.PestGrade> spinnerEditText, View view, int i, long l, String s) {
                            if (!((pestGrade.nextgrade + "").equals("null"))) {
                                v_secondgrade.setList(pestGrade.nextgrade);
                                v_secondgrade.setSelection(0);
                            } else {
                                v_secondgrade.dismissPop();
                            }
                        }
                    });
                } else {
                }
            }
        });
    }

    /**
     * 获取当前时间
     */
    @Override
    public void setDate(String date) {
        tv_date.setText(date);
    }

    /**
     * 获取当前经纬度
     */
    @Override
    public void setLatlng(String[] latlng) {
        jingduTV.setText(latlng[0]);
        weiduTV.setText(latlng[1]);
        gaodejingdu = latlng[2];
        gaodeweidu = latlng[3];
    }

    /**
     * 获取调查人姓名
     *
     * @param researName
     */
    @Override
    public void setResearName(String researName) {
        researchpeople_TV.setText(researName);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_again_pest);
        intiViews();

        pestPresenter.fetch();
    }

    @Override
    protected PestPresenter<IPestView> createPresenter() {
        return new PestPresenter<>();
    }


    /**
     * 初始化控件
     */
    private void intiViews() {

        tv_date = findViewById(R.id.tv_date);  //日期

        jingduTV = findViewById(R.id.jingdu);// 经纬度
        weiduTV = findViewById(R.id.weidu);

        sptadressid = findViewById(R.id.adressid);

        remark_ET = findViewById(R.id.remark);
        researchpeople_TV = findViewById(R.id.researchpeople);


        v_pestname = findViewById(R.id.pestname);
        v_firstgrade = findViewById(R.id.firstgrade);
        v_secondgrade = findViewById(R.id.secondgrade);


        addpicIV = findViewById(R.id.pestpic);
        addpicIV2 = findViewById(R.id.pestpic2);

        addpicLO = findViewById(addpestpic);
        addpicLO.setOnClickListener(this);

        addpicLO2 = findViewById(R.id.addpestpic2);
        addpicLO2.setOnClickListener(this);

        //提交数据按钮
        tijiaobtn = findViewById(R.id.tijiao);
        tijiaobtn.setOnClickListener(this);


    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tijiao:
                getinfo();
                if (tijiaoIssuccess()) {
                    new AlertDialog.Builder(this).setTitle("提示").setMessage("确定数据无误，确定提交吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    uploadpictoqiniu(1);

                                    finish();
                                }
                            }).show();
                }


                break;
            case addpestpic:
                k = 1;
                puWindow = new TakingPhotoUtils(AgainPestActivity.this, AgainPestActivity.this);
                puWindow.showPopupWindow(findViewById(R.id.set_act_parent));
                puWindow.setOnGetTypeClckListener(new onGetTypeClckListener() {

                    @Override
                    public void getType(Type type) {
                        AgainPestActivity.this.type = type;
                    }

                    @Override
                    public void getImgUri(Uri ImgUri, File file) {
                        AgainPestActivity.this.ImgUri = ImgUri;
                        AgainPestActivity.this.file = file;
                    }

                });

                break;

            case R.id.addpestpic2:

                k = 2;
                puWindow = new TakingPhotoUtils(AgainPestActivity.this, AgainPestActivity.this);
                puWindow.showPopupWindow(findViewById(R.id.set_act_parent));
                puWindow.setOnGetTypeClckListener(new onGetTypeClckListener() {

                    @Override
                    public void getType(Type type) {
                        AgainPestActivity.this.type = type;
                    }

                    @Override
                    public void getImgUri(Uri ImgUri, File file) {
                        AgainPestActivity.this.ImgUri = ImgUri;
                        AgainPestActivity.this.file = file;
                    }

                });


                break;

        }

    }


    public void getinfo() {
        adddate = tv_date.getText().toString();//时间
        adressid = sptadressid.getText().toString(); //地区id
        pestname = v_pestname.getText().toString();//害虫名字
        pestfirstgrade = v_firstgrade.getText().toString();
        pestsecondgrade = v_secondgrade.getText().toString();
        researchpeople = researchpeople_TV.getText().toString();//调查人
        remark = remark_ET.getText().toString(); // 备注


    }


    /**
     * 判断是否提交成功
     */
    private boolean tijiaoIssuccess() {

        if (TextUtils.isEmpty(adressid) && adressid.equals("0")) {

            Toast.makeText(AgainPestActivity.this, "区域编号不能为空，请选择！", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;

        /*if (TextUtils.isEmpty(pestname) && pestname.equals("0")) {

            Toast.makeText(AgainPestActivity.this, "虫种不能为空，请选择!", Toast.LENGTH_SHORT).show();
            return false;
        }else if (TextUtils.isEmpty(adressid) && adressid.equals("0")) {

            Toast.makeText(AgainPestActivity.this, "区域编号不能为空，请选择！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (addpicIV.getDrawable() == null) {

            Toast.makeText(AgainPestActivity.this, "图片1不能为空，请添加！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (addpicIV2.getDrawable() == null) {

            Toast.makeText(AgainPestActivity.this, "图片2不能为空，请添加！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;*/
    }


    /**
     * 上传图片至七牛云
     *
     * @param
     */
    public void uploadpictoqiniu(final int i) {
        try {
            // 构造上传策略
            JSONObject _json = new JSONObject();
            long _dataline = System.currentTimeMillis() / 1000 + 3600;
            _json.put("deadline", _dataline);// 有效时间为一个小时
            _json.put("scope", "oldtreetest"); // bucket name 空间名称
            String _encodedPutPolicy = UrlSafeBase64.encodeToString(_json.toString().getBytes());
            byte[] _sign = HmacSHA1Encrypt(_encodedPutPolicy, SecretKey);
            String _encodedSign = UrlSafeBase64.encodeToString(_sign);
            String _uploadToken = AccessKey + ':' + _encodedSign + ':' + _encodedPutPolicy;
            // String SAVE_FILE_DIRECTORY = uri.toString();

            String SAVE_FILE_DIRECTORY = Environment.getExternalStorageDirectory() + "/temp" + i + ".jpg";
            System.out.println("SAVE_FILE_DIRECTORY" + SAVE_FILE_DIRECTORY);
            UploadManager uploadManager = new UploadManager();

            uploadManager.put(SAVE_FILE_DIRECTORY, null, _uploadToken, new UpCompletionHandler() {

                @Override
                public void complete(String key, ResponseInfo info, JSONObject response) {

                    try {

                        String netname = response.getString("hash");

                        if (i == 1) {
                            Httpnet = "http://ojcst7op3.bkt.clouddn.com/" + netname;
                            uploadpictoqiniu(2);
                        } else if (i == 2) {
                            Httpnet2 = "http://ojcst7op3.bkt.clouddn.com/" + netname;
                            uploadinformation();
                        }
                        System.out.println("11" + Httpnet);
                        System.out.println("12" + Httpnet2);
                        //	uploadinformation();

                    } catch (JSONException e) {

                        e.printStackTrace();
                    }

                    // System.out.println("qiniu222" + response.toString());

                }
            }, null);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);
        byte[] text = encryptText.getBytes(ENCODING);
        // 完成 Mac 操作
        return mac.doFinal(text);
    }


    /**
     * 提交的信息
     */
    public void uploadinformation() {

        try {
            final JSONObject jsonObject = new JSONObject();
            try {

                jsonObject.put("date", adddate);
                jsonObject.put("areanumber", adressid);
                jsonObject.put("pestname", pestname);
                jsonObject.put("pestfirstgrade", pestfirstgrade);
                jsonObject.put("pestsecondgrade", pestsecondgrade);
                jsonObject.put("researchprople", researchpeople);
                jsonObject.put("remark", remark);

                jsonObject.put("longitude", gaodeweidu);
                jsonObject.put("latitude", gaodejingdu);

                jsonObject.put("pestpicurl1", Httpnet);
                jsonObject.put("pestpicurl2", Httpnet2);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            ByteArrayEntity entity = null;
            try {
                entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
                entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            /*final Map<String, Object> params = new HashMap<>();
            params.put("entity", entity);
            HttpHelper.obtain().post(URLUtils.PestCollectUrl, entity, new HttpCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    Toast.makeText(AgainPestActivity.this, "信息上传成功!" + s, Toast.LENGTH_SHORT).show();
                    Log.d("tag", "信息上传成功");
                }

                @Override
                public void onFailure(String e) {
                    Toast.makeText(AgainPestActivity.this, "信息上传失败!", Toast.LENGTH_SHORT).show();
                    Log.e("tag", "信息上传失败");
                }
            });*/

            String url = URLUtils.PestCollectUrl;
            //String url = "http://192.168.1.107:8080/Tree/FileUploadServlet";
            AsyncHttpClient client = new AsyncHttpClient();
            //client.post(url, params, new AsyncHttpResponseHandler() {
            client.post(this, url, (HttpEntity) entity, "application/json", new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

                    Toast.makeText(AgainPestActivity.this, "信息上传成功!", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                    Toast.makeText(AgainPestActivity.this, "信息上传失败!", Toast.LENGTH_SHORT).show();
                }

            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1) {
            if (ImgUri != null) {
                Log.d("ImgUri", ImgUri.toString());
                puWindow.onPhoto(k, ImgUri, 1000, 1000);
            }
        } else if (requestCode == 2) {
            if (data != null) {
                Uri uri = data.getData(); // 从相册选择的图片可以直接获得uri(uniform resource
                // bitmap = BitmapFactory.decodeFile(uri.toString());
                // addpicIV.setVisibility(View.VISIBLE);
                // addpicIV.setImageBitmap(bitmap); // identifier)资源标识
                puWindow.onPhoto(k, uri, 1000, 1000);
            }
        } else if (requestCode == 3) {
            if (type == Type.PHONE) {
                if (data != null) {
                    // Bundle extras = data.getExtras();
                    if (k == 1) {
                        bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/temp1.jpg");
                        addpicIV.setVisibility(View.VISIBLE);
                        addpicIV.setImageBitmap(bitmap);
                    } else if (k == 2) {
                        bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/temp2.jpg");
                        addpicIV2.setVisibility(View.VISIBLE);
                        addpicIV2.setImageBitmap(bitmap);
                    }

                }
            } else if (type == Type.CAMERA) {

                if (k == 1) {
                    bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/temp1.jpg");
                    addpicIV.setVisibility(View.VISIBLE);
                    addpicIV.setImageBitmap(bitmap);
                } else if (k == 2) {
                    bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/temp2.jpg");
                    addpicIV2.setVisibility(View.VISIBLE);
                    addpicIV2.setImageBitmap(bitmap);
                }

            }
        }
    }


}