package com.gingersoft.gsa.cloud.main.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.PrintTransitUtils;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.main.R;
import com.gingersoft.gsa.cloud.main.R2;
import com.gingersoft.gsa.cloud.main.di.component.DaggerBusinessReportComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.BusinessReportContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.BusinessBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.DailyReportBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.DaySalesReportBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.MainBusinessBean;
import com.gingersoft.gsa.cloud.main.mvp.presenter.BusinessReportPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.view.BillingAnalysisReportView;
import com.gingersoft.gsa.cloud.main.mvp.ui.view.DailyBusinessView;
import com.gingersoft.gsa.cloud.main.mvp.ui.view.OperatingReportView;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartConfiger.AAChartModel;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartConfiger.AAChartView;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartConfiger.AASeriesElement;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartEnum.AAChartLineDashStyleType;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartEnum.AAChartType;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AATools.AAGradientColor;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AATools.AALinearGradientDirection;
import com.gingersoft.gsa.cloud.ui.utils.TimePickerUtils;
import com.gingersoft.gsa.cloud.ui.view.TriangleView;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 02/23/2020 16:19
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 * 營業報表
 */
public class BusinessReportFragment extends BaseFragment<BusinessReportPresenter> implements BusinessReportContract.View, View.OnClickListener {

    @BindView(R2.id.report_business_chart)
    AAChartView mLineChart;
    //    @BindView(R2.id.rv_business_details)
//    RecyclerView mBusinessDetails;
//    @BindView(R2.id.tv_restaurant_name)
//    TextView mRestaurantName;
    @BindView(R2.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R2.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R2.id.iv_start_time_triangle)
    TriangleView triangleView;
    @BindView(R2.id.iv_end_time_triangle)
    TriangleView endTimeTriangleView;
    //    @BindView(R2.id.tv_report_bill_number)
//    TextView tvBillNumber;
//    @BindView(R2.id.tv_report_bill_average_price)
//    TextView tvBillAvgPrice;
//    @BindView(R2.id.tv_report_people_number)
//    TextView tvPeople;
//    @BindView(R2.id.tv_report_people_average_price)
//    TextView tvPeopleAvgPrice;
    @BindView(R2.id.layout_report_print)
    LinearLayout layout_report_print;
    //    @BindView(R2.id.layout_business_report)
//    LinearLayout LayoutBusinessReport;
    //    @BindView(R2.id.table_business)
//    SmartTable mTableBusiness;
    @BindView(R2.id.btn_print_business)
    QMUIAlphaButton btnPintBusiness;
    //    private BusinessInfoAdapter businessInfoAdapter;
//    private BusinessInfoAdapter printBusinessInfoAdapter;
    //查詢多少天的數據
    private int manyDay = 7;
    private String restaurantId;

    private boolean mChartFocus;


