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

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

import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

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.common.ui.adapter.ReportedPhotoHistoryAdapter;
import com.tofly.ghrq_route.module.uploadPhoto.UploadPhotoTool;
import com.tofly.ghrq_route.module.uploadPhoto.controller.UploadPhotoCallBack;
import com.tofly.ghrq_route.module.uploadPhoto.domain.ReportedPhotoBean;
import com.tofly.ghrq_route.module.uploadPhoto.domain.UploadPhotoEvent;
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.common.util.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;

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 UiPhotoReportHistory 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.layout_photo_module)
    HorizontalScrollView layoutPhotoModule;
    @BindView(R.id.layout_photo_upload_module)
    LinearLayout layoutPhotoUpload;
    @BindView(R.id.text_select_depart)
    TextView textSelectDepart;
    @BindView(R.id.text_select_user)
    TextView textSelectUser;
    @BindView(R.id.recycler_view)
    ARecycleView recyclerView;

    private String mDepartId = null;

    private String mUserId = null;

    private String mPicTypeId = null;

    private List<DepartmentBean> mDepartmentList;

    private List<DepartmentUserBean> mUserList;

    private int indexDepartment = 0;

    private int indexUser = 0;

    private int pageindex = 1;

    private UploadPhotoTool uploadPhotoTool;

    private ReportedPhotoHistoryAdapter photoHistoryAdapter;

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

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

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

        EventBusUtil.register(this);
    }

    @Subscribe
    public void onMessageEvent(UploadPhotoEvent event) {
        if (UploadPhotoEvent.UPLOAD_PHOTO_UPLOADED.equals(event.message)) {
            pageindex = 1;
            getReportedPhoto();
        }
    }

    private void initView(){
       initTopContent();
    }

    private void initTopContent() {
        // 4.4及以上版本开启
        setTranslucentStatus();
        //setToolbarPadding();

        initAppBar();
    }

    private void initAppBar() {
        // 4.4及以上版本开启
        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            if (verticalOffset == 0) {
                if (state != CollapsingToolbarLayoutState.EXPANDED) {
                    collapsingToolbarLayout.setTitle("");//设置title不显示
                    layoutPhotoUpload.setVisibility(View.VISIBLE);
                    state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                    collapsingToolbarLayout.setTitle("");
                    layoutPhotoUpload.setVisibility(View.GONE);
                    state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                }
            } else {
                if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                    if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                        collapsingToolbarLayout.setTitle("");//设置title不显示
                        layoutPhotoUpload.setVisibility(View.VISIBLE);
                    }
                    state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                }
            }
        });
    }

    private void initData(){
        uploadPhotoTool = UploadPhotoTool.getInstance();

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

        List<ReportedPhotoBean> photoList = new ArrayList<>();
        photoHistoryAdapter = new ReportedPhotoHistoryAdapter(this, photoList);
        recyclerView.setAdapter(photoHistoryAdapter);

        getReportedPhoto();
        getDepartAssigner();
    }

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

        recyclerView.setOnLoadMoreListener(() -> {
            pageindex++;
            getReportedPhoto();
        });

        photoHistoryAdapter.setOnItemClickListener((view, position) -> {
            ReportedPhotoBean photoBean = photoHistoryAdapter.getItem(position);
            gotoUiPhotoDetail(photoBean);
        });
    }


    private void gotoUiPhotoDetail(ReportedPhotoBean photoBean) {
        if (photoBean != null){
            Bundle bundle = new Bundle();
            bundle.putSerializable(ReportedPhotoBean.REPORTED_PHOTO_BEAN_KEY, photoBean);
            Intent intent = new Intent();
            intent.setClass(this, UiPhotoReportedDetail.class);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

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

        if (mUserList == null || mUserList.isEmpty()) {
            getDepartmentUsers(mDepartId);
        }
    }

    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);
                textSelectDepart.setText(departAll.getName());
                if (isSuccess) {
                    if (departmentList != null) {
                        mDepartmentList.addAll(departmentList);
                    }
                }
            }
        });
    }

    private void showDepartSelectPopupWindow(){
        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<>(this, R.layout.popup_content_item, tableNames));
        listPopupWindow.setOnItemClickListener((parent, view, position, id) -> {
            boolean bNeedReload = indexDepartment != position;
            indexDepartment = position;
            textSelectDepart.setText(tableNames.get(indexDepartment));
            if (bNeedReload) {
                DepartmentBean department = mDepartmentList.get(indexDepartment);
                mDepartId = department.getId();
                indexUser = 0;
                mUserId = null;
                getDepartmentUsers(mDepartId);

                pageindex = 1;
                getReportedPhoto();
            }
            listPopupWindow.dismiss();
        });
        listPopupWindow.setAnchorView(textSelectDepart);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.show();
    }

    private void getDepartmentUsers(String departId) {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartmentUsers(this, departId, new UserCallBack(){
            @Override
            public void onGetDepartmentUserList(boolean isSuccess, int errorCode, String errMsg, List<DepartmentUserBean> userList) {
                super.onGetDepartmentUserList(isSuccess, errorCode, errMsg, userList);
                mUserList = new ArrayList<>();
                DepartmentUserBean userBean = new DepartmentUserBean();
                userBean.setId(null);
                userBean.setRealName("全部人员");
                mUserList.add(userBean);
                textSelectUser.setText(userBean.getRealName());
                if (isSuccess) {
                    if (userList != null) {
                        mUserList.addAll(userList);
                    }
                }
            }
        });
    }


    private void showUserSelectPopupWindow(){
        List<String> tableNames = new ArrayList<>();
        for (int i = 0; i < mUserList.size(); i++) {
            DepartmentUserBean userBean = mUserList.get(i);
            tableNames.add(userBean.getRealName());
        }

        final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setAdapter(new ArrayAdapter<>(this, R.layout.popup_content_item, tableNames));
        listPopupWindow.setOnItemClickListener((parent, view, position, id) -> {
            boolean bNeedReload = indexUser != position;
            indexUser = position;
            textSelectUser.setText(tableNames.get(indexUser));
            DepartmentUserBean userBean = mUserList.get(indexUser);
            mUserId = userBean.getId();
            if (bNeedReload) {
                pageindex = 1;
                getReportedPhoto();
            }
            listPopupWindow.dismiss();
        });
        listPopupWindow.setAnchorView(textSelectUser);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.show();
    }

    private void getReportedPhoto() {
        startRefreshing();
        uploadPhotoTool.getReportedPhotoListOnline(this, mPicTypeId, mDepartId, mUserId, pageindex, new UploadPhotoCallBack(){
            @Override
            public void onGetReportedPhoto(boolean isSuccess, int errorCode, String errMsg, List<ReportedPhotoBean> photoBeans, int total) {
                super.onGetReportedPhoto(isSuccess, errorCode, errMsg, photoBeans, total);
                stopRefreshing();
                if (isSuccess) {
                    if (pageindex == 1) {
                        recyclerView.setTotal(total);
                        photoHistoryAdapter.clear();
                    }
                    if (photoBeans != null)
                        photoHistoryAdapter.addAll(photoBeans);
                }

            }
        });
    }

    @OnClick({R.id.layout_photo_upload_module, R.id.text_select_depart, R.id.text_select_user})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_photo_upload_module:
                Intent intent = new Intent();
                intent.setClass(this, UiPhotoReport.class);
                startActivity(intent);
                break;
            case R.id.text_select_depart:
                showDepartSelectPopupWindow();
                break;
            case R.id.text_select_user:
                showUserSelectPopupWindow();
                break;
        }
    }

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

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


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