package com.genlot.ninglottery.module.cancel;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.genlot.devicesdk.Printer;
import com.genlot.nativesdk.SystemNI;
import com.genlot.nativesdk.model.GameTicket;
import com.genlot.ninglottery.R;
import com.genlot.ninglottery.base.BaseMVPActivity;
import com.genlot.ninglottery.base.InjectPresenter;
import com.genlot.ninglottery.game.GameManager;
import com.genlot.ninglottery.model.Constant;
import com.genlot.ninglottery.model.PlayTypeID;
import com.genlot.ninglottery.toolkit.GameUtil;
import com.genlot.ninglottery.toolkit.LogTool;
import com.genlot.ninglottery.toolkit.TimeUtils;

import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

public class CancelActivity extends BaseMVPActivity implements ICancelView {

    @InjectPresenter
    CancelPresenter mPresenter;

    @OnClick(R.id.icon_close)
    public void close() {
        finish();
    }

    @OnClick(R.id.bt_cancel)
    public void cancel() {
        if (GameManager.isTrainMode) {
            onCancelSuccess(System.currentTimeMillis() / 1000);
        } else {
            mPresenter.t101300Cancel(mFeatureCode);
        }
    }

    private GameTicket mTicket;
    private String mFeatureCode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window win = this.getWindow();
        win.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = 864;
        lp.height = 564;
        lp.gravity = Gravity.CENTER;//设置对话框置顶显示
        win.setAttributes(lp);
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_cancel;
    }

    @Override
    public void initViews(Bundle savedInstanceState) {
        mTicket =  getIntent().getParcelableExtra(Constant.KEY_TICKET);
        mFeatureCode = getIntent().getStringExtra(Constant.KEY_CODE);
        StringBuilder feature = new StringBuilder();
        feature.append(mFeatureCode);
        feature.insert(4, "-");
        feature.insert(9, "-");
        feature.insert(14, "-");
        feature.insert(19, "-");
        feature.insert(24, "-");
        feature.insert(29, "-");
        tvFeatureCode.setText(feature.toString());
        if (mTicket != null) {
            tvGameName.setText(GameManager.getGameName(mTicket.mGameID));
            int playId = GameUtil.getPlayType(mTicket.mPlayType, mTicket.mBets);
            String playName = GameManager.getPlayTypeName(playId);
            if (playId == PlayTypeID.K3_SUM) {
                playName = "和值";
            }
            tvIssue.setText(String.format(Locale.getDefault(), "期号：%s", mTicket.mGameIssue));
            tvIssues.setText(String.format(Locale.getDefault(), "多    期：%d", mTicket.mMultiIssue));
            tvPlayName.setText(String.format(Locale.getDefault(), "玩法：%s", playName));
            tvStation.setText(String.format(Locale.getDefault(), "站号：%d", mTicket.mTerminalID));
            tvSn.setText(String.format(Locale.getDefault(), "流水号：%d", mTicket.mTicketSN));
            tvMoney.setText(String.format(Locale.getDefault(), "金额：%.2f元",  mTicket.mBettingMoney));
            tvSaleTime.setText(String.format(Locale.getDefault(), "销售时间：%s", TimeUtils.getDetailTime(mTicket.mBettingTime)));
            tvBetNums.setText(Html.fromHtml(GameUtil.parseTicketNum(mTicket)));
            tvAddress.setText(String.format(Locale.getDefault(), "站地址：%s", GameManager.getStationAddress()));
            //取第一个投注号码放到 mGameBetData[0][0] 里,用于计算验票码
            mTicket.mFeatureCode = mFeatureCode;
            try {
                String firstBetNum = mTicket.gameBetDataString[0].substring(0, mTicket.gameBetDataString[0].indexOf("|"));
                int firstNum = Integer.valueOf(firstBetNum);
                mTicket.mGameBetData[0][0] = firstNum;
            } catch (Exception exception) {
                LogTool.logE("ticket.mGameBetData set failed, " + exception.getMessage());
            }
            StringBuilder verifyCode = new StringBuilder();
            verifyCode.append(SystemNI.verifyCode(mTicket));
            verifyCode.insert(8, "-");
            verifyCode.insert(17, "-");
            verifyCode.insert(26, "-");
            tvCheckCode.setText(String.format(Locale.getDefault(), "验票码:%s", verifyCode.toString()));
            String statusResult = GameUtil.parseStatus(mTicket.mValid);
            if (!"有效".equals(statusResult)) {
                btCancel.setEnabled(false);
            }
        }
    }

    @Override
    public void onCancelSuccess(long cancelTime) {
        dismissLoading();
        runOnUiThread(() -> {
            btCancel.setEnabled(false);
            if (printCancelTicket(CancelActivity.this, cancelTime)) {
                finish();
            }
        });
    }

    private boolean printCancelTicket(Context context, long cancelTime) {
        Printer.preload(Printer.DEVICE_YK_T91, Printer.INTERFACE_USB);
        Printer.preloadUSBAttr(Constant.PRINT_VID, Constant.PRINT_PID);
        Printer.openPrinter(context);
        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);
        Printer.printString("--------------------------------------");
        Printer.lineFeed(1);
        str = "游  戏: " + GameManager.getGameName(mTicket.mGameID);
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "站  号: " + mTicket.mTerminalID;
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "期  号: " + mTicket.mGameIssue;
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "流水号: " + mTicket.mTicketSN;
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "面  额: " + String.format(Locale.getDefault(),"%.2f元",mTicket.mBettingMoney);
        Printer.printString(str);
        Printer.lineFeed(1);
        //打印注销信息
        Printer.printString("--------------------------------------");
        Printer.lineFeed(1);
        str = "注销站号: " + SystemNI.getTerminalID();
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "操作员  : " + GameManager.getUser();
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "注销时间: " + TimeUtils.getDetailTime(cancelTime);
        Printer.printString(str);
        Printer.lineFeed(4);

        int ret = Printer.cutPaper();
        Printer.closePrinter();
        return 0 == ret;
    }

    @BindView(R.id.tv_feature_code)
    TextView tvFeatureCode;
    @BindView(R.id.tv_game_name)
    TextView tvGameName;
    @BindView(R.id.tv_issue)
    TextView tvIssue;
    @BindView(R.id.tv_issues)
    TextView tvIssues;
    @BindView(R.id.tv_play_name)
    TextView tvPlayName;
    @BindView(R.id.tv_station)
    TextView tvStation;
    @BindView(R.id.tv_sn)
    TextView tvSn;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_sale_time)
    TextView tvSaleTime;
    @BindView(R.id.tv_bet_num)
    TextView tvBetNums;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_check_code)
    TextView tvCheckCode;

    @BindView(R.id.bt_cancel)
    Button btCancel;
}