    public static BusinessReportFragment newInstance() {
        BusinessReportFragment fragment = new BusinessReportFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerBusinessReportComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_business_report, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        restaurantId = String.valueOf(RestaurantInfoManager.newInstance().getRestaurantId());
        //獲取一段時間內的營業信息，默認獲取七天的數據
        startTime = TimeUtils.getOldDate(-manyDay);

        mTvStartTime.setText(TimeUtils.getOldDate(-manyDay + 1));
        mTvEndTime.setText(TimeUtils.getOldDate(0));

        //处理报表滑动过程中和页面滑动出现冲突
        mLineChart.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mLineChart.requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        mLineChart.requestDisallowInterceptTouchEvent(false);
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        mLineChart.requestDisallowInterceptTouchEvent(false);
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        getInfo();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(_mActivity, message, true);
        else
            LoadingDialog.showDialogForLoading(_mActivity);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ArmsUtils.makeText(mContext, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    /**
     * 加載營業信息圖表
     */
    @Override
    public void loadChart(List<MainBusinessBean.DataBean> data) {
        Object[] chartData = new Object[manyDay];

        String[] xData = new String[manyDay];

        Calendar cal = Calendar.getInstance();
        //設置默認時間為當前的起止時間-1天，因為要把起始時間算進去
        try {
            Date parse = TimeUtils.DATE_FORMAT_DATE.parse(TimeUtils.getDatebyDate(startTime, -1));
            if (parse != null) {
                cal.setTime(parse);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < manyDay; i++) {
            xData[i] = TimeUtils.getBeginDistanceDate(cal, 1, Calendar.DATE, TimeUtils.DEFAULT_DATE_MD);
        }

        //將數據以時間為key，數據為value存入map
        Map<String, MainBusinessBean.DataBean> map = new HashMap<>();
        int size = manyDay;
        if (data.size() <= manyDay) {
            size = data.size();
        }
        for (int i = 0; i < size; i++) {
            map.put(data.get(i).getStartingTime(), data.get(i));
        }
        //y軸 數據間隔
        double yAxisTickInterval = 0;
        //第一條線
        int year = cal.get(Calendar.YEAR);
        for (int i = 0; i < manyDay; i++) {
            //通過今年年份+月份+日期，獲取對應的對象
            MainBusinessBean.DataBean bean = map.get(year + "-" + xData[i]);
            if (bean != null) {
                chartData[i] = bean.getTotalAmount();
                yAxisTickInterval = Math.max(yAxisTickInterval, bean.getTotalAmount());
            } else {
                chartData[i] = 0;
            }
        }
        //配置線形圖
        AAChartModel aaChartModel = configureColorfulGradientSplineChart(xData, chartData, (int) (yAxisTickInterval / 6));
        //如果這幾天的數據都為0，設置默認最大數為18000，間隔為3000
        if (yAxisTickInterval < 1) {
            aaChartModel.yAxisMax(18000f);
            aaChartModel.yAxisTickInterval(3000);
        } else {
            aaChartModel.yAxisMax(null);
        }
        mLineChart.aa_drawChartWithChartModel(aaChartModel);
    }

    /**
     * @param todayData         今天的數據
     * @param yAxisTickInterval y軸間隔
     * @return
     */
    AAChartModel configureColorfulGradientSplineChart(String[] xData, Object[] todayData, int yAxisTickInterval) {
        Object[][] stopsArr = {
                {0.00, "#018EF2"},
        };//颜色字符串设置支持十六进制类型和 rgba 类型
        Map<String, Object> linearGradientColor = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToLeft,
                stopsArr
        );//颜色字符串设置支持十六进制类型和 rgba 类型

        return new AAChartModel()
                .chartType(AAChartType.Spline)
                .title("")
                .subtitle("")
                .yAxisTitle("")
                .axesTextColor("#777777")
                .axesTextSize(9)
                .legendEnabled(false)
                .markerRadius(0f)
                .categories(xData)
                .yAxisLineWidth(0.5f)
                .xAxisLineWidth(0.5f)
                .yAxisAllowDecimals(false)
                .yAxisTickInterval(yAxisTickInterval)
                .gridLineColor("#8CA0B3")
                .yAxisMin(0f)
                .gridLineDashStyle(AAChartLineDashStyleType.ShortDash)
                .dataLabelsFontColor("#777777")
                .yAxisLineColor("#018EF2")
                .series(new AASeriesElement[]{
                                new AASeriesElement()
                                        .name("營業額")
                                        .lineWidth(4f)
                                        .color(linearGradientColor)
                                        .data(todayData)
                        }
                );
    }

    /**
     * 每日營業詳情
     */
    private DailyBusinessView dailyBusinessView;
    /**
     * 賬單分析
     */
    private BillingAnalysisReportView billingAnalysisReportView;
    /**
     * 營業金額淨值詳情
     */
    private OperatingReportView netOperatingAmountView;
    /**
     * 訂單詳情
     */
    private OperatingReportView orderDetailsReportView;
    /**
     * 折扣詳情
     */
    private OperatingReportView discountDetailsReportView;
    private View[] printViews = new View[5];

    @Override
    public void loadBillReport(DaySalesReportBean.DataBean dataBean) {
        printViews[1] = new BillingAnalysisReportView(mContext).setPrint(true).setDataBean(dataBean).init();
        if (billingAnalysisReportView == null) {
            billingAnalysisReportView = new BillingAnalysisReportView(mContext).setPrint(false).setDataBean(dataBean);
            billingAnalysisReportView.init();
            billingAnalysisReportView.setOnReLoadListener(() -> mPresenter.getDaySalesReport(restaurantId, startTime, endTime));
            if (dailyBusinessView != null) {
                layout_report_print.addView(billingAnalysisReportView);
                if (netOperatingAmountView != null) {
                    layout_report_print.addView(netOperatingAmountView);
                    if (orderDetailsReportView != null) {
                        layout_report_print.addView(orderDetailsReportView);
                        if (discountDetailsReportView != null) {
                            layout_report_print.addView(discountDetailsReportView);
                        }
                    }
                }
            }
        } else {
            billingAnalysisReportView.setData(dataBean);
        }
    }


    @Override
    public void loadDaySalesReport(List<BusinessBean> businessBeans) {
        printViews[0] = new DailyBusinessView(mContext, true, businessBeans).init();
        if (dailyBusinessView == null) {
            dailyBusinessView = new DailyBusinessView(mContext, false, businessBeans);
            dailyBusinessView.init();
            dailyBusinessView.setOnReLoadListener(() -> mPresenter.getDaySalesReport(restaurantId, startTime, endTime));
            layout_report_print.addView(dailyBusinessView);
            if (billingAnalysisReportView != null) {
                layout_report_print.addView(billingAnalysisReportView);
                if (netOperatingAmountView != null) {
                    layout_report_print.addView(netOperatingAmountView);
                    if (orderDetailsReportView != null) {
                        layout_report_print.addView(orderDetailsReportView);
                        if (discountDetailsReportView != null) {
                            layout_report_print.addView(discountDetailsReportView);
                        }
                    }
                }
            }
        } else {
            dailyBusinessView.setNewData(businessBeans);
        }
    }

    @Override
    public void loadOrderAnalysis(List<DailyReportBean> dailyReportBeans) {
        printViews[2] = new OperatingReportView(mContext, true, "營業金額淨值詳情", dailyReportBeans, 4).init();
        if (netOperatingAmountView == null) {
            netOperatingAmountView = new OperatingReportView(mContext, false, "營業金額淨值詳情", dailyReportBeans, 4);
            netOperatingAmountView.setOnReLoadListener(() -> mPresenter.getOrderAnalysis(restaurantId, startTime, endTime));
            netOperatingAmountView.init();
            if (billingAnalysisReportView != null && dailyBusinessView != null) {
                layout_report_print.addView(netOperatingAmountView);
                if (orderDetailsReportView != null) {
                    layout_report_print.addView(orderDetailsReportView);
                    if (discountDetailsReportView != null) {
                        layout_report_print.addView(discountDetailsReportView);
                    }
                }
            }
        } else {
            netOperatingAmountView.setNewData(dailyReportBeans);
        }
    }

    @Override
    public void loadOrderDetailsReport(List<DailyReportBean> dailyReportBeans) {
        printViews[3] = new OperatingReportView(mContext, true, "訂單詳情", dailyReportBeans, 4).init();
        if (orderDetailsReportView == null) {
            orderDetailsReportView = new OperatingReportView(mContext, false, "訂單詳情", dailyReportBeans, 4);
            orderDetailsReportView.setOnReLoadListener(() -> mPresenter.getOrderDetailsReport(restaurantId, startTime, endTime));
            orderDetailsReportView.init();
            if (billingAnalysisReportView != null && dailyBusinessView != null && netOperatingAmountView != null) {
                layout_report_print.addView(orderDetailsReportView);
                if (discountDetailsReportView != null) {
                    layout_report_print.addView(discountDetailsReportView);
                }
            }
        } else {
            orderDetailsReportView.setNewData(dailyReportBeans);
        }
    }

    @Override
    public void loadDiscountDetailsReport(List<DailyReportBean> dailyReportBeans) {
        printViews[4] = new OperatingReportView(mContext, true, "折扣詳情", dailyReportBeans, 3).init();
        if (discountDetailsReportView == null) {
            discountDetailsReportView = new OperatingReportView(mContext, false, "折扣詳情", dailyReportBeans, 3);
            discountDetailsReportView.init();
            discountDetailsReportView.setOnReLoadListener(() -> mPresenter.getDiscountDetails(restaurantId, startTime, endTime));
            if (billingAnalysisReportView != null && dailyBusinessView != null && netOperatingAmountView != null && orderDetailsReportView != null) {
                layout_report_print.addView(discountDetailsReportView);
            }
        } else {
            discountDetailsReportView.setNewData(dailyReportBeans);
        }
    }

    @OnClick({R2.id.btn_print_business, R2.id.tv_start_time, R2.id.iv_start_time_triangle, R2.id.tv_end_time, R2.id.iv_end_time_triangle})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_print_business) {
            if (printViews != null) {
                //打印
                LinearLayout layout = new LinearLayout(mContext);
                layout.removeAllViews();
                layout.setOrientation(LinearLayout.VERTICAL);
                for (View printView : printViews) {
                    if (printView != null) {
                        layout.addView(printView);
                    }
                }
                PrintTransitUtils.getInstance().setPrintView(layout);
                CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                        .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_CLEAN_MACHINE)//清機打印
                        .setActionName("printActivity")
                        .build()
                        .callAsyncCallbackOnMainThread((cc, result) -> {
                            // 打印完之後，清除view
                            layout.removeAllViews();
                            PrintTransitUtils.getInstance().setPrintView(null);
                        });
            }
        } else if (viewId == R.id.tv_start_time || viewId == R.id.iv_start_time_triangle || viewId == R.id.tv_end_time || viewId == R.id.iv_end_time_triangle) {
            try {
                String time;
                Calendar startTime = Calendar.getInstance();
                startTime.set(Calendar.DAY_OF_YEAR, startTime.getActualMinimum(Calendar.DAY_OF_YEAR));//今年第一天

                Calendar endTime = Calendar.getInstance();

                if (viewId == R.id.tv_start_time || viewId == R.id.iv_start_time_triangle) {
                    triangleView.toggle();
                    time = mTvStartTime.getText().toString();

                    endTime.setTime(TimeUtils.DATE_FORMAT_DATE.parse(mTvEndTime.getText().toString()));
                } else {
                    endTimeTriangleView.toggle();
                    time = mTvEndTime.getText().toString();
                    startTime.setTime(TimeUtils.DATE_FORMAT_DATE.parse(mTvStartTime.getText().toString()));
                }

                Calendar cal = Calendar.getInstance();
                try {
                    //設置默認時間為當前的起止時間
                    cal.setTime(TimeUtils.DATE_FORMAT_DATE.parse(time));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //打開時間選擇器
                TimePickerUtils.showReportTimePicker(mContext, startTime, endTime, cal, (date, v1) ->
                {
                    if (viewId == R.id.tv_start_time || viewId == R.id.iv_start_time_triangle) {
                        mTvStartTime.setText(TimeUtils.DATE_FORMAT_DATE.format(date));
                    } else {
                        mTvEndTime.setText(TimeUtils.DATE_FORMAT_DATE.format(date));
                    }
                    getInfo();
                }).setOnDismissListener(o -> {
                    if (triangleView.isOpen()) {
                        triangleView.toggle();
                    } else if (endTimeTriangleView.isOpen()) {
                        endTimeTriangleView.toggle();
                    }
                });
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private String startTime;
    private String endTime;

    private void getInfo() {
        startTime = TimeUtils.getDatebyDate(mTvStartTime.getText().toString(), 0);
        endTime = TimeUtils.getDatebyDate(mTvEndTime.getText().toString(), 1);
        mPresenter.getRestaurantAmount(restaurantId, startTime, endTime);
        mPresenter.getRestaurantBusinessInfo(restaurantId, startTime, endTime);

        mPresenter.getDaySalesReport(restaurantId, startTime, endTime);
        mPresenter.getOrderAnalysis(restaurantId, startTime, endTime);
        mPresenter.getOrderDetailsReport(restaurantId, startTime, endTime);
        mPresenter.getDiscountDetails(restaurantId, startTime, endTime);
    }


}
