package com.doverfuelingsolutions.issp.driver.printer;


import android.text.TextUtils;

import com.doverfuelingsolutions.issp.api.bean.PayResultHs;
import com.doverfuelingsolutions.issp.api.dto.ResultPayment;
import com.doverfuelingsolutions.issp.data.GlobalData;
import com.doverfuelingsolutions.issp.utils.log.DFSLog;
import com.printsdk.cmd.PrintCmd;
import com.doverfuelingsolutions.issp.driver.scan.ScanValueListener;
import com.doverfuelingsolutions.issp.driver.serialPort.DataReceivedListener;
import com.doverfuelingsolutions.issp.driver.serialPort.SerialControl;
import com.doverfuelingsolutions.issp.driver.serialPort.SerialHelper;
import com.wayne.www.waynelib.fdc.message.DeviceClass;
import com.wayne.www.waynelib.webservice.entity.PosTrxItem;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ComPrintManager implements PrintManager, DataReceivedListener {

    public SerialControl serialControl;
    private int getStatus_flag; // 检查状态1或者状态2
    private boolean isReceived = false;
    private int status_1 = 0;
    private int status_2 = 0;

    private PrintStatusListen printStatusListen;

    public ComPrintManager(String port, int rate, PrintStatusListen psl) throws Exception {
        // serialControl = new SerialControl("/dev/ttyS3", 115200); // 串口号和波特率
        serialControl = new SerialControl(port, rate, this, psl); // 串口号和波特率
        serialControl.setbLoopData(PrintCmd.GetStatus4());
        OpenComPort(serialControl); // 打开串口
    }

    /**
     * 打印最后部分
     */
    private void printEnd() throws Exception {
        if (serialControl == null) return;
        serialControl.send(PrintCmd.PrintChargeRow());
        serialControl.send(PrintCmd.PrintString("感谢您使用，请妥善保管交易凭条", 0));
        serialControl.send(PrintCmd.PrintString("欢迎下次光临", 0));
        serialControl.send(PrintCmd.PrintFeedline(3));
        serialControl.send(PrintCmd.PrintFeedline(3));
        serialControl.send(PrintCmd.PrintCutpaper(1)); // 半切纸
    }

    /**
     * 支付成功后的小票打印
     * TODO LZP备注：新的数据应该拿 payResult 的
     */
    public void printOrderOkBillHs(DeviceClass dc, ResultPayment.PosTrxBean ptb) throws Exception {
        if (serialControl == null) return;
        if (ptb == null || dc == null) return;

        getStatus1();
        serialControl.send(PrintCmd.SetAlignment(1));
        serialControl.send(PrintCmd.PrintString("自助机加油支付小票", 0));
        serialControl.send(PrintCmd.PrintFeedline(2));
        serialControl.send(PrintCmd.SetAlignment(0));
        if (!TextUtils.isEmpty(GlobalData.INSTANCE.getBusinessName().get()))
            serialControl.send(PrintCmd.PrintString("加油站名称：" + GlobalData.INSTANCE.getBusinessName().get(), 0));
        serialControl.send(PrintCmd.SetBold(1));
        serialControl.send(PrintCmd.PrintString("油枪号：" + dc.getNozzleNo() + "号枪", 0));
            serialControl.send(PrintCmd.PrintString("加油金额：" + dc.getMyAmount() + "元", 0));
        serialControl.send(PrintCmd.SetBold(0));
            serialControl.send(PrintCmd.PrintString("优惠金额：" + ptb.getDiscount() + "元", 0));
            serialControl.send(PrintCmd.PrintString("支付金额：" + ptb.getNetAmount() + "元", 0));
        serialControl.send(PrintCmd.PrintString("加油升数：" + dc.getVolume() + "升", 0));
        serialControl.send(PrintCmd.PrintString("油品名称：" + dc.getProductName(), 0));
        if (!ptb.getItems().isEmpty()) {
            PosTrxItem ib = ptb.getItems().get(0);
            if (null != ib.getPosItem()) {
                serialControl.send(PrintCmd.PrintString("油品单价：" + ib.getPosItem().getPrice() + "/升", 0));
            }
            if (ib.isHaveTagId())
                serialControl.send(PrintCmd.PrintString("员工卡号：" + ib.getCardNo(), 0));
        }
//        serialControl.send(PrintCmd.PrintString("加油时间：" + ib.getItem().getCreatedDateTime(), 0));
        serialControl.send(PrintCmd.PrintFeedline(1));
//        serialControl.send(PrintCmd.PrintString("支付方式：" + payResult.getMyPayType(), 0));
//        serialControl.send(PrintCmd.PrintString("订单号：" + ptb.getId(), 0));
//        serialControl.send(PrintCmd.PrintString("支付ID：" + o.getMyId(), 0));
        serialControl.send(PrintCmd.PrintString("支付时间：" + ptb.getTransactionInitTimeInPos(), 0));
        serialControl.send(PrintCmd.PrintFeedline(1));
        serialControl.send(PrintCmd.SetAlignment(1));
        serialControl.send(PrintCmd.PrintString("感谢您使用，请妥善保管交易凭条", 0));
        serialControl.send(PrintCmd.PrintString("欢迎下次光临", 0));
        serialControl.send(PrintCmd.PrintFeedline(3));
        serialControl.send(PrintCmd.PrintFeedline(3));
        serialControl.send(PrintCmd.PrintCutpaper(1)); // 半切纸
        getStatus2Latter(2500);
    }

    @Override
    public void getStatus2() throws Exception {
        status_2 = 0;
        getStatus_flag = PrintStatusContants.GETSTATUS_2;
        isReceived = false;
        if (null != PrintCmd.GetStatus2() && null != serialControl)
            serialControl.send(PrintCmd.GetStatus2());// 获取状态2
//        LogHelper.i(TAG, "getStatus2");
    }

    public void getStatus2Latter(int waittime) {
        Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    getStatus2();
                    checkReceived();
                } catch (Exception e) {
//                    Utils.postException(e);
                    e.printStackTrace();
                }
            }
        }, waittime, TimeUnit.MILLISECONDS);
    }

    public void checkReceived() {
        try {
            Thread.sleep(500);
            if (getStatus_flag == 2 && !isReceived) {
                if (printStatusListen != null) {
                    printStatusListen.receivePrintStatus(PrintStatusContants.ERROR_CONNECT_FAIL);
                }
            }
        } catch (Exception e) {
            DFSLog.Companion.e(e);
        }
    }

    @Override
    public void getStatus1() throws Exception {
        status_1 = 0;
        getStatus_flag = PrintStatusContants.GETSTATUS_1;
        serialControl.send(PrintCmd.GetStatus1()); // 获取状态1
    }

    private void OpenComPort(SerialHelper ComPort) throws Exception {
        try {
            ComPort.open();
        } catch (Exception e) {
            DFSLog.Companion.e(e);
            e.printStackTrace();
//            LogHelper.i(TAG, "failed to open com port");
            throw e;
        }
    }


    @Override
    public void onDataReceived(byte[] data, PrintStatusListen printStatusListen) {
        if (data == null) return;
        if (this.printStatusListen == null)
            this.printStatusListen = printStatusListen;
        switch (getStatus_flag) {
            case PrintStatusContants.GETSTATUS_2:
                isReceived = true;
                if ((data[0] & 0x20) == 0x20) {
                    status_2 = PrintStatusContants.ERROR_STATE2_PRINTINGPAPER_USEDUP; //打印纸用完，停止打
                    if (null != printStatusListen) {
                        printStatusListen.receivePrintStatus(status_2);
                        return;
                    }
                }
                if ((data[0] & 0x40) == 0x40) {
                    status_2 = PrintStatusContants.ERROR_STATE2;//发生错误
                    if (null != printStatusListen) {
                        printStatusListen.receivePrintStatus(status_2);
                        return;
                    }
                }
                if (null != printStatusListen) {
                    //先判断 status_1状态  再判断status_2状态
                    if (status_1 != PrintStatusContants.DEFAULT) {
                        printStatusListen.receivePrintStatus(status_1);
                    } else if (status_2 != PrintStatusContants.DEFAULT) {
                        printStatusListen.receivePrintStatus(status_2);
                    } else {
                        printStatusListen.receivePrintStatus(PrintStatusContants.DEFAULT);
                    }
                }
                break;
            case PrintStatusContants.GETSTATUS_1:
                if ((data[0] & 0x8) == 0x8) {
                    status_1 = PrintStatusContants.ERROR_STATE1_OFFLINE; //脱机
                    if (null != printStatusListen)
                        printStatusListen.receivePrintStatus(status_1);
                }
                break;
        }

    }

    /**
     * @desc 摧毁界面后
     * @info Created by LzPeng on 2020/3/11 9:52
     */
    public void destroy() {
        if (null != printStatusListen) printStatusListen = null;
        if (null != serialControl) {
            serialControl.close();
            serialControl = null;
        }
    }


    @Override
    public void onDataReceived(byte[] data) {

    }

    @Override
    public void onDataReceived(byte[] data, ScanValueListener scanValueListener) {

    }
}
