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

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
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.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.common.ui.adapter.BuildManageAdapter;
import com.tofly.ghrq_route.module.buildManage.BuildTool;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageCallback;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageController;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildProcessManageBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.controller.UserController;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.module.user.domain.UserMenuBean;

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

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

/**
 * Created by Amu on 2017/5/22.
 * 工地监护
 */

public class UiBuildManage extends BaseUi {

    @BindView(R.id.layout_app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.layout_trouble_module)
    HorizontalScrollView layoutTroubleModule;
    /*     @BindView(R.id.tab_layout)
        TabLayout tabLayout;
       @BindView(R.id.view_pager)
        ViewPager viewPager;*/
    @BindView(R.id.ll_upLoad)
    LinearLayout llUpLoad;
    @BindView(R.id.ll_history)
    LinearLayout llHistory;
    @BindView(R.id.ll_gd)
    LinearLayout llGd;
    @BindView(R.id.ll_cx)
    LinearLayout llCx;
    @BindView(R.id.recycler_view)
    ARecycleView recyclerView;

    private int mSelectState = -1;
    //private JobListPageAdapter pageAdapter;
    private DBDaoHelper dbDaoHelper;
    //private List<String> labelList = new ArrayList<>();
    private BuildManageAdapter buildManageAdapter;
    private BuildTool buildTool;
    private UserController userController;
    private BuildManageController buildManageController;
    private int page = 1;

