package com.wd.workoffice.ui.activity.mes.report;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.WorkBaseActivity;
import com.wd.workoffice.bean.WarehoustBean;
import com.wd.workoffice.bean.mesBean.MesFactoryBean;
import com.wd.workoffice.bean.mesBean.OrderBadBean;
import com.wd.workoffice.bean.mesBean.ProBadBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.bat.order.ProductOrderAddActivity;
import com.wd.workoffice.ui.adapter.ReportBadListAdapter;
import com.wd.workoffice.ui.adapter.ReportProBadAdapter;
import com.wd.workoffice.ui.adapter.ReportTopAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.WorkUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import flexible.xd.android_base.utils.TimeUtils;
import io.reactivex.disposables.Disposable;

/**
 * 质量报表
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class MesReportActivity extends WorkBaseActivity {

    @BindView(R.id.tv_report)
    TextView tvReport;
    @BindView(R.id.tv_bad)
    TextView tvBad;
    @BindView(R.id.tb_title)
    Toolbar tbTitle;
    @BindView(R.id.rv_top)
    RecyclerView rvTop;
    @BindView(R.id.rv_pro_bad)
    RecyclerView rvProBad;
    @BindView(R.id.rv_bad)
    RecyclerView rvBad;
    @BindView(R.id.ll_report)
    LinearLayout llReport;
    @BindView(R.id.ll_bad)
    LinearLayout llBad;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ll_time)
    LinearLayout llTime;
    @BindView(R.id.tv_dept)
    TextView tvDept;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    private ReportBadListAdapter badAdapter;
    private ReportTopAdapter topAdapter;
    private ReportProBadAdapter proBadAdapter;
    private List<ProBadBean.DataBean> proBadList;
    private List<ProBadBean.DataBean> topList;
    private Map<String, Object> param;
    private List<OrderBadBean.ScrapStatisticsListsBean> badList;
    private Map<String, Object> badParam;
    private QMUIDialog.MenuDialogBuilder depDialog;
    private List<String> depNameList = new ArrayList<>();

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        setSupportActionBar(tbTitle);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        rvBad.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvProBad.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvTop.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
    }


    @Override
    protected void initData() {
        badList = new ArrayList<>();
        topList = new ArrayList<>();
        proBadList = new ArrayList<>();
        badAdapter = new ReportBadListAdapter(R.layout.item_mes_report_bad_list, badList);
        topAdapter = new ReportTopAdapter(R.layout.item_mes_report_top, topList);
        proBadAdapter = new ReportProBadAdapter(R.layout.item_mes_report_pro_bad, proBadList);
        badAdapter.bindToRecyclerView(rvBad);
        topAdapter.bindToRecyclerView(rvTop);
        proBadAdapter.bindToRecyclerView(rvProBad);
        param = WorkUtils.simpleParam();
        badParam = WorkUtils.simpleParam();
        badParam.put("beginDate", TimeUtils.getNowString());
        badParam.put("endDate", TimeUtils.getNowString());
        depDialog = DialogUtils.listDialog(this);
        getData();
        getDepData();
    }

    private void getDepData() {
        RtfUtils.getMesRtf().siteShow("1", WorkUtils.convertMapToBody(badParam)).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                List<MesFactoryBean.SitesBean> getList = JSON.parseObject(data.getData().toString(), MesFactoryBean.class).getSites();
                if (getList.size() != 0) {
                    badParam.put("siteCode", getList.get(0).getSiteCode());
                    tvDept.setText(getList.get(0).getSiteName());
                }
                depNameList.clear();
                depDialog = DialogUtils.listDialog(MesReportActivity.this);
                for (MesFactoryBean.SitesBean process : getList) {
                    depNameList.add(process.getSiteName());
                }
                depDialog.addItems(depNameList.toArray(new String[depNameList.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        badParam.put("siteCode", getList.get(which).getSiteCode());
                        tvDept.setText(depNameList.get(which));
                        dialog.dismiss();
                        getOrderBad();
                    }
                });

            }
        });
    }

    private void getData() {
        RtfUtils.getMesRtf().scrapAnalysisList("1", WorkUtils.convertMapToBody(param)).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                List<ProBadBean.DataBean> getList = JSON.parseArray(data.getData().toString(), ProBadBean.DataBean.class);
                Collections.sort(getList, new Comparator<ProBadBean.DataBean>() {
                    @Override
                    public int compare(ProBadBean.DataBean o1, ProBadBean.DataBean o2) {
                        return new BigDecimal(o2.getScrapWeight()).compareTo(new BigDecimal(o1.getScrapWeight()));
                    }
                });
                topList.clear();
                topList.addAll(getList);
                proBadList.clear();
                proBadList.addAll(getList);
                topAdapter.notifyDataSetChanged();
                proBadAdapter.notifyDataSetChanged();
            }
        });

    }

    private void getOrderBad() {
        RtfUtils.getMesRtf().scrapStatistics("1", WorkUtils.convertMapToBody(badParam)).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                List<OrderBadBean.ScrapStatisticsListsBean> getList = JSON.parseObject(data.getData().toString(), OrderBadBean.class).getScrapStatisticsLists();
                badList.clear();
                if (getList != null) {
                    badList.addAll(getList);
                }
                badAdapter.notifyDataSetChanged();

            }
        });
    }

    @Override
    protected void initEvent() {
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_mes_report;
    }


    @OnClick({R.id.tv_dept, R.id.tv_start, R.id.tv_end, R.id.ll_time, R.id.tv_report, R.id.tv_bad})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_dept:
                depDialog.show();
                break;
            case R.id.tv_start:
                PickTimeUtils.showPickThree(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                        badParam.put("beginDate", time);
                        tvStart.setText(time);
                        getOrderBad();
                    }
                }, false).show();
                break;
            case R.id.tv_end:
                PickTimeUtils.showPickThree(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                        badParam.put("endDate", time);
                        tvEnd.setText(time);
                        getOrderBad();
                    }
                }, false).show();
                break;
            case R.id.ll_time:
                PickTimeUtils.showPickTwo(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View view) {
                        String month = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM"));
                        tvTime.setText(month);
                        addMonthParam(month);
                        getData();
                    }
                }).show();
                break;
            case R.id.tv_report:
                changView(0);
                break;
            case R.id.tv_bad:
                changView(1);
                break;
        }
    }

    private void addMonthParam(String nowString) {
        param.put("beginDate", nowString + "-01 00:00:00");
        String nextMonth = (Integer.valueOf(nowString.split("-")[1]) + 1) + "";
        String nextMonthString = Integer.valueOf(nowString.split("-")[0]) + "-" + (nextMonth.length() == 2 ? nextMonth : "0" + nextMonth + "-01 00:00:00");
        param.put("endDate", nextMonthString);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void changView(int type) {
        if (type == 0) {
            llReport.setVisibility(View.VISIBLE);
            llBad.setVisibility(View.GONE);
            tvReport.setBackgroundResource(R.drawable.shape_report_choose);
            tvReport.setTextColor(Color.WHITE);
            tvBad.setBackgroundResource(R.drawable.shape_report);
            tvBad.setTextColor(Color.parseColor("#FF4A92DE"));
        } else {
            llReport.setVisibility(View.GONE);
            llBad.setVisibility(View.VISIBLE);
            tvBad.setBackgroundResource(R.drawable.shape_report_choose);
            tvBad.setTextColor(Color.WHITE);
            tvReport.setBackgroundResource(R.drawable.shape_report);
            tvReport.setTextColor(Color.parseColor("#FF4A92DE"));
        }
    }

}
