package com.qhclh.ytzh.work.Hatchery;

import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.qhclh.ytzh.R;
import com.qhclh.ytzh.base.BaseActivity;
import com.qhclh.ytzh.home.RpcUrl;
import com.qhclh.ytzh.tasks.ViewOnClickTask;
import com.qhclh.ytzh.ui.Chose2timePopuWindow;
import com.qhclh.ytzh.ui.LinkedHorizontalScrollView;
import com.qhclh.ytzh.ui.NoScrollHorizontalScrollView;
import com.qhclh.ytzh.utils.DateTimeUtil;

import org.forks.jsonrpc.JsonRpcResult;
import org.forks.jsonrpc.RpcFacade;
import org.forks.jsonrpc.RpcObject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * Created by 青花瓷 on 2018/4/2.
 */

public class HatcheryReportActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.sv_title_hatchery)
    NoScrollHorizontalScrollView sv_title;//不可滑动的顶部左侧的ScrollView
    @BindView(R.id.sv_report_detail_hatchery)
    LinkedHorizontalScrollView sv_report_detail;//底部左侧的ScrollView
    @BindView(R.id.lv_left)
    ListView lv_buildhousename;//底部左侧的ListView
    @BindView(R.id.lv_report_info_right)
    ListView lv_report_info;//底部右侧的ListView
    @BindView(R.id.ll_main)
    LinearLayout ll_main;
    @BindView(R.id.tv_toolbar_title)
    TextView tv_toolbar_title;

    private boolean isLeftListEnabled = false;
    private boolean isRightListEnabled = false;

    private HatcheryReportInfoAdapter adapter;

    private List<HatcheryReportBean> reportBeanList;

    private long hatchingStoreID;
    private String HatchName;
    @Override
    protected int setLayoutId() {
        return R.layout.act_hatchery_report;
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initToolbar(mToolbar, "", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        combination(lv_buildhousename, lv_report_info, sv_title, sv_report_detail);
    }

    @Override
    protected void initData() {
        hatchingStoreID= getIntent().getLongExtra("hatchingStoreID",0);
        HatchName = getIntent().getStringExtra("HatchName");
        tv_toolbar_title.setText(HatchName);
        reportBeanList = new ArrayList<>();
        adapter = new HatcheryReportInfoAdapter(HatcheryReportActivity.this,reportBeanList);
        lv_report_info.setAdapter(adapter);
    }

    @Override
    protected void initOper() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            long first = (long)1000 * 60 * 60 * 24*38;
            long second = (long)1000 * 60 * 60 * 24*19;
            QueryHatchingStoreDetails(hatchingStoreID,new SimpleDateFormat("yyyy-MM-dd").parse(DateTimeUtil.getYMD(new Date(System.currentTimeMillis() - first))),new SimpleDateFormat("yyyy-MM-dd").parse(DateTimeUtil.getYMD(new Date(System.currentTimeMillis() - second))));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.chosetime, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.chose_time:
                Chose2timePopuWindow popuWindow = new Chose2timePopuWindow(HatcheryReportActivity.this);
                popuWindow.showPopupWindow();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private void combination(final ListView lvName, final ListView lvDetail, final HorizontalScrollView title, LinkedHorizontalScrollView content) {
        /**
         * 左右滑动同步
         */
        content.setMyScrollChangeListener(new LinkedHorizontalScrollView.LinkScrollChangeListener() {
            @Override
            public void onscroll(LinkedHorizontalScrollView view, int x, int y, int oldx, int oldy) {
                title.scrollTo(x, y);
            }
        });

        /**
         * 上下滑动同步
         */
        // 禁止快速滑动
        lvName.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        lvDetail.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        //左侧ListView滚动时，控制右侧ListView滚动
        lvName.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //这两个enable标志位是为了避免死循环
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                    isRightListEnabled = false;
                    isLeftListEnabled = true;
                } else if (scrollState == SCROLL_STATE_IDLE) {
                    isRightListEnabled = true;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                                 int totalItemCount) {
                View child = view.getChildAt(0);
                if (child != null && isLeftListEnabled) {
                    lvDetail.setSelectionFromTop(firstVisibleItem, child.getTop());
                }
            }
        });

        //右侧ListView滚动时，控制左侧ListView滚动
        lvDetail.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                    isLeftListEnabled = false;
                    isRightListEnabled = true;
                } else if (scrollState == SCROLL_STATE_IDLE) {
                    isLeftListEnabled = true;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                                 int totalItemCount) {
                View c = view.getChildAt(0);
                if (c != null && isRightListEnabled) {
                    lvName.setSelectionFromTop(firstVisibleItem, c.getTop());
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false)
    public void onEvent(ChoseTimeEvent event) {
        QueryHatchingStoreDetails(hatchingStoreID,event.getStartDate(),event.getEndDate());
    }

    private void QueryHatchingStoreDetails(final long id,final Date starDate,final Date endDate) {
        ViewOnClickTask hatchTask = new ViewOnClickTask(HatcheryReportActivity.this,"加载中...") {
            List<RpcObject> objList;
            @Override
            protected void successUI() {
                reportBeanList.clear();
                for (int i =0;i<objList.size();i++){
                    String HatchIncubateDate="";
                    if (objList.get(i).getDate("HatchIncubateDate")!=null){
                        HatchIncubateDate = DateTimeUtil.getYMD(objList.get(i).getDate("HatchIncubateDate"));
                    }
                    String BreedFactory_Name = "";
                    if (objList.get(i).getString("BreedFactory_Name")!= null){
                        BreedFactory_Name = objList.get(i).getString("BreedFactory_Name");
                    }
                    String WeekAge = "";
                    if (objList.get(i).getString("WeekAge")!= null){
                        WeekAge = objList.get(i).getString("WeekAge");
                    }

                    String HatchIncubateNumber = "";
                    if (objList.get(i).getDecimal("HatchIncubateNumber")!= null){
                        HatchIncubateNumber = objList.get(i).getDecimal("HatchIncubateNumber").setScale(0, BigDecimal.ROUND_DOWN).toString();
                    }

                    String NumberSurvival_HatchDownTray = "";
                    if (objList.get(i).getInt("NumberSurvival_HatchDownTray")!= null){
                        NumberSurvival_HatchDownTray = objList.get(i).getInt("NumberSurvival_HatchDownTray")+"";
                    }
                    String NumberDead_HatchDownTray = "";
                    if (objList.get(i).getInt("NumberDead_HatchDownTray")!= null){
                        NumberDead_HatchDownTray = objList.get(i).getInt("NumberDead_HatchDownTray")+"";
                    }
                    String Number_HatchChickOut_Estimated = "";
                    if (objList.get(i).getInt("Number_HatchChickOut_Estimated")!= null){
                        Number_HatchChickOut_Estimated = objList.get(i).getInt("Number_HatchChickOut_Estimated")+"";
                    }
                    String SurvivalyRate = "";
                    if (objList.get(i).getDecimal("SurvivalyRate")!= null){
                        SurvivalyRate = objList.get(i).getDecimal("SurvivalyRate").multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString() + "%";
                    }
                    String DeadRate = "";
                    if (objList.get(i).getDecimal("DeadRate")!= null){
                        DeadRate = objList.get(i).getDecimal("DeadRate").multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString() + "%";
                    }
                    reportBeanList.add(new HatcheryReportBean(i,HatchIncubateDate,BreedFactory_Name,WeekAge
                            ,HatchIncubateNumber,NumberSurvival_HatchDownTray,NumberDead_HatchDownTray
                            ,Number_HatchChickOut_Estimated,SurvivalyRate,DeadRate));

                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public Object call() throws Exception {
                JsonRpcResult result = RpcFacade.rpcCall(RpcUrl.QueryHatchingStoreDetails,id,starDate,endDate);
                objList = result.getRpcObjectList(RpcUrl.QueryHatchingStoreDetails_fanhui);
                return null;
            }
        };
        hatchTask.execute();
    }
}
