package com.danding.yang800;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.danding.yang800.General.Yang800App;
import com.danding.yang800.Presenter.ShopDesignActivityPresenter;
import com.danding.yang800.Util.GeneralUtil;
import com.danding.yang800.Util.StatusColorUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.View.NetworkProgressDialog;
import com.yanzhenjie.sofia.Sofia;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopDesignActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.shopDesign_backTv)
    TextView shopDesign_backTv;
    @BindView(R.id.shopdesign_liebiao)
    LinearLayout shopdesign_liebiao;
    @BindView(R.id.shopdesign_liebiao1Iv)
    ImageView shopdesign_liebiao1Iv;
    @BindView(R.id.shopdesign_liebiao2Iv)
    ImageView shopdesign_liebiao2Iv;
    @BindView(R.id.shopdesign_shopNameLayout)
    RelativeLayout shopdesign_shopNameLayout;
    @BindView(R.id.shopDesign_describeLayout)
    RelativeLayout shopDesign_describeLayout;
    @BindView(R.id.shopdesign_headLayout)
    RelativeLayout shopdesign_headLayout;
    @BindView(R.id.shopdesign_shopIv)
    ImageView shopdesign_shopIv;
    @BindView(R.id.shopdesign_backIVlayout)
    RelativeLayout shopdesign_backIVlayout;
    @BindView(R.id.shopdesign_backIV)
    ImageView shopdesign_backIV;
    @BindView(R.id.shopdesign_showIv)
    ImageView shopdesign_showIv;
    @BindView(R.id.shopdesign_nameTv)
    TextView shopdesign_nameTv;
    SharedPreferences sp;
    private PopupWindow popupWindow;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private static final int MY_PERMISSIONS_CAMERA = 0;
    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int MY_PERMISSIONS_WRITE_CONTACTS = 2;
    private static final int PHOTO_REQUEST_GALLERY = 3;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 4;// 结果
    private static final int ACTIVITY_RESULT = 5;
    private File tempFile;
    private Bitmap bitmap;
    boolean head = false;
    private NetworkProgressDialog pd = null;
    ShopDesignActivityPresenter presenter;
    boolean show = false;
    String type;
    String shopName = "";
    String describe = "";
    String storeId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        int type = StatusColorUtil.StatusBarLightMode(this);
