package co.dc.aptiv.service;

import co.dc.aptiv.AptivApp;
import co.dc.commons.basedao.CommonBaseDao;
import co.dc.commons.utils.DateTimeUtil;
import co.dc.aptiv.ScanFrame;
import co.dc.aptiv.pojo.BillDetailPojo;
import co.dc.aptiv.pojo.MaterielPojo;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @describe: 二维码生成
 * @author: liuxinglong
 * @version: 2018/4/18 19:50
 */
@Service("qrCodesService")
public class QrCodeService {
    private ScanFrame scanFrame;
    private static final Log log = LogFactory.getLog(QrCodeService.class);
    @Resource(name = "commonBaseDao")
    private CommonBaseDao baseDao;
    protected String createDateTime = null;


    /**
     * 根据物料Id生成二维码
     *
     * @param materielId 物料Id
     * @return QR Code
     */
    public String generateQRCode(Long materielId) {
        createDateTime = DateTimeUtil.getDateTimeString();
        //当前日期
        String nowDate = createDateTime.substring(0, 10);
        //物料最后生产日期
        String lastDate = AptivApp.billDetailService.getLastDate(materielId);
        MaterielPojo materielPojo = AptivApp.materielService.findById(materielId);
        if (materielPojo == null) {
            return null;
        }
        /*lastDate == null || (nowDate - lastDate > 0)  = 重置计数*/
        if (lastDate == null || (DateTimeUtil.compareDay(nowDate, lastDate) > 0)) {
            //重置计数
            materielPojo.setMaxNum(1);
            AptivApp.materielService.updateMaterielpojo(materielPojo);
        }
        //每天计数不能超过9999
        if (materielPojo.getMaxNum() > 9999) {
            return null;
        }
        String maxNum = materielPojo.getMaxNum() + "";
        //最大序号进行补位
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4 - maxNum.length(); i++) {
            sb.append("0");
        }
        maxNum = sb.toString() + maxNum;
        //物料编号+生产日期+(补位+最大序号）
        return materielPojo.getCpn() + " " + nowDate.replace("-", "").substring(2, 8) + maxNum;
    }


    /**
     * 将码发送到激光机
     */
    public int sendQrCode() {
        if (AptivApp.flag == 1 && AptivApp.printStatus) {
            AptivApp.printStatus = false;
            String code = generateQRCode(AptivApp.nowMaterielPojo.getId());
            if (code == null) {
                return 2;
            }
            AptivApp.qrCode = code;
            getScanFrame().loadCode();
            //获取码并发送到激光机
            int status = AptivApp.printMina.sendByte(AptivApp.ccu.String2ASCII(AptivApp.nowMaterielPojo.getCpn() + AptivApp.nowMaterielPojo.getType() + AptivApp.qrCode));
            if (status > 0) {
                AptivApp.scanStatus = true;
                log.info("成功发送码" + AptivApp.qrCode);
                return status;
            }
        }
        return -1;
    }


    /**
     * 从采集器接收码并保存
     *
     * @param str
     */
    public void receiveQrCode(String str) {
        //设置扫描状态为不可扫描
        AptivApp.scanStatus = false;
        //保存详情
        BillDetailPojo bdp = AptivApp.billDetailService.addBillDetail(AptivApp.billPojo.getId(), AptivApp.nowMaterielPojo.getId(), AptivApp.qrCode.trim(), str.trim());
        //不合格返给采集器错误信号
        if (!AptivApp.qrCode.trim().equals(str.trim())) {
            AptivApp.collectorMina.sendByte(AptivApp.ccu.String2ASCII("E"));
        }
        getScanFrame().loadjtable1(bdp);

        //更新物料序号
        AptivApp.materielService.updateMaterielpojoMaxNum(AptivApp.nowMaterielPojo.getId());

        //更新单据统计数据
        AptivApp.billService.updateBillStatistics(AptivApp.billPojo.getId(), str);

        //设置打印状态为可打印
        AptivApp.printStatus = true;
        log.info("成功保存码 " + str);

        //打印状态且非联机模式，重新发码
        if (AptivApp.flag == 1 && !getScanFrame().onLine) {
            int codeFlag = sendQrCode();
            if (codeFlag > 1) {
                getScanFrame().alertMsg(1, "生产码异常，请停止打印并联系管理员！");
            }
            if (codeFlag < 0) {
                //此处如果打印不成功
            }
        }
    }

    /**
     * 统计当前日期打印总数
     *
     * @return
     */
    public Map<String, Object> countDayData() {
        String date = DateTimeUtil.getDateString();
        Map<String, Object> map = new HashMap<String, Object>(3);
        try {
            String sql = "SELECT SUM(number),sum(qualifiedNum),sum(UnqualifiedNum) FROM bill WHERE createTime BETWEEN '" + date + " 00:00:00' AND '" + date + " 23:59:59';";
            map = baseDao.query(sql, new MapHandler());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return map;
    }


    public ScanFrame getScanFrame() {
        return scanFrame;
    }

    public void setScanFrame(ScanFrame scanFrame) {
        this.scanFrame = scanFrame;
    }

    /**
     * 检查重码
     *
     * @return
     */
    public boolean checkReCode(String str) {
        //采到的码去找当前订单详情
        BillDetailPojo billDetailPojo = baseDao.findByParam(BillDetailPojo.class, "qrCode", str.trim());
        //判断当前模式，0点检，1打印
        if (AptivApp.flag == 0) {
            /*
                判断是不是我们产的码
                不是我们产的码返给采集器错误信号
                是我们生产的那肯定是重码
            */
            if (billDetailPojo == null) {
                AptivApp.collectorMina.sendByte(AptivApp.ccu.String2ASCII("E"));
                getScanFrame().alertMsg(1, "检测到不是我们生产的码！");
                return false;
            } else {
                AptivApp.collectorMina.sendByte(AptivApp.ccu.String2ASCII("E"));
                getScanFrame().alertMsg(1, "检测到重码！");
                return false;
            }
        } else {
            //当前订单详情不等于空，那就是有重码了
            if (billDetailPojo != null) {
                //重码时反给采集器错误信号
                AptivApp.collectorMina.sendByte(AptivApp.ccu.String2ASCII("E"));
                //设置打印状态为可打印
                AptivApp.printStatus = true;
                if (!getScanFrame().onLine) {
                    sendQrCode();
                }
                log.info("捕获到重码： " + str);
                return false;
            }
        }
        return true;
    }

}
