package com.efounder.chat.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;

import org.json.JSONException;

import static com.efounder.chat.R.id.detail;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;


/**
 * 搜索应用号展示应用号详情的界面
 * Created by Tian Yu on 2016/9/10.
 */

public class AddPublicFriendInfoActivity extends BaseActivity implements View.OnClickListener {

    //private ImageLoader imageLoader;
//    private DisplayImageOptions options;
    ImageView icon;
    String PublicFriendId;
    TextView tv_name;
    TextView tv_function;
    TextView contactWay;
    User user;
    String userId;
    private MyHandler myHandler;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_officialaccounts);
        myHandler = new MyHandler();

        Intent intent = getIntent();
        if (intent.hasExtra("user")) {
            user = (User) intent.getSerializableExtra("user");
            User user1 = WeChatDBManager.getInstance().getOneOfficialNumber(Integer.valueOf(user.getId()));
            if (user1 != null) {
                Intent intent1 = new Intent(this, PublicNumerInfoActivity.class);
                intent1.putExtra("id", user.getId());
                startActivity(intent1);
                this.finish();
                return;
            }
            initViewAndData();
        } else if (intent.hasExtra("userID")) {
            userId = getIntent().getStringExtra("userID");
            showLoading(ResStringUtil.getString(R.string.common_text_please_wait));
            user = WeChatDBManager.getInstance().getOneOfficialNumber(Integer.valueOf(userId));
            if (user != null) {
                Intent intent1 = new Intent(this, PublicNumerInfoActivity.class);
                intent1.putExtra("id", user.getId());
                startActivity(intent1);
                // progressDialog.dismiss();
                dismissLoading();
                finish();
            } else {//不存在，从服务器拉取
                if (!isNetActive()) {
                    ToastUtil.showToast(this, R.string.common_text_network_error_please_again);
                    dismissLoading();
                    user = null;
                    initViewAndData();

                }

                GetHttpUtil.getUserInfo(Integer.valueOf(userId), AddPublicFriendInfoActivity.this,
                        new GetHttpUtil.GetUserListener() {
                            @Override
                            public void onGetUserSuccess(User user1) {
                                myHandler.sendEmptyMessage(1);
                                user = WeChatDBManager.getInstance().
                                        getOneUserById(Integer.valueOf(userId));
                                initViewAndData();
                            }

                            @Override
                            public void onGetUserFail() {

                            }
                        });
            }
        }
        ;


        // WeChatDBManager.getInstance() WeChatDBManager.getInstance() = WeChatDBManager.getInstance();
        // user = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(PublicFriendId));
        // String avatar=user.getAvatar();


    }

    private void initViewAndData() {

        ImageView back = (ImageView) findViewById(R.id.back);
        icon = (ImageView) findViewById(R.id.icon);
        RelativeLayout re_historymessage = (RelativeLayout) findViewById(R.id.re_historymessage);
        Button focus = (Button) findViewById(R.id.focus);
        tv_name = (TextView) findViewById(R.id.iconname);
        tv_function = (TextView) findViewById(R.id.function_introduction);
        contactWay = (TextView) findViewById(detail);


        back.setOnClickListener(this);
        icon.setOnClickListener(this);
        re_historymessage.setOnClickListener(this);
        focus.setOnClickListener(this);
        //initImageLoader();
        if (user != null) {
            showUserAvatar(user.getAvatar());
            tv_name.setText(user.getNickName());
        } else {
            contactWay.setText("");
            tv_function.setText("");
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            AddPublicFriendInfoActivity.this.finish();
        } else if (id == R.id.icon) {
//            if (user.getAvatar() != null && user.getAvatar().contains("http")) {
//                Intent intent = new Intent(AddPublicFriendInfoActivity.this,
//                        ShowBigImageActivity.class);
//                intent.putExtra("path", user.getAvatar());
//                startActivity(intent);
            //   } else {
            // ToastUtil.showToast(AddPublicFriendInfoActivity.this, "该公众号暂未设置头像");

        } else if (id == R.id.re_historymessage) {
            // Toast.makeText(this,"点击查看历史消息",Toast.LENGTH_SHORT).show();
        } else {

            myHandler.sendEmptyMessage(2);

            try {
                GetHttpUtil.focusPublicNumber(AddPublicFriendInfoActivity.this,
                        EnvironmentVariable.getProperty(CHAT_USER_ID),
                        EnvironmentVariable.getProperty(CHAT_PASSWORD),
                        user.getId(),
                        new GetHttpUtil.FocusPublicCallBack() {
                            @Override
                            public void focusPublicSuccess(boolean isSuccess) {
                                if (isSuccess) {
                                    myHandler.sendEmptyMessage(1);//取消关注中dialog

                                    user.setType(User.PUBLICFRIEND);
                                    user.setIsBother(false);
                                    user.setLoginUserId(Integer.parseInt(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                                    WeChatDBManager.getInstance()
                                            //  .insertOfficialNumber(user);
                                            .insertUserTable(user);

                                    if (user.getGroupUserType() == 0) {
                                        ToastUtil.showToast(AddPublicFriendInfoActivity.this, R.string.chat_follow_public_success);
                                        myHandler.sendEmptyMessage(4);
                                    } else {
                                        showAlertDialog();//展示需要申请的提示
                                    }

                                } else {
                                    myHandler.sendEmptyMessage(1);
                                    ToastUtil.showToast(AddPublicFriendInfoActivity.this,
                                            R.string.chat_follow_public_fail);
                                }
                            }
                        });
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }


    /**
     * 显示用户头像
     */

    public void showUserAvatar(String url) {
//        if ("公众号".equals(user.getNickName())) {
//            icon
//                    .setImageResource(R.drawable.icon_official_account);
//        } else if ("群聊".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.icon_group_chat);
//        } else if ("组织机构".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.icon_organization);
//        } else if ("人力资源系统".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.rlzy);
//        } else if ("内控系统".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.neikong);
//        } else if ("固定资产系统".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.gdzc);
//        } else if ("财务核算系统".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.czhs);
//        } else if ("生产监控系统".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.scjk2);
//        } else if ("生产日报系统".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.bj);
//        } else if ("CRM系统".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.crm);
//        } else if ("普联餐厅".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.ct);
//        } else if ("普联健身".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.jianshen);
//        } else if ("奥体中心".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.atzx);
//        } else if ("乒乓球室".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.ppq);
//        } else if ("篮球场".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.lanqiu);
//        } else if ("足球场".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.zuqiu);
//        } else if ("新的朋友".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.icon_official_account);
//        }
//        else if ("中油铁工".equals((user.getNickName()))) {
//            icon.setImageResource(R.drawable.zhongyoutg);
//        }
//        else if ("大庆油田".equals(user.getNickName())) {
//            icon.setImageResource(R.drawable.daqingyoutian);
//        }
//        if (url.contains("http")) {
//            imageLoader.displayImage(url, icon, options);
//        } else {
//            imageLoader.displayImage("", icon, options);
//        }
        LXGlideImageLoader.getInstance().showRoundUserAvatar(this, icon, url, LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
    }

    private void showAlertDialog() {
        new AlertDialog.Builder(AddPublicFriendInfoActivity.this).
                setMessage(ResStringUtil.getString(R.string.chat_send_request_success)).setTitle(R.string.common_text_hint)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        AddPublicFriendInfoActivity.this.finish();
                        dialogInterface.dismiss();
                    }
                }).show();
    }

    /**
     * 异步加载头像
     */

//    public void initImageLoader() {
//        // 初始化异步加载图片的类
//        //imageLoader = ImageLoader.getInstance();
//        // 设置异步加载图片的配置信息
//        options = ImageUtil.getImageLoaderOptions(R.drawable.default_useravatar);
//
//    }

    public class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
               dismissLoading();
            } else if (msg.what == 2) {
              showLoading(ResStringUtil.getString(R.string.chat_attention_follow));
            } else if (msg.what == 4) {
                dismissLoading();
                Intent intent = null;
//                if (user.getId() == 2307){//代记账应用号-2307
//                    intent = new Intent(AddPublicFriendInfoActivity.this, EFAppAccountDJZMainActivity.class);
//                }else {
//                    intent = new Intent(AddPublicFriendInfoActivity.this, EFAppAccountMainActivity.class);
//                }
                intent = new Intent(AddPublicFriendInfoActivity.this, EFAppAccountMainActivity.class);
                intent.putExtra("id", user.getId());
                intent.putExtra("nickName", user.getNickName());
                startActivity(intent);
                AddPublicFriendInfoActivity.this.finish();
            }
        }
    }
}