package com.efounder.chat.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.appcompat.app.AlertDialog;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.model.ShareContent;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.service.OSPService;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.utils.HandleShareIntentUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.ServiceUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ReflectUtils;
import com.utilcode.util.ToastUtils;

import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 联信应用本地分享activity
 *
 * @author yqs
 */

public class MobileShareMainActivity extends BaseActivity implements View.OnClickListener {

    private final String TAG = "MobileShareMainActivity";

    private RelativeLayout rlWeblayout;
    private ConstraintLayout clWebLayout;
    private ImageView webImage;
    private TextView webSubject, webTitle;
    private TextView tvUrl;
    private RelativeLayout rlIamgelayout;
    private GridView gridView;
    private LinearLayout llMenu;

    private LinearLayout llMenu2;

    private TextView tv_title_text;
    private GridViewAdapter mAdapter;


    //分享类型 0 文字 1 图片 2 图文消息  图片文字带url
    private int shareType = HandleShareIntentUtil.SHARE_TYPE_TEXT;
    private ShareContent shareContent = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wechatview_activity_mobile_share_main);
        initView();
        checkIsLogin();


    }

    private void checkIsLogin() {
        String chatUserID = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String chatPassword = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        if (null == chatUserID || "".equals(chatUserID)
                || null == chatPassword || "".equals(chatPassword)) {
            //用户没有登陆 跳转登录界面
            new AlertDialog.Builder(this).setTitle(R.string.common_text_hint)
                    .setMessage(ResStringUtil.getString(R.string.chat_not_login_after_share))
                    .setCancelable(false)
                    .setPositiveButton(R.string.chat_go_login, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            try {
                                intent.setClass(MobileShareMainActivity.this, Class.forName("com.efounder.activity.Login_withTitle"));
                                startActivity(intent);
                                finish();
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    })
                    .setNeutralButton(R.string.common_text_back, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .show();
            return;
        } else {
            startService(new Intent(this, MessageService.class));
            if (!ServiceUtils.isServiceRunning(getApplicationContext(), SystemInfoService.class.getCanonicalName())) {
                startService(new Intent(this, SystemInfoService.class));
            }
            if (!ServiceUtils.isServiceRunning(getApplicationContext(), OSPService.class.getCanonicalName())) {
                startService(new Intent(this, OSPService.class));
            }
            initData();
        }

    }


    private void initView() {
        //标题
        TextView tvTitle = (TextView) this.findViewById(R.id.tv_title);
        tvTitle.setText(R.string.chat_share_to);
        TextView cannelView = (TextView) findViewById(R.id.tv_save);
        cannelView.setVisibility(View.VISIBLE);
        cannelView.setText(R.string.common_text_cancel);
        cannelView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        rlWeblayout = (RelativeLayout) findViewById(R.id.rl_weblayout);
        clWebLayout = (ConstraintLayout) findViewById(R.id.cl_webLayout);
        webImage = (ImageView) findViewById(R.id.imageview);
        webSubject = (TextView) findViewById(R.id.tvTitle);
        webTitle = (TextView) findViewById(R.id.tvMessage);
        tvUrl = (TextView) findViewById(R.id.tv_url);
        tv_title_text = (TextView) findViewById(R.id.tv_title_text);
        tv_title_text.setMovementMethod(ScrollingMovementMethod.getInstance());
        rlIamgelayout = (RelativeLayout) findViewById(R.id.rl_iamgelayout);
        gridView = (GridView) findViewById(R.id.gridView);
        llMenu = (LinearLayout) findViewById(R.id.ll_menu);
//        ivAvatar = (ImageView) findViewById(R.id.iv_avatar);
//        tvName = (TextView) findViewById(R.id.tv_name);
//        ivArrow = (ImageView) findViewById(R.id.iv_arrow);
        llMenu2 = (LinearLayout) findViewById(R.id.ll_menu2);
//        ivAvatar2 = (ImageView) findViewById(R.id.iv_avatar2);
//        tvName2 = (TextView) findViewById(R.id.tv_name2);
//        ivArrow2 = (ImageView) findViewById(R.id.iv_arrow2);
        llMenu.setOnClickListener(this);
        llMenu2.setOnClickListener(this);
//        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                ViewPagerActivity.showImageWall(MobileShareMainActivity.this,
//                        localPathList.toArray(new String[localPathList.size()]), position, view);
//            }
//        });

        //todo 需要判断是否具有引力场的功能，没有的话不要显示分享菜单,通过反射的方式判断

        try {
            ReflectUtils reflectUtils = ReflectUtils.reflect("com.efounder.zone.fragment.MainZoneFragment");
        } catch (ReflectUtils.ReflectException e) {
            Log.e(TAG, "不具有引力场功能，屏蔽分享到引力场");
            llMenu2.setVisibility(View.GONE);
        }


    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void initData() {

        Intent intent = getIntent();
        shareContent = HandleShareIntentUtil.handleIntent(this, intent);
        if (shareContent != null) {
            shareType = shareContent.getType();
            refreshView();
        } else {
            ToastUtils.showShort(R.string.chat_share_error);
        }
    }

    private void refreshView() {
        //纯文本
        if (shareType == HandleShareIntentUtil.SHARE_TYPE_TEXT) {
            rlIamgelayout.setVisibility(View.GONE);
            clWebLayout.setVisibility(View.GONE);
            rlWeblayout.setVisibility(View.VISIBLE);
            tv_title_text.setText(shareContent.getText());
        } else if (shareType == HandleShareIntentUtil.SHARE_TYPE_IMAGE) {
            //图片
            rlIamgelayout.setVisibility(View.VISIBLE);
            rlWeblayout.setVisibility(View.GONE);
            clWebLayout.setVisibility(View.GONE);
            mAdapter = new GridViewAdapter(this, 1, shareContent.getPictureList());
            gridView.setAdapter(mAdapter);

        } else if (shareType == HandleShareIntentUtil.SHARE_TYPE_WEB) {
            //网页
            rlIamgelayout.setVisibility(View.GONE);
            clWebLayout.setVisibility(View.VISIBLE);
            rlWeblayout.setVisibility(View.GONE);
            webSubject.setText(shareContent.getSubject());
            webTitle.setText(shareContent.getText());
            LXGlideImageLoader.getInstance().displayImage(this, webImage, shareContent.getImgUrl(),
                    R.drawable.share_web, R.drawable.share_web);
        }
    }

    /**
     * 返回
     *
     * @param view
     */
    @Override
    public void back(View view) {
        finish();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_menu) {
            if (shareContent.getType() == HandleShareIntentUtil.SHARE_TYPE_IMAGE && shareContent.getPictureList().size() == 0) {
                ToastUtils.showShort(R.string.chat_share_empty);
                return;
            }
            Intent intent = getIntent();
            intent.setClass(MobileShareMainActivity.this, MobileShareActivity.class);
            startActivity(intent);
            finish();

        } else if (id == R.id.ll_menu2) {
            if (shareContent.getType() == HandleShareIntentUtil.SHARE_TYPE_IMAGE && shareContent.getPictureList().size() == 0) {
                ToastUtils.showShort(R.string.chat_share_empty);
                return;
            }
            Intent intent = new Intent();
            if (shareContent != null) {
                intent.putExtra("shareContent", shareContent);
            }
            intent.setClass(MobileShareMainActivity.this, ShareToZoneActivity.class);
            startActivity(intent);
            finish();
        }
    }


    public static class GridViewAdapter extends ArrayAdapter<String> {

        private List<String> list;
        private Context mContext;

        public GridViewAdapter(Context context, int textViewResourceId, List<String> objects) {
            super(context, textViewResourceId, objects);
            list = objects;
            this.mContext = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(getContext(), R.layout.wechatview_item_share_image_grid, null);
            }

            ImageView imageView = (ImageView) convertView.findViewById(R.id.imageview);
            LXGlideImageLoader.getInstance().displayImage(mContext, imageView, list.get(position));


            return convertView;
        }

    }
}
