package com.qhclh.ytzh.me;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qhclh.ytzh.R;
import com.qhclh.ytzh.base.BaseActivity;
import com.qhclh.ytzh.utils.BitmapUtils;
import com.qhclh.ytzh.utils.DateUtils;
import com.qhclh.ytzh.utils.GlideLoader;
import com.qhclh.ytzh.utils.dialog.MixedDialog;
import com.qhclh.ytzh.utils.widget.DateTimePickDialog;
import com.qhclh.ytzh.utils.widget.XCRoundImageView;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import java.util.Date;
import java.util.List;

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

import static com.qhclh.ytzh.utils.DateUtils.PATTERN_TRANSVERSE;

public class MineInfoActivity extends BaseActivity {
    /**
     * 监听获取数据信息
     */
    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
        }

        @Override
        public void onSuccess(List<String> photoList) {
            for (String path : photoList) {
                imageView.setImageBitmap(BitmapUtils.getSmallBitmap(path, 100, 100));
            }
        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onFinish() {
        }

        @Override
        public void onError() {
        }
    };
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.imageView)
    XCRoundImageView imageView;
    @BindView(R.id.ly_personPicture)
    LinearLayout lyPersonPicture;
    @BindView(R.id.ly_phoneNumber)
    LinearLayout lyPhoneNumber;
    @BindView(R.id.ly_sex)
    LinearLayout lySex;
    @BindView(R.id.ly_birthday)
    LinearLayout lyBirthday;
    public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 0x01;
    @BindView(R.id.tv_phoneNumber)
    TextView tvPhoneNumber;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_toolbar_title)
    TextView tvToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private MixedDialog mixedDialog;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_mine_info;
    }

    @Override
    protected void initView() {
        initToolbar(toolbar, "个人资料", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initOper() {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ly_personPicture, R.id.ly_phoneNumber, R.id.ly_sex, R.id.ly_birthday})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ly_personPicture:
                openSelectImage();
                break;
            case R.id.ly_phoneNumber:
                ClickBtn1();
                break;
            case R.id.ly_sex:
                setSexInfo();
                break;
            case R.id.ly_birthday:
                setTimeDialog();
                break;
        }
    }

    /**
     * 打开图片选择器前进行授权
     */
    private void openSelectImage() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // 提示用户如果想要正常使用，要手动去设置中授权。
                Toast.makeText(this, "请在 设置-应用管理 中开启此应用的储存授权。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            // 进行正常操作
            openGallery();
        }
    }

    /**
     * 性别选择
     */
    private void setSexInfo() {
        final String[] items = new String[2];
        items[0] = "男";
        items[1] = "女";
        MixedDialog.showDialog(this, items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvSex.setText(items[which]);
            }
        });
    }

    /**
     * 日期选择器
     */
    private void setTimeDialog() {
        DateTimePickDialog mDateTimePickDialog = new DateTimePickDialog(this, new DateTimePickDialog.DateChangedCallBack() {
            @Override
            public void onDateChanged(Date date) {
                String birthday_time = DateUtils.format(date, PATTERN_TRANSVERSE);
                tvBirthday.setText(birthday_time);
            }
        });
        mDateTimePickDialog.show();
    }

    /**
     * 授权
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openGallery();
            }
        }
    }

    /**
     * 打开图片选择器
     */
    private void openGallery() {
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.yancy.gallerypickdemo.fileprovider")   // provider (必填)
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .isShowCamera(true)                      // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();
        //打开图片选择器
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
    }

    /**
     * 手机号编辑
     */
    public void ClickBtn1() {
        mixedDialog = new MixedDialog(this, MixedDialog.SINGLE, R.style.MyDialog);
        //标题
        mixedDialog.setTitleText("手机号");
        mixedDialog.show();
        //触摸对话框外围区域是否消失对话框
        mixedDialog.setCanceledOnTouchOutside(true);
        mixedDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mixedDialog.dismiss();

            }
        });
        /**
         * 确定按钮点击事件
         * 显示输入的电话号码
         * 关闭对话框
         */
        mixedDialog.buttonOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone_str = mixedDialog.importEditText.getText().toString();
                tvPhoneNumber.setText(phone_str);
                mixedDialog.dismiss();
            }
        });
    }


}
