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


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.LinearLayout;
import android.widget.TextView;

import com.genlot.devicesdk.Printer;
import com.genlot.nativesdk.SystemNI;
import com.genlot.nativesdk.model.GameRuntimeAttr;
import com.genlot.nativesdk.model.ReportItem;
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.game.GameManager;
import com.genlot.ninglottery.model.Constant;
import com.genlot.ninglottery.model.GameIDSet;
import com.genlot.ninglottery.module.report.IReportView;
import com.genlot.ninglottery.module.report.ReportPresenter;
import com.genlot.ninglottery.module.report.adapter.ReportAdapter;
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 com.genlot.ninglottery.widget.CustomSpinnerDropDown.SpinnerPopWindow;
import com.genlot.ninglottery.widget.KeyboardEditText;

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

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author ZhuYongKang
 * @description 期报表选择
 * @date 2019/8/20
 */
public class ReportIssueFragment extends BaseMVPFragment implements IReportView {

    @InjectPresenter
    ReportPresenter mPresenter;
    private SpinnerPopWindow mGameTypeSpinner;
    private int mGameId;
    private List<ReportSection> mReportList;
    private ReportAdapter mAdapter;
    private String sIssue,eIssue;

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

    @Override
    public void onCreateViewFinished(Bundle state) {
        super.onCreateViewFinished(state);
        initSpinner();
        mGameId = GameIDSet.GAME_ID_SSQ;
        refreshIssue();
        tvDurationTitle.setText("期号范围：");
        tvStation.setText(String.valueOf(SystemNI.getTerminalID()));
        mReportList = new ArrayList<>();
        rvReport.setLayoutManager(new LinearLayoutManager(activity));
        mAdapter = new ReportAdapter(R.layout.item_report_data, R.layout.item_report_head, mReportList);
        rvReport.setAdapter(mAdapter);
    }

    private void initSpinner() {
        mGameTypeSpinner = new SpinnerPopWindow(getActivity(), mTvGameType);
        List<String> gameNameList = new ArrayList<>(Arrays.asList("双色球", "3D", "七乐彩", "快三"));
        mGameTypeSpinner.refreshData(gameNameList);
        mTvGameType.setText(gameNameList.get(0));
        mGameTypeSpinner.setItemListener((view, pos) -> {
            mTvGameType.setText(gameNameList.get(pos));
            switch (pos) {
                case 0:
                    mGameId = GameIDSet.GAME_ID_SSQ;
                    break;
                case 1:
                    mGameId = GameIDSet.GAME_ID_3D;
                    break;
                case 2:
                    mGameId = GameIDSet.GAME_ID_SLC;
                    break;
                case 3:
                    mGameId = GameIDSet.GAME_ID_K3;
                    break;

            }
            refreshIssue();
        });
    }

    private void refreshIssue() {
        GameRuntimeAttr attr = GameManager.getGameRuntime(mGameId);
        if (attr != null) {
            etStartIssue.setText(String.valueOf(attr.mGameIssue));
            etEndIssue.setText(String.valueOf(attr.mGameIssue));
        }
    }

    @OnClick({R.id.tv_game_type, R.id.btn_confirm,R.id.btn_back,R.id.btn_print})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_game_type:
                mGameTypeSpinner.setWidth(mTvGameType.getWidth());
                mGameTypeSpinner.setHeight(200);
                mGameTypeSpinner.showAsDropDown(mTvGameType);
                break;
            case R.id.btn_confirm:
                sIssue = etStartIssue.getText().toString().trim();
                eIssue = etEndIssue.getText().toString().trim();
                if (TextUtils.isEmpty(sIssue)) {
                    etStartIssue.setError("请输入开始时段");
                    return;
                }
                if (TextUtils.isEmpty(eIssue)) {
                    etEndIssue.setError("请输入结束时段");
                    return;
                }
                tvDuration.setText(String.format("%s~%s", sIssue, eIssue));
                mReportList.clear();
                mAdapter.notifyDataSetChanged();
                llRange.setVisibility(View.GONE);
                llDetail.setVisibility(View.VISIBLE);
                mPresenter.t101401QueryIssueReport(mGameId, sIssue, eIssue);
                break;
            case R.id.btn_back:
                llRange.setVisibility(View.VISIBLE);
                llDetail.setVisibility(View.GONE);
                break;
            case R.id.btn_print:
                printReport();
                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 = "期号范围：" + sIssue + "期 ~ " + eIssue + "期";
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "打印时间：" + TimeUtils.getDetailTimeMil(System.currentTimeMillis());
        Printer.printString(str);
        Printer.lineFeed(1);

        for (int i = 0; i < mReportList.size(); i++) {
            ReportSection section = mReportList.get(i);
            if (section.isHeader) {
                Printer.printString(section.header);
                Printer.lineFeed(1);
            } else {
                ReportBean bean = section.t;
                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) {
        ReportItem item = bundle.getParcelable(EventToken.EVENT_KEY_RESULT_OBJECT);
        LogTool.logD(item.toString());
        ReportSection sectionHeader = new ReportSection(true,
                "-------------------["+mTvGameType.getText().toString()+"]-------------------");
        mReportList.add(sectionHeader);
        String[] titles = new String[]{"销售:", "注销:", "中心注销:", "冲正:", "实销:", "兑奖:"};
        int[] nums = new int[]{item.mSaleSize, item.mCancelSize, item.mCenterCancelSize,
                item.mReverseSize, item.mActualSaleSize, item.mCashSize};
        double[] moneys = new double[]{item.mSaleMoney, item.mCancelMoney, item.mCenterCancelMoney,
                item.mReverseMoney, item.mActualSaleMoney, item.mCashMoney};
        for (int i = 0; i < titles.length; i++) {
            ReportBean bean = new ReportBean();
            bean.setTitle(titles[i]);
            bean.setNum(String.valueOf(nums[i]));
            bean.setMoney(String.format(Locale.getDefault(),"%.2f", moneys[i]));
            ReportSection sectionBody = new ReportSection(bean);
            mReportList.add(sectionBody);
        }
        activity.runOnUiThread(() -> mAdapter.replaceData(mReportList));
    }

    @BindView(R.id.tv_game_type)
    TextView mTvGameType;
    @BindView(R.id.tv_start_issue)
    KeyboardEditText etStartIssue;
    @BindView(R.id.tv_end_issue)
    KeyboardEditText etEndIssue;
    @BindView(R.id.tv_report_duration_title)
    TextView tvDurationTitle;
    @BindView(R.id.tv_report_duration)
    TextView tvDuration;
    @BindView(R.id.tv_report_station)
    TextView tvStation;
    @BindView(R.id.rv_report)
    RecyclerView rvReport;

    @BindView(R.id.issue_range_layout)
    LinearLayout llRange;
    @BindView(R.id.issue_detail_layout)
    LinearLayout llDetail;

}