    boolean hasListModule = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_build_list);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        initTopContent();
        initTabLayout();
    }

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

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

    private void initTabLayout() {
        dbDaoHelper = DBDaoHelper.getInstance();
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        List<UserMenuBean> menuBeans = dbDaoHelper.getUserMenuList(userBean.getUserid());
        if (menuBeans != null && menuBeans.size() > 0) {
            for (UserMenuBean userMenuBean : menuBeans) {
                switch (userMenuBean.getCode()) {
/*                    case "gongdijianhupaigong":
                        labelList.add("派工");
                        if (mSelectState == -1) {
                            mSelectState = 0;
                        }
                        break;*/
                    case "gongdijianhuguochengguanli":
                        //labelList.add("过程管理");
                        if (mSelectState == -1) {
                            mSelectState = 2;
                        }
                        hasListModule = true;
                        break;
/*                    case "gongdijianhushenhe":
                        labelList.add("审核");
                        if (mSelectState == -1) {
                            mSelectState = 3;
                        }
                        break;*/
                    case "gongdijianhuguidang":
                        llGd.setVisibility(View.VISIBLE);
                        break;
                    case "gongdijianhushangbao":
                        llUpLoad.setVisibility(View.VISIBLE);
                        llHistory.setVisibility(View.VISIBLE);
                        break;
                    case "gongdijianhuchaxun":
                        llCx.setVisibility(View.VISIBLE);
                        break;
                }
            }
        }

/*        String[] tabTitle = labelList.toArray(new String[0]);
        pageAdapter = new JobListPageAdapter(this, labelList);
        viewPager.setAdapter(pageAdapter);
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < pageAdapter.getCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null)
                tab.setText(tabTitle[i]);
        }*/
    }

    private void initData() {
        buildTool = BuildTool.getInstance();

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

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.bg_recyclerview_divider);
        dividerItemDecoration.setDrawable(drawable);
        recyclerView.addItemDecoration(dividerItemDecoration);

        List<BuildManageBean> mBuildManageList = new ArrayList<>();
        buildManageAdapter = new BuildManageAdapter(this, mBuildManageList, mSelectState);
        //recyclerView = pageAdapter.getRecycleView(0);

        if (hasListModule) {
            recyclerView.setAdapter(buildManageAdapter);
            recyclerView.setOnRefreshListener(UiBuildManage.this::getOnlineBuildList);
            getOnlineBuildList();
        }

        getUserList();
    }

    private void getUserList() {
        if (userController == null) {
            userController = new UserController(this);
        }
        userController.getUserList("", new UserCallBack());
        if (buildManageController == null) {
            buildManageController = new BuildManageController(this);
        }
        buildManageController.getManagerList(new BuildManageCallback());
        buildManageController.getBuildType(new BuildManageCallback());
    }

    private void initListener() {
        /*viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                recyclerView = pageAdapter.getRecycleView(position);
                switch (labelList.get(position)) {
                    case "派工":
                        mSelectState = 0;
                        break;
                    case "过程管理":
                        mSelectState = 2;
                        break;
                    case "审核":
                        mSelectState = 3;
                        break;
                }
                if (recyclerView != null) {
                    buildManageAdapter.clear();
                    recyclerView.setAdapter(buildManageAdapter);
                    recyclerView.setOnRefreshListener(UiBuildManage.this::getOnlineBuildList);
                    Handler handler = new Handler();
                    handler.postDelayed(() -> getOnlineBuildList(), 100);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });*/

        if (buildManageAdapter != null) {
            buildManageAdapter.setOnItemClickListener((view, position) -> {
                BuildManageBean buildManageBean = buildManageAdapter.getItem(position);
                if (buildManageBean != null) {
                    Intent intent = new Intent();
                    switch (mSelectState) {
                        case 0:
                            intent.setClass(UiBuildManage.this, UiBuildDispatch.class);
                            intent.putExtra("id", buildManageBean.getId());
                            startActivityForResult(intent, 0x0001);
                            break;
                        case 2:
                            intent.setClass(UiBuildManage.this, UiBuildProcessManage.class);
                            intent.putExtra("build_manage", buildManageBean);
                            startActivityForResult(intent, 0x0001);
                            break;
                        case 3:
                            intent.setClass(UiBuildManage.this, UiBuildExamine.class);
                            intent.putExtra("id", buildManageBean.getId());
                            startActivityForResult(intent, 0x0001);
                            break;
                    }
                }
            });


            buildManageAdapter.setHandleClickListener((view, position, list) -> {
                BuildManageBean buildManageBean = buildManageAdapter.getItem(position);
                if (buildManageBean != null) {
                    if (!TextUtils.isEmpty(buildManageBean.getId())) {
                        List<BuildProcessManageBean> processManageBeans = dbDaoHelper.getBuildProcessManage(buildManageBean.getId());
                        if (processManageBeans != null && processManageBeans.size() > 0) {
                            updateBuildLogAlert(buildManageBean);
                        } else {
                            toast("请先进行过程管理");
                        }
                    }
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x0001 && resultCode == 0x001) {
            getOnlineBuildList();
        }
    }

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

    private void stopRefreshing() {
        Handler handler = new Handler();
        handler.postDelayed(() -> {
            recyclerView.setRefreshing(false);
            recyclerView.hideMoreProgress();
        }, 1000);
    }

    private void getOnlineBuildList() {
        if (mSelectState == 2) {
            getProcess();
        } else {
            getData();
        }
    }

    private void getData() {
        startRefreshing();
        if (buildManageController == null)
            buildManageController = new BuildManageController(this);
        buildManageController.getDataList(mSelectState, page, 10, new BuildManageCallback() {
            @Override
            public void onGetBuildManageList(boolean isSuccess, int errorCode, String errMsg, List<BuildManageBean> buildManageList, int total) {
                super.onGetBuildManageList(isSuccess, errorCode, errMsg, buildManageList, total);
                stopRefreshing();
                if (isSuccess) {
                    recyclerView.setTotal(total);
                    buildManageAdapter.clear();
                    if (buildManageList != null) {
                        if (mSelectState == 3) {
                            String userid = BaseApp.getInstance().getLoginUser().getUserid();
                            Iterator<BuildManageBean> it = buildManageList.iterator();
                            while (it.hasNext()) {
                                BuildManageBean b = it.next();
                                if (!TextUtils.isEmpty(b.getDispatchUserId())) {
                                    if (!b.getDispatchUserId().equals(userid)) {
                                        it.remove();
                                    }
                                } else {
                                    it.remove();
                                }
                            }
                        }
                        buildManageAdapter.addAll(buildManageList);
                        buildManageAdapter.setDatas(mSelectState);
                    }
                }
            }
        });
    }

    private void getProcess() {
        startRefreshing();
        buildTool.getServerBuildManages(this, String.valueOf(mSelectState), new BuildManageCallback() {
            @Override
            public void onGetBuildManageList(boolean isSuccess, int errorCode, String errMsg, List<BuildManageBean> buildList, int total) {
                super.onGetBuildManageList(isSuccess, errorCode, errMsg, buildList, total);
                stopRefreshing();
                /*加载本地保存的计划*/
                getLocalBuildList();
            }
        });
    }

    private void getLocalBuildList() {
        buildTool.getLocalBuildManages(this, String.valueOf(mSelectState), new BuildManageCallback() {
            @Override
            public void onGetBuildManageList(boolean isSuccess, int errorCode, String errMsg, List<BuildManageBean> buildManageList, int total) {
                super.onGetBuildManageList(isSuccess, errorCode, errMsg, buildManageList, total);
                stopRefreshing();
                if (isSuccess) {
                    recyclerView.setTotal(total);
                    buildManageAdapter.clear();
                    if (buildManageList != null) {
                        buildManageAdapter.addAll(buildManageList);
                        buildManageAdapter.setDatas(mSelectState);
                    }
                }
            }
        });
    }

    private void updateBuildLogAlert(BuildManageBean buildManageBean) {
        String title = "结束监护";
        String content = "是否结束工地监护?";
        showAlertWithConfirmCancelButton(title, content, true, (dialogInterface, i) -> updateBuildLog(buildManageBean));
    }

    /**
     * 更新工地监护状态
     */
    private void updateBuildLog(final BuildManageBean buildManage) {
        if (buildManage != null) {
            String strUploading = getString(R.string.uploading_data);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            buildTool.updateBuildLogState(this, buildManage, new BuildManageCallback() {
                @Override
                public void onUpdateBuildLog(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUpdateBuildLog(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        getOnlineBuildList();
                        toast("操作成功");
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        toast(errMsg);
                    }
                }
            });
        }
    }

    @OnClick({R.id.ll_upLoad, R.id.ll_history, R.id.ll_gd, R.id.ll_cx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_upLoad:
                Intent intent = new Intent(this, UiBuildFoundFirst.class);
                startActivityForResult(intent, 0x0001);
                break;
            case R.id.ll_history:
                Intent intent1 = new Intent(this, UiBuildHistoryActivity.class);
                startActivity(intent1);
                break;
            case R.id.ll_gd:
                Intent intent2 = new Intent(this, UiBuildGdActivity.class);
                startActivity(intent2);
                break;
            case R.id.ll_cx:
                Intent intent3 = new Intent(this, UiBuildCXActivity.class);
                startActivity(intent3);
                break;
        }
    }
}
