package com.tofly.ghrq_route.common.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.lcp.arecyclerview.widget.ARecycleView;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.DepartmentBean;
import com.tofly.ghrq_route.module.user.domain.DepartmentUserBean;
import com.tofly.ghrq_route.module.user.domain.MessageUserBean;
import com.tofly.ghrq_route.common.ui.adapter.UserPhoneAdapter;
import com.tofly.ghrq_route.common.util.app.AppUtil;

import java.util.ArrayList;
import java.util.List;

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

/**
 * Created by Amu on 2017/10/9.
 */

public class UiPhoneCall extends BaseUi {
    @BindView(R.id.layout_app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.layout_collapse_toolbar)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.text_select_table)
    TextView textSelectState;
    @BindView(R.id.recycler_view)
    ARecycleView recyclerView;

    //private final static String TAG = UiPhoneCall.class.getSimpleName();

    private PermissionHelper permissionHelper;

    private UserPhoneAdapter userPhoneAdapter;

    private DepartmentUserBean userSelected;

    private String mDepartId = null;

    private List<DepartmentBean> mDepartmentList;

    private int mTableIndex = 0;

    private int pageindex = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_phone_call);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();
    }

    private void initView(){
       initAppBar();
        textSelectState.setText("全部");
    }

    private void initAppBar() {
        // 4.4及以上版本开启
        setTranslucentStatus();
        setToolbarPadding();
        setLightStatusBar();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {

        });
    }

    private void initData(){
        permissionHelper = new PermissionHelper(this);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        List<DepartmentUserBean> userList = new ArrayList<>();
        userPhoneAdapter = new UserPhoneAdapter(this, userList);
        recyclerView.setAdapter(userPhoneAdapter);

        startRefreshing();
        getDepartAssigner();
        getUserList();
    }

    private void  initListener(){
        recyclerView.setOnRefreshListener(() -> {
            pageindex = 1;
            getUserList();
        });

        userPhoneAdapter.setItemPhoneClickListener((view, position) -> {
            DepartmentUserBean userBean = userPhoneAdapter.getItem(position);
            if (userBean != null){
                userSelected = userBean;
                checkCallPermission();
            }
        });

        userPhoneAdapter.setItemMessageClickListener((view, position) -> {
            DepartmentUserBean userBean = userPhoneAdapter.getItem(position);
            if (userBean != null){
                userSelected = userBean;
                gotoUiMessageNew();
            }
        });
    }

    @OnClick({R.id.text_select_table})
    public void onClick(View view) {
        if (view.getId() == R.id.text_select_table) {
            showTableSelectPopupWindow();
        }
    }

    @Override
    public void onBackPressed() {
        gotoSystemHome();
    }

    private void startRefreshing() {
        recyclerView.setRefreshing(true);
    }

    private void stopRefreshing() {
        recyclerView.postDelayed(() -> {
            recyclerView.setRefreshing(false);
            recyclerView.hideMoreProgress();
        }, 2000);
    }

    private void getDepartAssigner() {
        if (mDepartmentList == null || mDepartmentList.isEmpty()) {
            getDepartments();
        }
    }

    private void getDepartments() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartments(this, false, new UserCallBack(){
            @Override
            public void onGetDepartmentList(boolean isSuccess, int errorCode, String errMsg, List<DepartmentBean> departmentList) {
                super.onGetDepartmentList(isSuccess, errorCode, errMsg, departmentList);
                mDepartmentList = new ArrayList<>();
                DepartmentBean departAll = new DepartmentBean();
                departAll.setId(null);
                departAll.setName("全部");
                mDepartmentList.add(departAll);
                if (isSuccess) {
                    mDepartmentList.addAll(departmentList);
                }
            }
        });
    }

    private void showTableSelectPopupWindow(){
        List<String> tableNames = new ArrayList<>();
        for (int i = 0; i < mDepartmentList.size(); i++) {
            DepartmentBean departmentBean = mDepartmentList.get(i);
            tableNames.add(departmentBean.getName());
        }

        final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setAdapter(new ArrayAdapter<String>(this, R.layout.popup_content_item, tableNames));
        listPopupWindow.setOnItemClickListener((parent, view, position, id) -> {
            boolean bNeedReload = mTableIndex != position;
            mTableIndex = position;
            textSelectState.setText(tableNames.get(mTableIndex));
            if (bNeedReload) {
                DepartmentBean department = mDepartmentList.get(mTableIndex);
                mDepartId = department.getId();
                getUserList();
            }
            listPopupWindow.dismiss();
        });
        listPopupWindow.setAnchorView(textSelectState);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.show();
    }

    private void getUserList(){
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartmentUsers(this, mDepartId, new UserCallBack(){
            @Override
            public void onGetDepartmentUserList(boolean isSuccess, int errorCode, String errMsg, List<DepartmentUserBean> userList) {
                super.onGetDepartmentUserList(isSuccess, errorCode, errMsg, userList);
                stopRefreshing();
                if (isSuccess && userList != null) {
                    if (userList.size() > 0) {
                        int total = userList.size();
                        if (pageindex == 1) {
                            recyclerView.setTotal(total);
                            userPhoneAdapter.clear();
                        }
                        userPhoneAdapter.addAll(userList);
                    }else {
                        recyclerView.setTotal(0);
                        userPhoneAdapter.clear();
                    }
                } else {
                    toast(errMsg);
                }
            }
        });
    }

    private void gotoUiMessageNew(){
        if (userSelected != null){
            List<MessageUserBean> userBeanList = new ArrayList<>();
            MessageUserBean userBean = new MessageUserBean();
            userBean.setId(Integer.parseInt(userSelected.getId()));
            userBean.setAvatar(userSelected.getAvatar());
            userBean.setMobile(userSelected.getMobile());
            userBean.setRealName(userSelected.getRealName());
            userBean.setUsername(userSelected.getUsername());
            userBean.setUserid(userSelected.getId());

            userBeanList.add(userBean);
            ArrayList list = new ArrayList();
            list.add(userBeanList);

            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList("receiver_list", list);

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClass(UiPhoneCall.this, UIMessageNew.class);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    private void checkCallPermission() {
        String callPermission = Manifest.permission.CALL_PHONE;
        permissionHelper.requestPermissions("请授予[拨号]权限，否则无法进行拨号", new PermissionHelper.PermissionListener() {
            @Override
            public void doAfterGrand(String... permission) {
                startUserCall();
            }

            @Override
            public void doAfterDenied(String... permission) {
                String errstr = "获取授权失败,无法拨打电话";
                toast(errstr);
            }
        }, callPermission);
    }

    private void startUserCall() {
        if (userSelected != null){
            String mobile = userSelected.getMobile();
            AppUtil.startPhoneCall(this, mobile);
        }
    }

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