package co.dc.aptiv.mina;

import co.dc.aptiv.AptivApp;
import co.dc.aptiv.pojo.MaterielPojo;
import co.dc.aptiv.service.BillService;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 一道采集逻辑处理类
 *
 * @author mx
 */
public class TestMachineCollectorMinaHandler extends MinaAbstractHandler {

    private static final Log log = LogFactory.getLog(TestMachineCollectorMinaHandler.class);

    public TestMachineCollectorMinaHandler(TestMachineCollectorMina collectorMina, QueryRunner queryRunner) {
        super(collectorMina, queryRunner);
    }

    private BillService billService;


    public TestMachineCollectorMinaHandler(MinaAbstract mina, QueryRunner queryRunner, BillService billService) {
        super(mina, queryRunner);
        this.billService = billService;
    }


    /**
     * 处理收到的信息
     */
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        IoBuffer in = (IoBuffer) message;
        byte[] bytes = new byte[in.remaining()];
        in.get(bytes, 0, in.remaining());
        String s = Integer.toHexString(bytes[0]);
        if (s != null) {
            String dpn = AptivApp.ccu.HexString2String(bytes);
            if (AptivApp.qrcodeService.getScanFrame().onLine) {
                MaterielPojo materielPojo = AptivApp.materielService.findByDPN(dpn);
                //判断物料是否存在
                if (materielPojo != null) {
                    log.info("测试机发来的物料,DPN = " + dpn);
                    //判断当前是否可打印模式
//                    if (AptivApp.printStatus) {
                        AptivApp.nowMaterielPojo = materielPojo;
                        AptivApp.qrcodeService.getScanFrame().setComboBox_1();
                        int codeFlag = AptivApp.qrcodeService.sendQrCode();
                        if (codeFlag != 1) {
                            log.info("发送码给激光机异常");
                            AptivApp.qrcodeService.getScanFrame().alertMsg(1, "生产码异常，请停止打印并联系管理员！");
                        }
//                    }
                } else {
                    //弹出提示信息
                    AptivApp.qrcodeService.getScanFrame().alertMsg(1, "测试机发来的物料不存在，请检查测试机或物料！");
                    log.info("测试机发来的物料不存在,DPN = " + dpn);
                }
                //给测试机回复收到物料号
                Thread.sleep(100);
                AptivApp.testMachineCollectorMina.sendByte(AptivApp.ccu.String2ASCII("ok"));
            }
        }
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
}
