package com.genlot.ninglottery.module.report.fragments;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.genlot.devicesdk.Printer;
import com.genlot.nativesdk.SystemNI;
import com.genlot.nativesdk.model.ReportBankPayment;
import com.genlot.nativesdk.sender.EventToken;
import com.genlot.ninglottery.R;
import com.genlot.ninglottery.base.BaseMVPFragment;
import com.genlot.ninglottery.base.InjectPresenter;
import com.genlot.ninglottery.model.Constant;
import com.genlot.ninglottery.module.report.IReportView;
import com.genlot.ninglottery.module.report.ReportPresenter;
import com.genlot.ninglottery.module.report.adapter.ReportBankAdapter;
import com.genlot.ninglottery.module.report.bean.ReportBean;
import com.genlot.ninglottery.module.report.bean.ReportSection;
import com.genlot.ninglottery.toolkit.LogTool;
import com.genlot.ninglottery.toolkit.TimeUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author ZhuYongKang
 * @description 银行缴款报表界面
 * @date 2019/8/20
 */
public class ReportBankFragment extends BaseMVPFragment implements IReportView {

    @InjectPresenter
    ReportPresenter mPresenter;
    private int mYear, mMonth, mDay;
    private static final String DATE_FORMAT = "%d年%02d月%02d日";
    private String mStartDate, mEndDate;

    private List<ReportBean> mReportList;
    private ReportBankAdapter mAdapter;

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_report_bank;
    }

    @Override
    public void onCreateViewFinished(Bundle state) {
        super.onCreateViewFinished(state);
        initDate();
        mReportList = new ArrayList<>();
        rvReport.setLayoutManager(new LinearLayoutManager(activity));
        mAdapter = new ReportBankAdapter(R.layout.item_report_bank, mReportList);
        rvReport.setAdapter(mAdapter);
        tvStation.setText(String.valueOf(SystemNI.getTerminalID()));

    }

    private void initDate() {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        mYear = cal.get(Calendar.YEAR);
        mMonth = cal.get(Calendar.MONTH);
        mDay = cal.get(Calendar.DAY_OF_MONTH);
        mEdStartRange.setText(String.format(Locale.getDefault(), DATE_FORMAT, mYear, mMonth + 1, mDay));
        mEdEndRange.setText(String.format(Locale.getDefault(), DATE_FORMAT, mYear, mMonth + 1, mDay));
    }

    private DatePickerDialog.OnDateSetListener onStartDateListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            mEdStartRange.setText(String.format(Locale.getDefault(), DATE_FORMAT, mYear, mMonth + 1, mDay));
        }
    };

    private DatePickerDialog.OnDateSetListener onEndDateListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            mEdEndRange.setText(String.format(Locale.getDefault(), DATE_FORMAT, mYear, mMonth + 1, mDay));
        }
    };

    @OnClick({R.id.btn_confirm, R.id.tv_query_start_range, R.id.tv_query_end_range, R.id.btn_back, R.id.btn_print})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_query_start_range:
                new DatePickerDialog(activity, onStartDateListener, mYear, mMonth, mDay).show();
                break;
            case R.id.tv_query_end_range:
                new DatePickerDialog(activity, onEndDateListener, mYear, mMonth, mDay).show();
                break;
            case R.id.btn_confirm:
                mStartDate = mEdStartRange.getText().toString().trim();
                mEndDate = mEdEndRange.getText().toString().trim();
                if (TextUtils.isEmpty(mStartDate)) {
                    ToastUtils.showShort("请选择开始日期");
                    return;
                }
                if (TextUtils.isEmpty(mEndDate)) {
                    ToastUtils.showShort("请输入结束日期");
                    return;
                }
                tvDuration.setText(String.format("%s~%s", mStartDate, mEndDate));
                mReportList.clear();
                mAdapter.notifyDataSetChanged();
                tvPayMoney.setText("");
                tvLeftMoney.setText("");
                llRange.setVisibility(View.GONE);
                llDetail.setVisibility(View.VISIBLE);
                mPresenter.t101404QueryBankReport(String.valueOf(TimeUtils.getTimeStart(mStartDate)),
                        String.valueOf(TimeUtils.getTimeEnd(mEndDate)));
                break;
            case R.id.btn_back:
                llRange.setVisibility(View.VISIBLE);
                llDetail.setVisibility(View.GONE);
                break;
            case R.id.btn_print:
                printReport();
                break;
            default:
                break;
        }
    }

    private void printReport() {
        Printer.preload(Printer.DEVICE_YK_T91, Printer.INTERFACE_USB);
        Printer.preloadUSBAttr(Constant.PRINT_VID, Constant.PRINT_PID);
        Printer.openPrinter(getContext());
        Printer.initPrinter();

        Printer.setLeftMargin(20);
        Printer.lineFeed(2);
        Printer.setFontBold(1);
        Printer.setFontSize(17);
        String str = "==银行缴款报表==";
        Printer.printString(str);
        Printer.lineFeed(2);

        Printer.setFontSize(0);
        Printer.setFontBold(0);
        str = "站号：" + SystemNI.getTerminalID();
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "日期范围：" + mStartDate + " ~ " + mEndDate;
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "打印时间：" + TimeUtils.getDetailTimeMil(System.currentTimeMillis());
        Printer.printString(str);
        Printer.lineFeed(1);

        Printer.printString("缴款时间");
        Printer.setAbsX(220);
        Printer.printString("银行名称");
        Printer.setAbsX(400);
        Printer.printString("缴款金额(元)");
        Printer.lineFeed(1);
        for (int i = 0; i < mReportList.size(); i++) {
            ReportBean bean = mReportList.get(i);
            Printer.printString(bean.getTitle());
            Printer.setAbsX(220);
            Printer.printString(bean.getNum());
            Printer.setAbsX(400);
            Printer.printString(bean.getMoney());
            Printer.lineFeed(1);
        }
        Printer.lineFeed(4);
        Printer.cutPaper();
        Printer.closePrinter();
    }

    @Override
    public void onQuerySuccess(Bundle bundle) {
        ReportBankPayment bankPayment = bundle.getParcelable(EventToken.EVENT_KEY_RESULT_OBJECT);
        LogTool.logD(bankPayment.toString());
        List<ReportBankPayment.BankPayment> bankPaymentList = bankPayment.bankPaymentList;
        if (bankPaymentList.size() > 0) {
            for (ReportBankPayment.BankPayment payment : bankPaymentList) {
                ReportBean bean = new ReportBean();
                bean.setTitle(payment.PayedTime);
                bean.setNum("银行调帐收入");
                bean.setMoney(payment.PayedMoney);
                mReportList.add(bean);
            }
        }
        activity.runOnUiThread(() -> {
            tvPayMoney.setText(bankPayment.PayedAmount);
            tvLeftMoney.setText(bankPayment.StationAmount);
            mAdapter.replaceData(mReportList);
        });

    }

    @BindView(R.id.tv_query_start_range)
    TextView mEdStartRange;
    @BindView(R.id.tv_query_end_range)
    TextView mEdEndRange;
    @BindView(R.id.bank_range_layout)
    LinearLayout llRange;
    @BindView(R.id.bank_detail_layout)
    LinearLayout llDetail;
    @BindView(R.id.tv_report_duration)
    TextView tvDuration;
    @BindView(R.id.tv_report_station)
    TextView tvStation;
    @BindView(R.id.rv_bank_pay)
    RecyclerView rvReport;
    @BindView(R.id.tv_pay_money)
    TextView tvPayMoney;
    @BindView(R.id.tv_left_money)
    TextView tvLeftMoney;
}