//        if (type > 0) {
//            StatusColorUtil.setStatusBarColor(this, R.color.white);
//            StatusColorUtil.StatusBarLightMode(this, type);
//        }
        setContentView(R.layout.activity_shop_design);
        Sofia.with(this).statusBarDarkFont().statusBarBackground(ContextCompat.getColor(this, R.color.white));
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
        storeId = sp.getString("storeId", "");
        ButterKnife.bind(this);
        presenter = new ShopDesignActivityPresenter(this);
        presenter.getShopInfo(storeId);
        presenter.getUploadImgUrl();
        initDialog();
    }

    public void initData(String name, String headImg, String backImg, boolean authentication, String style, String des) {
        shopdesign_nameTv.setText(name);
        describe = des;
        shopName = name;
        if (headImg.equals("")) {
            shopdesign_shopIv.setImageResource(R.drawable.main_myhead);
        } else {
            Glide.with(this).load(headImg).error(R.drawable.huisebeijing).
                    diskCacheStrategy(DiskCacheStrategy.SOURCE).into(shopdesign_shopIv);

        }
        if (backImg.equals("")) {
            shopdesign_backIV.setImageResource(R.drawable.shop_design_back);
        } else {
            Glide.with(this).load(backImg).error(R.drawable.huisebeijing).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(shopdesign_backIV);

        }

//        Glide.with(this).load(headImg).error(R.drawable.main_myhead).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(shopdesign_shopIv);
//        Glide.with(this).load(backImg).error(R.drawable.shop_design_back).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(shopdesign_backIV);
        show = authentication;
        if (show) {
            shopdesign_showIv.setImageDrawable(getResources().getDrawable(R.drawable.switch_button));
        } else {
            shopdesign_showIv.setImageDrawable(getResources().getDrawable(R.drawable.switch_off));
        }
        type = style;
        if (type.equals("1")) {
            shopdesign_liebiao1Iv.setImageDrawable(getResources().getDrawable(
                    R.drawable.liebiao_1));
            shopdesign_liebiao2Iv.setImageDrawable(getResources().getDrawable(
                    R.drawable.liebiao_2));
        } else {
        shopdesign_liebiao1Iv.setImageDrawable(getResources().getDrawable(
                R.drawable.liebiao_1_off));
        shopdesign_liebiao2Iv.setImageDrawable(getResources().getDrawable(
                R.drawable.liebiao_2_off));

    }

    }

    public void updateShow(boolean authentication) {
        show = authentication;
        if (show) {
            shopdesign_showIv.setImageDrawable(getResources().getDrawable(R.drawable.switch_button));
        } else {
            shopdesign_showIv.setImageDrawable(getResources().getDrawable(R.drawable.switch_off));
        }
    }

    public void updateType(String style) {
        type = style;
        if (type.equals("1")) {
            shopdesign_liebiao1Iv.setImageDrawable(getResources().getDrawable(
                    R.drawable.liebiao_1));
            shopdesign_liebiao2Iv.setImageDrawable(getResources().getDrawable(
                    R.drawable.liebiao_2));
        } else {
            shopdesign_liebiao1Iv.setImageDrawable(getResources().getDrawable(
                    R.drawable.liebiao_1_off));
            shopdesign_liebiao2Iv.setImageDrawable(getResources().getDrawable(
                    R.drawable.liebiao_2_off));
        }
    }

    @OnClick({R.id.shopDesign_backTv, R.id.shopdesign_liebiao, R.id.shopdesign_shopNameLayout, R.id.shopDesign_describeLayout
            , R.id.shopdesign_backIVlayout, R.id.shopdesign_headLayout, R.id.shopdesign_showIv
    })
    public void onViewClicked(View view) {
       /* if (!Yang800App.wifiConnect) {
            ToastUtil.show(this, "当前无网络");
            return;
        }*/
        switch (view.getId()) {
            case R.id.shopDesign_backTv:
                finish();
                break;
            case R.id.shopdesign_showIv:
                initDialog();
                presenter.updateInfo(storeId, !show, "");
                break;
            case R.id.shopdesign_liebiao:
                initDialog();
                if (type.equals("1")) {
                    presenter.updateInfo(storeId, show, "2");
                } else {
                    presenter.updateInfo(storeId, show, "1");
                }
                break;
            case R.id.shopdesign_shopNameLayout:
                Intent intent = new Intent(ShopDesignActivity.this, ChangeShopNameActivity.class);
                intent.putExtra("id", storeId);
                intent.putExtra("authentication", show);
                intent.putExtra("shopName", shopName);
                startActivityForResult(intent, ACTIVITY_RESULT);
                break;
            case R.id.shopDesign_describeLayout:
                Intent intentshop = new Intent(ShopDesignActivity.this, ShopDescribeActivity.class);
                intentshop.putExtra("id", storeId);
                intentshop.putExtra("authentication", show);
                intentshop.putExtra("des", describe);
                startActivityForResult(intentshop, ACTIVITY_RESULT);
                break;
            case R.id.shopdesign_headLayout:
                head = true;
                showWindow();
                break;
            case R.id.shopdesign_backIVlayout:
                head = false;
                showWindow();
                break;

        }
    }


    private void showWindow() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.layout_popupwindows_camera, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        TextView popupwindows_camera = (TextView) contentView
                .findViewById(R.id.popupwindows_camera);
        popupwindows_camera.setOnClickListener(this);
        TextView popupwindows_picture = (TextView) contentView
                .findViewById(R.id.popupwindows_picture);
        popupwindows_picture.setOnClickListener(this);
        TextView tv_popupwindows_off = (TextView) contentView
                .findViewById(R.id.tv_popupwindows_off);
        tv_popupwindows_off.setOnClickListener(this);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.popupwindows_camera:
                popupwindowscamera();
                popupWindow.dismiss();
                break;
            case R.id.popupwindows_picture:
                popupWindow.dismiss();
                getWritePermission();
                break;
            case R.id.tv_popupwindows_off:
                popupWindow.dismiss();
                break;
        }
    }

    private void getWritePermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_WRITE_CONTACTS);
            } else {
                picture();
            }
        } else {
            picture();
        }
    }

    private void picture() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }

    private void popupwindowscamera() {
        if (!GeneralUtil.isCameraCanUse()) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_CAMERA);
                }
            } else {
                ToastUtil.show(ShopDesignActivity.this, "无摄像头权限");
            }
        } else {
            takepicture();
        }
    }

    private void takepicture() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(Environment
                            .getExternalStorageDirectory(), PHOTO_FILE_NAME)));
        }
        startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takepicture();
            } else {
                ToastUtil.show(ShopDesignActivity.this, "无摄像头权限");
//                // Permission Denied
//                Toast.makeText(MainActivity.this, "拒绝", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        if (requestCode == MY_PERMISSIONS_WRITE_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                picture();
            } else {
                Toast.makeText(ShopDesignActivity.this, "没有读取存储权限", Toast.LENGTH_SHORT).show();
            }

            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    Uri uritempFile;

    private void crop(Uri uri, int x, int y) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", x);
        intent.putExtra("aspectY", y);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", x);
        intent.putExtra("outputY", y);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        //  intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                if (head) {
                    crop(uri, 100, 100);
                } else {
                    crop(uri, 226, 115);
                }
            }
        } else if (requestCode == 10) {
            if (GeneralUtil.isCameraCanUse()) {
                picture();
            }
        } else if (requestCode == 11) {
            if (GeneralUtil.isCameraCanUse()) {
                takepicture();
            }
        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            if (hasSdcard()) {
                tempFile = new File(Environment.getExternalStorageDirectory(),
                        PHOTO_FILE_NAME);
                if (resultCode != Activity.RESULT_CANCELED) {
                    if (head) {
                        crop(Uri.fromFile(tempFile), 100, 100);
                    } else {
                        crop(Uri.fromFile(tempFile), 226, 115);
                    }
                }
            } else {
                Toast.makeText(ShopDesignActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT)
                        .show();
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            try {
                // bitmap = data.getParcelableExtra("data");
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
                // UpdateImg();
//                startProgressDialog("");
                initDialog();
                if (head) {
                    presenter.updateImg(bitmap, sp.getString("uploadImgUrl", ""), storeId, head);
                } else {
                    presenter.updateImg(bitmap, sp.getString("uploadImgUrl", ""), storeId, head);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //accountset_head.setImageBitmap(bitmap2);
        } else if (requestCode == ACTIVITY_RESULT) {
            initDialog();
            presenter.getShopInfo(storeId);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void UpdateImg() {
        if (head)
            shopdesign_shopIv.setImageBitmap(bitmap);
        else
            shopdesign_backIV.setImageBitmap(bitmap);

    }


    public void initDialog() {
        if (pd == null) {
            pd = NetworkProgressDialog.createDialog(this);
            if (!pd.isShowing()) {
                pd.show();
            }
        }
    }

    public void dismissDialog() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
            NetworkProgressDialog.clear();
        }
    }
}