package com.yutou.jianr_mg.views;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.text.InputType;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.leon.lfilepickerlibrary.LFilePicker;
import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Network.HttpApi;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.Tools.ActivitysManager;
import com.yutou.jianr_mg.Tools.CDNTools;
import com.yutou.jianr_mg.Tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;

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

import me.drakeet.materialdialog.MaterialDialog;

public class UserDataActivity extends AppCompatActivity {
    private ListView listView;
    private ArrayAdapter adapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userdata);
        adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,getData());
        listView=findViewById(R.id.list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            switch (position){
                case 1:
                    upUname();
                    break;
                case 2:
                    upEmail();
                    break;
                case 3:
                    upImg();
                    break;
                case 4:
                    logout();
                    break;
            }
        });
    }
    private List<String> getData(){
        List<String> list=new ArrayList<>();
        list.add("UID:"+ AppData.userdata.getUid());
        list.add("昵称:"+AppData.user.getUname());
        list.add("绑定邮箱:"+AppData.userdata.getEmail());
        list.add("更换头像");
        list.add("注销登录");
        return list;
    }
    private void upUname(){
         MaterialDialog dialog=new MaterialDialog(this);
         dialog.setTitle("更换昵称");
         EditText editText=new EditText(this);
         editText.setHint("请输入昵称");
         dialog.setContentView(editText);
         dialog.setPositiveButton("提交",v -> {
             String uname=editText.getText().toString();
             if(!Utils.testStringIsNull(uname)){
                 try {
                     JSONObject json=new JSONObject();
                     json.put("uname",uname);
                     HttpUtils.post(HttpApi.HOME_URL+HttpApi.USER_UPDATE,json,null);
                     AppData.user.setUname(uname);
                     Utils.toast(UserDataActivity.this,"更新成功");
                     adapter.clear();
                     adapter.addAll(getData());
                     adapter.notifyDataSetChanged();
                 }catch (Exception e){
                     e.printStackTrace();
                 }
             }
             dialog.dismiss();
         });
         dialog.setNegativeButton("取消",v -> dialog.dismiss());
         dialog.show();
    }
    private void upEmail(){
        MaterialDialog dialog=new MaterialDialog(this);
        dialog.setTitle("更换Email");
        EditText editText=new EditText(this);
        editText.setHint("请输入Email");
        editText.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        dialog.setContentView(editText);
        dialog.setPositiveButton("提交",v -> {
            String email=editText.getText().toString();
            if(!Utils.testStringIsNull(email)){
                try {
                    JSONObject json=new JSONObject();
                    json.put("email",email);
                    HttpUtils.post(HttpApi.HOME_URL+HttpApi.USER_UPDATE,json,null);
                    AppData.userdata.setEmail(email);
                    Utils.toast(UserDataActivity.this,"更新成功");
                    adapter.clear();
                    adapter.addAll(getData());
                    adapter.notifyDataSetChanged();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            dialog.dismiss();
        });
        dialog.setNegativeButton("取消",v -> dialog.dismiss());
        dialog.show();
    }
    private String token;
    private void upImg(){
        try{
            JSONObject json=new JSONObject();
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.USER_UPIMG, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        JSONObject json=new JSONObject(string);
                        token=json.optString("token");
                        AppData.handler.post(()->{
                            new LFilePicker()
                                    .withActivity(UserDataActivity.this)
                                    .withRequestCode(100)
                                    .withStartPath(Application.application.getFilesDir()+"/jianRMG")//指定初始显示路径
                                    .withIsGreater(false)//过滤文件大小 小于指定大小的文件
                                    .withMutilyMode(false)
                                    .withFileSize(5*1024*1024)//指定文件大小为500K
                                    .start();
                            Utils.toast(UserDataActivity.this,"请选择头像");
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void httpError(Exception e) {

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

    }
    private void logout(){
        MaterialDialog dialog=new MaterialDialog(this);
        dialog.setTitle("退出？");
        dialog.setMessage("注销账号并退出登录");
        dialog.setPositiveButton("提交",v -> {
            try {
                JSONObject json=new JSONObject();
                HttpUtils.post(HttpApi.HOME_URL + HttpApi.USER_LOGOUT, json, new HttpInterface() {
                    @Override
                    public void httpGetData(String string, int code) {
                        AppData.handler.post(()->{
                            ActivitysManager.finishAllActivity();
                            System.exit(0);
                        });

                    }

                    @Override
                    public void httpError(Exception e) {

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

        });
        dialog.setNegativeButton("取消",v -> dialog.dismiss());
        dialog.show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                //如果是文件选择模式，需要获取选择的所有文件的路径集合
                List<String> list = data.getStringArrayListExtra("paths");
                File file=new File(list.get(0));
                if(file.exists()){
                    showImgDialog(file);
                }
            }
        }
    }
    private void showImgDialog(File file){
        MaterialDialog dialog=new MaterialDialog(this);
        dialog.setTitle("更换头像");
        ImageView imageView=new ImageView(this);
        imageView.setImageURI(Uri.fromFile(file));
        dialog.setContentView(imageView);
        imageView.setOnClickListener(v -> {
            dialog.dismiss();
            upImg();
        });
        dialog.setPositiveButton("提交",v -> {
            try {
                CDNTools.getInstance(UserDataActivity.this)
                        .upload(file,AppData.user.getId()+"/img/"+file.getName(),token);
            }catch (Exception e){
                e.printStackTrace();
            }
            dialog.dismiss();

        });
        dialog.setNegativeButton("取消",v -> dialog.dismiss());
        dialog.show();
    }
}
