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.view.View;
import android.widget.Button;
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.ReportData;
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.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.StringTool;
import com.genlot.ninglottery.toolkit.TimeUtils;

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

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author ZhuYongKang
 * @description 时段报表详情
 * @date 2019/8/20
 */
public class ReportDetailFragment extends BaseMVPFragment implements IReportView {

    /**
     * 日报表
     */
    private static final int TYPE_DAY = 0;
    /**
     * 日期包含今天为时段报表
     */
    private static final int TYPE_TIME = 1;
    /**
     * 日期不包含今天为缴款报表
     */
    private static final int TYPE_OTHER = 2;

    @InjectPresenter
    ReportPresenter mPresenter;

    private long sTime, eTime, sToday, eToday;
    private int mReportType;
    private List<ReportSection> mReportList;
    private ReportAdapter mAdapter;
    private int mGameId;

    @OnClick(R.id.btn_back)
    public void backToIssue() {
        activity.onBackPressed();
    }


    @OnClick(R.id.btn_print)
    public 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 = "";
        switch (mReportType) {
            case TYPE_DAY:
                str = "==日报表==";
                break;
            case TYPE_TIME:
                str = "==时段报表==";
                break;
            case TYPE_OTHER:
                str = "==缴款报表==";
                break;
        }
        Printer.printString(str);
        Printer.lineFeed(2);

        Printer.setFontSize(0);
        Printer.setFontBold(0);
        str = "查询方式：中心查询    站号：" + SystemNI.getTerminalID();
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "日期范围：" + TimeUtils.getShortTime(sTime) + " ~ " + TimeUtils.getShortTime(eTime);
        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();
    }

    public static ReportDetailFragment newInstance(int gameId, String sTime, String eTime) {
        Bundle args = new Bundle();
        args.putString("sTime", sTime);
        args.putString("eTime", eTime);
        args.putInt("gameId", gameId);
        ReportDetailFragment fragment = new ReportDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public void onCreateViewFinished(Bundle state) {
        super.onCreateViewFinished(state);
        sToday = TimeUtils.getStartTimeOfToday();
        eToday = TimeUtils.getLastTimeOfToday();
        sTime = sToday;
        eTime = eToday;
        mGameId = -1;
        mReportType = TYPE_DAY;
        if (getArguments() != null) {
            sTime = TimeUtils.getTimeStart(getArguments().getString("sTime"));
            eTime = TimeUtils.getTimeEnd(getArguments().getString("eTime"));
            mGameId = getArguments().getInt("gameId");
            if (eTime > sToday) {
                mReportType = TYPE_TIME;
            } else if (eTime < sToday && eTime > 0) {
                mReportType = TYPE_OTHER;
            }
        }
        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);
        tvStation.setText(String.valueOf(SystemNI.getTerminalID()));
        if (mReportType == TYPE_DAY) {
            btBack.setVisibility(View.GONE);
        } else {
            btBack.setVisibility(View.VISIBLE);
        }
        refresh();
    }

    private void refresh() {
        tvDuration.setText(String.format("%s~%s", TimeUtils.getShortTime(sTime), TimeUtils.getShortTime(eTime)));
        mPresenter.t101412QueryTimeReport(mGameId, sTime, eTime);
    }

    @Override
    public void onQuerySuccess(Bundle bundle) {
        ReportData data = bundle.getParcelable(EventToken.EVENT_KEY_RESULT_OBJECT);
        ArrayList<ReportItem> mReportItem = data.mReportItem;
        String[] titles = new String[]{"销售:", "注销:", "中心注销:", "冲正:", "实销:", "兑奖:"};
        int[] totalNums = new int[6];
        double[] totalSales = new double[6];
        //代销费
        double totalSalesCommission = 0;
        //代兑费
        double totalCashingBonus = 0;
        for (ReportItem item : mReportItem) {
            GameRuntimeAttr attr = GameManager.getGameRuntime(item.mGameID);
            //未做该游戏
            if (attr == null) {
                continue;
            }
            LogTool.logD(item.toString());
            ReportSection sectionHeader = new ReportSection(true,
                    "-------------------["+attr.mGameName+"]-------------------");
            mReportList.add(sectionHeader);
            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};
            totalNums[0] += item.mSaleSize;
            totalNums[1] += item.mCancelSize;
            totalNums[2] += item.mCenterCancelSize;
            totalNums[3] += item.mReverseSize;
            totalNums[4] += item.mActualSaleSize;
            totalNums[5] += item.mCashSize;
            totalSales[0] += item.mSaleMoney;
            totalSales[1] += item.mCancelMoney;
            totalSales[2] += item.mCenterCancelMoney;
            totalSales[3] += item.mReverseMoney;
            totalSales[4] += item.mActualSaleMoney;
            totalSales[5] += item.mCashMoney;
            totalSalesCommission += item.mSalesCommission;
            totalCashingBonus += item.mCashingBonus;
            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);
            }
        }
        //总计
        ReportSection sectionHeader = new ReportSection(true,
                "================[合计]================");
        mReportList.add(sectionHeader);
        for (int i = 0; i < titles.length; i++) {
            ReportBean bean = new ReportBean();
            bean.setTitle(titles[i]);
            bean.setNum(String.valueOf(totalNums[i]));
            bean.setMoney(String.format(Locale.getDefault(),"%.2f", totalSales[i]));
            ReportSection sectionBody = new ReportSection(bean);
            mReportList.add(sectionBody);
        }
        //余额统计
        ReportSection cashHeader = new ReportSection(true,
                "---------------------------------------------");
        mReportList.add(cashHeader);
        switch (mReportType) {
            case TYPE_DAY:
            case TYPE_TIME:
                String[] cashNames1 = {"账户余额:", "营业余额:", "信用额度:"};
                String[] cashValue1 = {data.mBalance, data.mPayment, data.mCredit};
                for (int i = 0; i < cashNames1.length; i++) {
                    ReportBean bean = new ReportBean();
                    bean.setTitle(cashNames1[i]);
                    bean.setMoney(cashValue1[i]);
                    ReportSection sectionBody = new ReportSection(bean);
                    mReportList.add(sectionBody);
                }
                break;
            case TYPE_OTHER:
                String[] cashNames2 = {"通信费:","代销费:", "代兑费:", "应交款:", "已缴款:","补偿款", "累计欠款:", "通讯补偿:","其他欠款:"};
                String[] cashValue2 = {data.mBaseCommFee, StringTool.format1(totalSalesCommission), StringTool.format1(totalCashingBonus),
                        data.mPayment, data.mHadPaid, data.mRetrieveAmount, data.mArrearage, data.mOtherIncomeMoney, data.mOtherOutgoMoney};
                for (int i = 0; i < cashNames2.length; i++) {
                    ReportBean bean = new ReportBean();
                    bean.setTitle(cashNames2[i]);
                    bean.setMoney(cashValue2[i]);
                    ReportSection sectionBody = new ReportSection(bean);
                    mReportList.add(sectionBody);
                }
                break;
        }
        activity.runOnUiThread(() -> mAdapter.replaceData(mReportList));
    }

    @BindView(R.id.btn_back)
    Button btBack;
    @BindView(R.id.tv_report_station)
    TextView tvStation;
    @BindView(R.id.tv_report_duration)
    TextView tvDuration;
    @BindView(R.id.rv_report)
    RecyclerView rvReport;

}
