package com.itant.shiwushu.ui.menu.me.info;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.itant.shiwushu.R;
import com.itant.shiwushu.base.BaseSkinActivity;
import com.itant.shiwushu.base.IPermission;
import com.itant.shiwushu.bean.User;
import com.itant.shiwushu.manager.ToastManager;
import com.itant.shiwushu.manager.UserManager;
import com.itant.shiwushu.tool.PermissionTool;
import com.itant.shiwushu.tool.file.FileTool;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import me.iwf.photopicker.PhotoPicker;

/**
 * 用户资料
 * Created by Jason on 2018/10/2.
 */

public class UserInfoActivity extends BaseSkinActivity implements View.OnClickListener, IPermission,
        TextWatcher, UserInfoContract.View {
    private static final int REQUEST_PHOTO = 1;
    private static final String[] PERMISSIONS_NECESSARY = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private EditText et_nickname;
    private EditText et_saying;
    private ImageView iv_head;
    private File outFile;
    private String suffix;

    private User user = UserManager.getInstance().getUser();
    private boolean isEdited;

    private UserInfoPresenter presenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        findViewById(R.id.aciv_back).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);
        findViewById(R.id.ll_head).setOnClickListener(this);

        et_nickname = findViewById(R.id.et_nickname);
        et_saying = findViewById(R.id.et_saying);
        iv_head = findViewById(R.id.iv_head);

        if (user != null) {
            et_nickname.setText(user.getNickName());
            et_saying.setText(user.getSaying());
            if (!TextUtils.isEmpty(user.getHeadIcon())) {
                Glide.with(this).load(user.getHeadIcon())
                        .apply(new RequestOptions()
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                //.skipMemoryCache(true)
                                //.signature(new ObjectKey(System.currentTimeMillis()))
                                )
                        .into(iv_head);
            }
        }

        presenter = new UserInfoPresenter(this);
        et_nickname.addTextChangedListener(this);
        et_saying.addTextChangedListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.aciv_back:
                // 返回
                onBackPressed();
                break;

            case R.id.ll_head:
                // 更换头像
                PermissionTool.initPermission(this,this, PERMISSIONS_NECESSARY, REQUEST_PHOTO);
                break;

            case R.id.tv_save:
                updateUserData();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (isEdited) {
            showSaveDataDialog();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onPermissionSuccess(int requestCode) {
        pickPhoto();
    }

    @Override
    public void onPermissionFail(int requestCode) {
        ToastManager.getInstance().toastShort("权限被拒绝");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionTool.onActivityPermissionResult(this, requestCode, grantResults);
    }

    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(false)
                .setShowGif(false)
                .setPreviewEnabled(false)
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data == null) {
                return;
            }
            ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            if (photos.size() == 1) {
                String sourceFilePath = photos.get(0);
                RequestOptions options = new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .skipMemoryCache(true)
                        .signature(new ObjectKey(System.currentTimeMillis()));
                File srcFile = new File(sourceFilePath);
                suffix = sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
                File outFileDir = new File(getFilesDir(), "img");
                outFile = new File(outFileDir, "head" + suffix);
                try {
                    FileTool.copyFile(srcFile, outFile);
                    Glide.with(this).load(outFile.getAbsolutePath())
                            .apply(options)
                            .into(iv_head);
                    isEdited = true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 询问是否保存更改
     */
    private void showSaveDataDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                //.setIcon(R.mipmap.icon)//设置标题的图片
                //.setTitle("开通会员")//设置对话框的标题
                .setMessage("用户资料已更改，是否保存？")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("丢弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        updateUserData();
                    }
                }).create();
        dialog.show();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        isEdited = true;
    }

    /**
     * 更新用户数据
     */
    private void updateUserData() {
        String nickname = et_nickname.getText().toString();
        if (TextUtils.isEmpty(nickname)) {
            ToastManager.getInstance().toastShort("昵称不能为空");
            return;
        }
        String saying = et_saying.getText().toString();
        if (TextUtils.isEmpty(saying)) {
            ToastManager.getInstance().toastShort("签名不能为空");
            return;
        }

        setLoading(true);
        presenter.updateUserData(nickname, saying, outFile, suffix);
    }

    @Override
    public void onRequestComplete() {
        setLoading(false);
    }

    @Override
    public void onUpdateSuccess(User user) {
        UserManager.getInstance().notifyUserDataUpdate(user);
        // 提示更新成功，然后关闭本页面
        ToastManager.getInstance().toastShort("更新成功");
        finish();
    }

    @Override
    public void onUpdateFailed(String message) {
        ToastManager.getInstance().toastShort(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.setView(null);
    }
}
