package com.hw.mes.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.hw.common.core.constant.MesConstants;
import com.hw.common.core.constant.SecurityConstants;
import com.hw.common.core.domain.R;
import com.hw.common.core.exception.ServiceException;
import com.hw.common.core.utils.DateUtils;
import com.hw.common.core.utils.StringUtils;
import com.hw.common.core.utils.uuid.Seq;
import com.hw.common.security.utils.SecurityUtils;
import com.hw.mes.api.domain.MesBaseBarcodeInfo;
import com.hw.mes.domain.vo.MesBindBarcodeVo;
import com.hw.printer.api.RemotePrinterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hw.mes.mapper.MesBaseBarcodeInfoMapper;
import com.hw.mes.service.IMesBaseBarcodeInfoService;

/**
 * 条码信息Service业务层处理
 *
 * @author xs
 * @date 2023-12-20
 */
@Service
public class MesBaseBarcodeInfoServiceImpl implements IMesBaseBarcodeInfoService {
    @Autowired
    private MesBaseBarcodeInfoMapper mesBaseBarcodeInfoMapper;

    @Autowired
    private RemotePrinterService remotePrinterService;

    /**
     * 查询条码信息
     *
     * @param barcodeInfo 条码信息UID
     * @return 条码信息
     */
    @Override
    public MesBaseBarcodeInfo selectMesBaseBarcodeInfoByBarcodeInfo(String barcodeInfo) {
        return mesBaseBarcodeInfoMapper.selectMesBaseBarcodeInfoByBarcodeInfo(barcodeInfo);
    }


    /**
     * 查询条码信息
     *
     * @param barcodeId 条码信息主键
     * @return 条码信息
     */
    @Override
    public MesBaseBarcodeInfo selectMesBaseBarcodeInfoByBarcodeId(Long barcodeId) {
        return mesBaseBarcodeInfoMapper.selectMesBaseBarcodeInfoByBarcodeId(barcodeId);
    }

    /**
     * 查询条码信息列表
     *
     * @param mesBaseBarcodeInfo 条码信息
     * @return 条码信息
     */
    @Override
    public List<MesBaseBarcodeInfo> selectMesBaseBarcodeInfoList(MesBaseBarcodeInfo mesBaseBarcodeInfo) {
        return mesBaseBarcodeInfoMapper.selectMesBaseBarcodeInfoList(mesBaseBarcodeInfo);
    }

    /**
     * 新增条码信息
     * barcode_type '条码类型（1=原材料,2=半成品,3=成品,4=背板）'
     *
     * @param mesBaseBarcodeInfo 条码信息
     * @return 结果
     */
    @Override
    public int insertMesBaseBarcodeInfo(MesBaseBarcodeInfo mesBaseBarcodeInfo) {
        mesBaseBarcodeInfo.setCreateTime(DateUtils.getNowDate());
        // 生成原材料条码
        if (mesBaseBarcodeInfo.getBarcodeType().equals(MesConstants.MES_BARCODE_TYPE_RAW)) {
            //同一批次的批次代码相同
            mesBaseBarcodeInfo.setBatchCode(Seq.getId(Seq.mesBatchCodeSeqType, Seq.mesBatchCodeCode));
            if (mesBaseBarcodeInfo.getBatchFlag().equals(MesConstants.NOT_IS_BATCH)) {
                int frequency = mesBaseBarcodeInfo.getAmount().intValue();
                for (int i = 0; i < frequency; i++) {
                    // 生成数量条的不同条码内容
                    mesBaseBarcodeInfo.setBarcodeInfo(Seq.getId(Seq.mesBarcodeSeqType, Seq.mesBarcodeCode));
                    mesBaseBarcodeInfo.setAmount(new BigDecimal(1));
                    mesBaseBarcodeInfoMapper.insertMesBaseBarcodeInfo(mesBaseBarcodeInfo);
                }
            }
            if (mesBaseBarcodeInfo.getBatchFlag().equals(MesConstants.IS_BATCH)) {
                mesBaseBarcodeInfo.setBarcodeInfo(Seq.getId(Seq.mesBarcodeSeqType, Seq.mesBarcodeCode));
                mesBaseBarcodeInfoMapper.insertMesBaseBarcodeInfo(mesBaseBarcodeInfo);
            }
        }
        // 生成成品条码
        if (mesBaseBarcodeInfo.getBarcodeType().equals(MesConstants.MES_BARCODE_TYPE_PRODUCT)) {
            // 批次代码 == 条码内容
            int frequency = mesBaseBarcodeInfo.getAmount().intValue();
            for (int i = 0; i < frequency; i++) {
                String code = Seq.getId(Seq.mesCompBarcodeSeqType, Seq.mesCompBarcodeCode);
                mesBaseBarcodeInfo.setBatchCode(code);
                mesBaseBarcodeInfo.setBarcodeInfo(code);
                mesBaseBarcodeInfo.setAmount(new BigDecimal(1));
                mesBaseBarcodeInfoMapper.insertMesBaseBarcodeInfo(mesBaseBarcodeInfo);
            }
        }
        return 1;
    }

    /**
     * 修改条码信息
     *
     * @param mesBaseBarcodeInfo 条码信息
     * @return 结果
     */
    @Override
    public int updateMesBaseBarcodeInfo(MesBaseBarcodeInfo mesBaseBarcodeInfo) {
        mesBaseBarcodeInfo.setUpdateBy(SecurityUtils.getUsername());
        mesBaseBarcodeInfo.setUpdateTime(DateUtils.getNowDate());
        return mesBaseBarcodeInfoMapper.updateMesBaseBarcodeInfo(mesBaseBarcodeInfo);
    }

