package com.genlot.ninglottery.toolkit;

import android.content.Context;

import com.genlot.devicesdk.Printer;
import com.genlot.nativesdk.SystemNI;
import com.genlot.nativesdk.model.GameRuntimeAttr;
import com.genlot.nativesdk.model.GameTicket;
import com.genlot.ninglottery.game.GameManager;
import com.genlot.ninglottery.game.bet.BetManager;
import com.genlot.ninglottery.model.Constant;
import com.genlot.ninglottery.model.GameIDSet;
import com.genlot.ninglottery.model.PlayTypeID;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author ZhuYongKang
 * @description 打印机工具类
 * @date 2019/8/29
 */
public class PrinterTool {

    private static void open(Context context) {
        Printer.preload(Printer.DEVICE_YK_T91, Printer.INTERFACE_USB);
        Printer.preloadUSBAttr(Constant.PRINT_VID, Constant.PRINT_PID);
        Printer.openPrinter(context);
        Printer.initPrinter();
    }

    /**
     * 打印机状态是否正常
     * @return the boolean
     */
    public static boolean isPrintOK(Context context) {
        open(context);
        int status = Printer.queryStatus();
        Printer.closePrinter();
        return status == 0 || status == 7;
    }

    /**
     * 打印各个游戏投注的票
     *
     * @param context   Context
     * @param ticket    GameTicket
     * @return
     */
    public static boolean printTicket(Context context, GameTicket ticket) {
        open(context);
        //打印特征码
        Printer.setFontSize(0);
        Printer.setLeftMargin(50);
        String featureCode = SystemNI.featureCode(ticket);
        ticket.mFeatureCode = featureCode;
        StringBuilder feature = new StringBuilder();
        feature.append(featureCode);
        feature.insert(4, "-");
        feature.insert(9, "-");
        feature.insert(14, "-");
        feature.insert(19, "-");
        feature.insert(24, "-");
        feature.insert(29, "-");
        Printer.printString(feature.toString());
        Printer.lineFeed(1);

        //打印图标
        Printer.setFontSize(17);
        Printer.setFontBold(1);//1 加粗
        Printer.printString("中 国 福 利 彩 票");
        Printer.lineFeed(1);

        //打印游戏名称
        Printer.setFontAlignment(1);//居中
        Printer.setFontSize(16);//00010000 高四位表示宽度,低四位表示高度
        int gameId = BetManager.getInstance().getGameId();
        int playType = GameUtil.getPlayType(ticket.mPlayType, ticket.mBets);
        Printer.printString(GameManager.getGameName(gameId));
        Printer.lineFeed(1);

        //打印玩法 期号
        Printer.setFontAlignment(0);//居左
        Printer.setLeftMargin(10);
        Printer.setFontSize(0);
        Printer.setFontBold(0);
        String str = "期号:" + ticket.mGameIssue;
        Printer.printString(str);
        Printer.setAbsX(200);
        str = "多  期:" +  BetManager.getInstance().getIssues();
        Printer.printString(str);
        Printer.setAbsX(350);
        if (playType == PlayTypeID.K3_SUM) {
            str = "玩法:" + "和值";
        } else {
            str = "玩法:" +  GameManager.getPlayTypeName(playType);
        }
        Printer.printString(str);
        Printer.lineFeed(1);

        //打印站号 流水号
        str = "站号:" + ticket.mTerminalID;
        Printer.printString(str);
        Printer.setAbsX(200);
        str = "流水号:" + ticket.mTicketSN;
        Printer.printString(str);
        Printer.lineFeed(1);

        //打印金额 销售时间
        str = "金额:" + String.format(Locale.getDefault(),"%.2f", ticket.mBettingMoney) + "元";
        Printer.printString(str);
        Printer.setAbsX(200);
        str = "销售时间:" + TimeUtils.getDetailTime(ticket.mBettingTime);
        Printer.printString(str);
        Printer.lineFeed(1);

        //打印投注号码
        switch (gameId) {
            case GameIDSet.GAME_ID_SSQ:
                printSSQBetInfo(ticket, playType);
                break;
            case GameIDSet.GAME_ID_3D:
                print3DBetInfo(ticket, playType);
                break;
            case GameIDSet.GAME_ID_SLC:
                print7LCBetInfo(ticket, playType);
                break;
            case GameIDSet.GAME_ID_K3:
                printK3BetInfo(ticket, playType);
                break;
            default:
                break;
        }

        //打印开奖时间
        Printer.setFontSize(0);
        if (GameManager.isTrainMode) {
            str = "开奖日期:" + TimeUtils.getDetailTimeMil(System.currentTimeMillis());
        } else {
            GameRuntimeAttr runtime = GameManager.getGameRuntime(ticket.mGameID);
            str = "开奖日期:" + TimeUtils.getDetailTime(runtime.mDrawTime);
        }
        Printer.printString(str);
        Printer.lineFeed(1);
        //打印站地址
        str = "站地址:" + GameManager.getStationAddress();
        Printer.printString(str);
        Printer.lineFeed(1);

        //打印验票码
        StringBuffer verifyCode = new StringBuffer();
        verifyCode.append(ticket.mVerifyCode);
        verifyCode.insert(8, "-");
        verifyCode.insert(17, "-");
        verifyCode.insert(26, "-");

        str = "验票码:" + verifyCode.toString();
        Printer.printString(str);
        Printer.lineFeed(1);

        //公益金提示语
        Printer.printString(ticket.mWelfareFundTipsString);
        Printer.lineFeed(2);
        //打印PDF417
        String srcString = featureCode + ";;;;";
        String encryptFeatureCode = SystemNI.rc4EncryptData(srcString);
        LogTool.logI("encryptFeatureCode=" + encryptFeatureCode);

        //测试解密
        //String decryptFeatureCode = SystemNI.rc4DecryptData(encryptFeatureCode);
        //LogTool.logI(LogTool.tag(), "decryptFeatureCode=" + decryptFeatureCode);

        Printer.setPDF417(16, 10, 2, 4, 3);
        Printer.printPDF417(encryptFeatureCode);
        //打印PDF417+QRcode
//        Printer.setLeftMargin(50);
//        Printer.setPDF417(10, 8, 2, 4, 3);
//        Printer.setQR(1, 3, 3);
//        Printer.printPDF417QRcodeOneRow(featureCode,(byte)60,(byte)0);

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

    private static String[] betNums = {"①", "②", "③", "④", "⑤"};

    private static void printSSQBetInfo(GameTicket ticket, int playType) {
        String[] betData = ticket.gameBetDataString;
        switch (playType) {
            case PlayTypeID.SSQ_SINGLE:
                for (int i = 0; i < ticket.mBets; i++) {
                    Printer.printString(betNums[i] + " ");
                    Printer.setFontSize(16);
                    Printer.setFontBold(1);//1 加粗
                    StringBuilder sb = new StringBuilder();
                    String[] singleNums = betData[i].split("-");
                    String[] numRed = singleNums[0].split("\\|");
                    String[] numBlue = singleNums[1].split("\\|");
                    for (String red : numRed) {
                        sb.append(StringTool.format2(Integer.parseInt(red))).append(" ");
                    }
                    sb.setCharAt(sb.length() -1,'-');
                    for (String blue : numBlue) {
                        sb.append(StringTool.format2(Integer.parseInt(blue)));
                    }
                    Printer.printString(sb.toString());
                    Printer.setFontSize(0);
                    Printer.setFontBold(0);
                    if (i == 0) {
                        Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
                    }
                    Printer.lineFeed(1);
                }
                break;
            case PlayTypeID.SSQ_MULTI:
                Printer.setFontSize(16);
                Printer.setFontBold(1);
                StringBuilder sb = new StringBuilder();
                String[] multiNums = betData[0].split("-");
                String[] numRed = multiNums[0].split("\\|");
                String[] numBlue = multiNums[1].split("\\|");
                for (String red : numRed) {
                    sb.append(StringTool.format2(Integer.parseInt(red))).append("+");
                }
                sb.setCharAt(sb.length()-1,'-');
                for (String blue : numBlue) {
                    sb.append(StringTool.format2(Integer.parseInt(blue))).append("+");
                }
                sb.setCharAt(sb.length()-1,' ');
                Printer.printString(sb.toString());
                Printer.setFontSize(0);
                Printer.setFontBold(0);
                Printer.printString(String.format(Locale.getDefault(), "[%d倍]", ticket.mMultiTimes[0]));
                Printer.lineFeed(1);
                break;
            case PlayTypeID.SSQ_BASE:
            case PlayTypeID.SSQ_BASE_MULTI:
                Printer.setFontSize(16);
                Printer.setFontBold(1);
                StringBuilder builder = new StringBuilder();
                String[] baseNums = betData[0].split("-");
                String[] numDan = baseNums[0].split("\\|");
                String[] numTuo = baseNums[1].split("\\|");
                String[] numsBlue = baseNums[2].split("\\|");
                for (String dan : numDan) {
                    builder.append(StringTool.format2(Integer.parseInt(dan))).append("+");
                }
                builder.setCharAt(builder.length()-1,'^');
                for (String tuo : numTuo) {
                    builder.append(StringTool.format2(Integer.parseInt(tuo))).append("+");
                }
                builder.setCharAt(builder.length()-1,'-');
                for (String blue : numsBlue) {
                    builder.append(StringTool.format2(Integer.parseInt(blue))).append("+");
                }
                builder.setCharAt(builder.length()-1,' ');
                Printer.printString(builder.toString());
                Printer.setFontSize(0);
                Printer.setFontBold(0);
                Printer.printString(String.format(Locale.getDefault(), "[%d倍]", ticket.mMultiTimes[0]));
                Printer.lineFeed(1);
                break;
        }
    }

    private static void print7LCBetInfo(GameTicket ticket, int playType) {
        String[] betData = ticket.gameBetDataString;
        switch (playType) {
            case PlayTypeID.STAR_7_SINGLE:
                for (int i = 0; i < ticket.mBets; i++) {
                    Printer.printString(betNums[i] + " ");
                    Printer.setFontSize(16);
                    Printer.setFontBold(1);
                    String[] nums = betData[i].split("\\|");
                    StringBuilder sb = new StringBuilder();
                    for (String num : nums) {
                        sb.append(num).append(" ");
                    }
                    Printer.printString(sb.toString());
                    Printer.setFontSize(0);
                    Printer.setFontBold(0);
                    if (i == 0) {
                        Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
                    }
                    Printer.lineFeed(1);
                }
                break;
            case PlayTypeID.STAR_7_MULTI:
                Printer.setFontSize(16);
                Printer.setFontBold(1);
                String[] multiNums = betData[0].split("\\|");
                StringBuilder sb = new StringBuilder();
                for (String num : multiNums) {
                    sb.append(num).append("+");
                }
                sb.setCharAt(sb.length() - 1,' ');
                Printer.printString(sb.toString());
                Printer.setFontSize(0);
                Printer.setFontBold(0);
                Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
                Printer.lineFeed(1);
                break;
            case PlayTypeID.STAR_7_BASE_ROUND:
                Printer.setFontSize(16);
                Printer.setFontBold(1);
                String[] baseNums = betData[0].split("-");
                String[] numDan = baseNums[0].split("\\|");
                String[] numTuo = baseNums[1].split("\\|");
                StringBuilder sbBase = new StringBuilder();
                for (String dan : numDan) {
                    sbBase.append(dan).append("+");
                }
                sbBase.setCharAt(sbBase.length() - 1, '^');
                for (String tuo : numTuo) {
                    sbBase.append(tuo).append("+");
                }
                sbBase.setCharAt(sbBase.length() - 1, ' ');
                Printer.printString(sbBase.toString());
                Printer.setFontSize(0);
                Printer.setFontBold(0);
                Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
                Printer.lineFeed(1);
                break;
        }
    }

    private static void print3DMulti(String bet) {
        String[] nums = bet.split("-");
        String[] serials = {"[百]", "[十]", "[个]"};
        for (int i = 0; i < 3; i++) {
            Printer.printString(serials[i] + " ");
            Printer.setFontSize(16);
            Printer.setFontBold(1);
            String[] numWei = nums[i].split("\\|");
            String[] betWei = {"-","-","-","-","-","-","-","-","-","-"};
            System.arraycopy(numWei, 0, betWei, 0, numWei.length);
            StringBuilder sb = new StringBuilder();
            for (String wei : betWei) {
                sb.append(wei).append(" ");
            }
            Printer.printString(sb.toString());
            Printer.setFontSize(0);
            Printer.setFontBold(0);
            if (i == 2) {
                Printer.printString(" [" + BetManager.getInstance().getTimes() + "倍]");
            }
            Printer.lineFeed(1);
        }
    }

    private static void printBase(String bet) {
        Printer.setFontSize(16);
        Printer.setFontBold(1);//1 加粗
        String[] nums = bet.split("-");
        String[] numDan = nums[0].split("\\|");
        String[] numTuo = nums[1].split("\\|");
        StringBuilder sb = new StringBuilder();
        for (String dan : numDan) {
            sb.append(dan).append("+");
        }
        sb.setCharAt(sb.length() - 1, '^');
        for (String tuo : numTuo) {
            sb.append(tuo).append("+");
        }
        sb.setCharAt(sb.length() - 1, ' ');
        Printer.printString(sb.toString());
        Printer.setFontSize(0);
        Printer.setFontBold(0);
        Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
        Printer.lineFeed(1);
    }

    private static void printMulti(String bet) {
        Printer.setFontSize(16);
        Printer.setFontBold(1);//1 加粗
        String[] nums = bet.split("\\|");
        StringBuilder sb = new StringBuilder();
        for (String num : nums) {
            sb.append(num).append("+");
        }
        sb.setCharAt(sb.length() - 1,' ');
        Printer.setFontSize(0);
        Printer.setFontBold(0);
        Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
        Printer.lineFeed(1);
    }

    private static void print3DBetInfo(GameTicket ticket, int playType) {
        String[] betData = ticket.gameBetDataString;
        switch (playType) {
            case PlayTypeID.D3_MULTI:
                print3DMulti(betData[0]);
                break;
            case PlayTypeID.D3_BASE:
            case PlayTypeID.D3_BASE_BOX:
            case PlayTypeID.D3_BASE_BOX3:
            case PlayTypeID.D3_BASE_BOX6:
                printBase(betData[0]);
                break;
            case PlayTypeID.D3_MULTI_BOX3:
            case PlayTypeID.D3_MULTI_BOX6:
            case PlayTypeID.D3_MULTI_STRAIGHT_BOX3:
            case PlayTypeID.D3_MULTI_STRAIGHT_BOX6:
            case PlayTypeID.D3_STRING:
            case PlayTypeID.D3_STRAIGHT_BASE:
                printMulti(betData[0]);
                break;
            default:
                for (int i = 0; i < ticket.mBets; i++) {
                    Printer.printString(betNums[i] + " ");
                    Printer.setFontSize(16);
                    Printer.setFontBold(1);//1 加粗
                    String[] nums = betData[i].split("\\|");
                    StringBuilder sb = new StringBuilder();
                    switch (playType) {
                        case PlayTypeID.D3_GUESS_BS:
                        case PlayTypeID.D3_GUESS_OE:
                            for (String num : nums) {
                                if (num.equals("1")) {
                                    sb.append("小").append(" ");
                                } else if(num.equals("2")){
                                    sb.append("大").append(" ");
                                } else if (num.equals("4")) {
                                    sb.append("偶").append(" ");
                                } else if (num.equals("5")) {
                                    sb.append("奇").append(" ");
                                }
                            }
                            break;
                        case PlayTypeID.D3_1D:
                        case PlayTypeID.D3_2D:
                            for (String num : nums) {
                                sb.append("255".equals(num) ? "-" : num).append(" ");
                            }
                            break;
                        case PlayTypeID.D3_ZHIXUAN_BIT_MULTI:
                            for (String num : nums) {
                                sb.append("255".equals(num) ? "*" : num).append(" ");
                            }
                            break;
                        case PlayTypeID.D3_GUESS_3SAME:
                            sb.append("三同号").append(" ");
                            break;
                        case PlayTypeID.D3_TRACTOR:
                            sb.append("拖拉机").append(" ");
                            break;
                        case PlayTypeID.D3_STRAIGHT_ALL_BOX3:
                            sb.append("- - -").append(" ");
                            break;
                        case PlayTypeID.D3_DIFFERENCE:
                            sb.append("DX-KD:").append("[").append(nums[0]).append("]").append(" ");
                            break;
                        case PlayTypeID.D3_DIFFERENCE_BOX3:
                            sb.append("ZUX3-KD:").append("[").append(nums[0]).append("]").append(" ");
                            break;
                        case PlayTypeID.D3_DIFFERENCE_BOX6:
                            sb.append("ZUX6-KD:").append("[").append(nums[0]).append("]").append(" ");
                            break;
                        default:
                            for (String num : nums) {
                                sb.append(num).append(" ");
                            }
                            break;
                    }
                    Printer.printString(sb.toString());
                    Printer.setFontSize(0);
                    Printer.setFontBold(0);
                    if (i == 0) {
                        Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
                    }
                    Printer.lineFeed(1);
                }
                break;
        }
    }

    private static void printK3BetInfo(GameTicket ticket, int playType){
        String[] betData = ticket.gameBetDataString;
        switch (playType) {
            case PlayTypeID.K3_SINGLE:
            case PlayTypeID.K3_3NUMBER_SINGLE:
            case PlayTypeID.K3_2NUMBER_MULTI:
            case PlayTypeID.K3_2NUMBER_SINGLE:
            case PlayTypeID.K3_3NUMBER_DIFF:
            case PlayTypeID.K3_SUM:
            case PlayTypeID.K3_2NUMBER_DIFF:
                for (int i = 0; i < ticket.mBets; i++) {
                    Printer.printString(betNums[i] + " ");
                    Printer.setFontSize(16);
                    Printer.setFontBold(1);//1 加粗
                    String[] nums = betData[i].split("\\|");
                    StringBuilder sb = new StringBuilder();
                    for (String num : nums) {
                        sb.append(num.equals("255") ? "*" : num).append(" ");
                    }
                    Printer.printString(sb.toString());
                    Printer.setFontSize(0);
                    Printer.setFontBold(0);
                    if (i == 0) {
                        Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
                    }
                    Printer.lineFeed(1);
                }
                break;
            case PlayTypeID.K3_3NUMBER_ALL:
                Printer.setFontSize(16);
                Printer.setFontBold(1);//1 加粗
                Printer.printString("三同号通选 ");
                Printer.setFontSize(0);
                Printer.setFontBold(0);
                Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
                Printer.lineFeed(1);
                break;
            case PlayTypeID.K3_3NUMBER_SERIAL:
                Printer.setFontSize(16);
                Printer.setFontBold(1);//1 加粗
                Printer.printString("三连号通选 ");
                Printer.setFontSize(0);
                Printer.setFontBold(0);
                Printer.printString("[" + BetManager.getInstance().getTimes() + "倍]");
                Printer.lineFeed(1);
                break;
        }
    }

    /**
     * 打印冲正单
     * @param context   Context
     * @param ticket    GameTicket
     * @return  boolean
     */
    public static boolean printRevertTicket(Context context, GameTicket ticket) {
        open(context);
        //打印冲正单
        Printer.setLeftMargin(30);
        Printer.setFontBold(1);
        Printer.setFontSize(17);//00010001 高四位表示宽度,低四位表示高度
        String str = "==冲正单==";
        Printer.printString(str);
        Printer.lineFeed(3);
        //打印游戏信息
        Printer.setFontSize(0);
        Printer.printString("---------------------------------");
        Printer.lineFeed(1);
        GameRuntimeAttr attr = GameManager.getGameRuntime(ticket.mGameID);
        assert attr != null;
        str = "游  戏: " + attr.mGameName;
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "站  号: " + ticket.mTerminalID;
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "期  号: " + ticket.mGameIssue;
        Printer.printString(str);
        Printer.lineFeed(1);
        str = "流水号: " + ticket.mTicketSN;
        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);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss", Locale.getDefault());
        long timeStamp = System.currentTimeMillis();
        String dateInfo = sdf.format(new Date(timeStamp));
        str = "冲正时间: " + dateInfo;
        Printer.printString(str);
        Printer.lineFeed(1);

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

}