    /**
     * 批量删除条码信息
     *
     * @param barcodeIds 需要删除的条码信息主键
     * @return 结果
     */
    @Override
    public int deleteMesBaseBarcodeInfoByBarcodeIds(Long[] barcodeIds) {
        return mesBaseBarcodeInfoMapper.deleteMesBaseBarcodeInfoByBarcodeIds(barcodeIds);
    }

    /**
     * 删除条码信息信息
     *
     * @param barcodeId 条码信息主键
     * @return 结果
     */
    @Override
    public int deleteMesBaseBarcodeInfoByBarcodeId(Long barcodeId) {
        return mesBaseBarcodeInfoMapper.deleteMesBaseBarcodeInfoByBarcodeId(barcodeId);
    }

    /**
     * 打印条码
     *
     * @param barcodeIds
     * @return
     */
    @Override
    public int printBarCode(Long[] barcodeIds) {
        StringBuilder buffer = new StringBuilder();
        //获取条码List
        for (Long barcodeId : barcodeIds) {
            MesBaseBarcodeInfo mesBaseBarcodeInfo = mesBaseBarcodeInfoMapper.selectMesBaseBarcodeInfoByBarcodeId(barcodeId);
            try {
                //调用的打印接口
                MesBaseBarcodeInfo barCodeInfo = remotePrinterService.printBarCode(mesBaseBarcodeInfo, SecurityConstants.INNER);
                MesBaseBarcodeInfo baseBarcodeInfo = new MesBaseBarcodeInfo();
                baseBarcodeInfo.setBarcodeId(barcodeId);
                baseBarcodeInfo.setMachineName(barCodeInfo.getMachineName());
                baseBarcodeInfo.setPrintTime(DateUtils.getNowDate());
                baseBarcodeInfo.setPrintPerson(SecurityUtils.getUsername());
                baseBarcodeInfo.setPrintFlag("1");
                baseBarcodeInfo.setPrintNumber(StringUtils.isNull(baseBarcodeInfo.getPrintNumber()) ? 1 : baseBarcodeInfo.getPrintNumber() + 1);
                baseBarcodeInfo.setAcceptedDate(DateUtils.getNowDate());
                this.updateMesBaseBarcodeInfo(baseBarcodeInfo);
            } catch (Exception e) {
                buffer.append("打印条码报错——条码内容：").append(mesBaseBarcodeInfo.getBarcodeInfo()).append(e.getMessage());
            }
        }
        if (buffer.length() == 0) {
            return 1;
        } else {
            throw new ServiceException(buffer.toString());
        }
    }


    /**
     * 绑定条码信息(适用于五楼柜体拆分区)
     *
     * @param mesBindBarcodeVo
     * @return
     */
    @Override
    public int bindBarcode(MesBindBarcodeVo mesBindBarcodeVo) {
        String productBarcode = mesBindBarcodeVo.getProductBarcode();
        String materialBarcode = mesBindBarcodeVo.getMaterialBarcode();
        String planCode = mesBindBarcodeVo.getPlanCode();
        String planDetailCode = mesBindBarcodeVo.getPlanDetailCode();

        MesBaseBarcodeInfo productBarcodeInfo = mesBaseBarcodeInfoMapper
                .selectMesBaseBarcodeInfoByBarcodeInfo(productBarcode);
        if (productBarcodeInfo == null) {
            throw new ServiceException("成品条码有误");
        }

        if (productBarcodeInfo.getBarcodeType().equals(MesConstants.MES_BARCODE_TYPE_RAW)) {
            throw new ServiceException("物料条码有误");
        }

        if (!productBarcodeInfo.getPlanCode().equals(planCode)) {
            throw new ServiceException("绑定不匹配，此成品条码工单编号为:" + productBarcodeInfo.getPlanCode());
        }

        if (StringUtils.isNotEmpty(productBarcodeInfo.getBindBarcode())) {
            throw new ServiceException("此成品条码已经绑定，无需重复绑定");
        }

        MesBaseBarcodeInfo materialBarcodeInfo = mesBaseBarcodeInfoMapper
                .selectMesBaseBarcodeInfoByBarcodeInfo(materialBarcode);
        if (materialBarcodeInfo == null ||
                !materialBarcodeInfo.getBarcodeType().equals(MesConstants.MES_BARCODE_TYPE_RAW)) {
            throw new ServiceException("物料条码有误");
        }

        productBarcodeInfo.setBindBarcode(materialBarcode);
        productBarcodeInfo.setBindBy(SecurityUtils.getUsername());
        productBarcodeInfo.setBindTime(new Date());
        productBarcodeInfo.setBindStatus(MesConstants.MES_BARCODE_BIND_STATUS_BINDING);
        productBarcodeInfo.setPlanDetailCode(planDetailCode);
        return mesBaseBarcodeInfoMapper.updateMesBaseBarcodeInfo(productBarcodeInfo);
    }






    /**
     * 查询条码信息
     *
     * @param bindBarcode 绑定条码信息
     * @return 条码信息
     */
    @Override
    public MesBaseBarcodeInfo selectMesBaseBarcodeInfoByBindBarcode(String bindBarcode) {
        return mesBaseBarcodeInfoMapper.selectMesBaseBarcodeInfoByBindBarcode(bindBarcode);
    }
}
