package com.cim.idm.service.Impl;

import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.model.*;
import com.cim.idm.model.dto.StoragePrintDto;
import com.cim.idm.service.LabelService;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


/**
 * @author 10486880
 * @version 1.0
 * @description LabelServiceImpl
 * @date 2024/4/19 11:16
 */
@Service("labelService")
public class LabelServiceImpl implements LabelService {

    @Resource
    private BSLabelServiceImpl bsLabelService;


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

    @Override
    public void labelAction(LabelDto data) {
        EventInfo eventInfo = EventInfoUtil.makeEventInfo("LabelCreate", data.getUser(),"LabelAction");
        //bsLabelService.labelAction(data, eventInfo);
    }

    @Override
    public void labelAssignFGCodeAction(LabelAssignFGCodeDto data) {
       // bsLabelService.labelAssignFGCodeAction(data);
    }

    @Override
    public void labelAssignParameterAction(LabelAssignParameterDto data) {
//        EventInfo eventInfo = EventInfoUtil.makeEventInfo("labelAssignParameterAction",data.getUser(),
//        		"labelAssignParameterAction");
//        bsLabelService.labelAssignParameter(data, eventInfo);
    }

    @Override
    public String labelPrintTest(LabelPrintDto data) throws CustomException {
        String urlFull = "";
    	try {
            urlFull = bsLabelService.rePrintArriveMaterial(data.getLotName(),data.getOpreater(),data.getPrinterName());
        } catch (Exception e) {
        	e.printStackTrace();
            throw new CustomException(  "标签打印异常... " + e.getMessage());
        }
        return urlFull;
    }

    @Override
    public String storagePrint(StoragePrintDto data) throws CustomException {
        String urlFull = "";
        try {
            urlFull = bsLabelService.storagePrint(data);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(  "标签打印异常... " + e.getMessage());
        }
        return urlFull;
    }
    
    @Override
    public void labelPrintTest1(LabelPrintDto1 data) throws CustomException {
        try {
            bsLabelService.rePrintArriveMaterial1(data.getLotName(),data.getOpreater(),data.getPrinterName(),data.getDESC_CN(),data.getLabelType());
        } catch (Exception e) {
        	e.printStackTrace();
            throw new CustomException(  "标签打印异常... " + e.getMessage());
        }
    }
    
    @Override
    public void labelPrintTest2(LabelPrintDto2 data) throws CustomException {
        try {
            bsLabelService.rePrintArriveMaterial2(data.getLotName(),data.getOpreater(),data.getPrinterName(),data.getQty());
        } catch (Exception e) {
        	e.printStackTrace();
            throw new CustomException(  "标签打印异常... " + e.getMessage());
        }
    }
    
    @Override
    public String labelPrintTest3(LabelPrintDto1 data) throws CustomException {
    	String urlFull = "";
    	try {
    		urlFull = bsLabelService.rePrintArriveMaterial3(data.getLotName(),data.getOpreater(),data.getPrinterName(),data.getDESC_CN(),data.getLabelType());
        } catch (Exception e) {
        	e.printStackTrace();
            throw new CustomException(  "标签打印异常... " + e.getMessage());
        }
    	return urlFull;
    }

    @Override
    public void labelPrint(LabelPrintDto data) {
//        try {
//            bsLabelService.labelPrint(data);
//        } catch (Exception e) {
//            throw new CustomException(  "标签打印异常... " + e.getMessage());
//        }
    }

    @Override
    public void batchLabelPrint(LabelPrintBatchDto data) throws IllegalArgumentException {
//        try {
//            bsLabelService.batchLabelPrint(data);
//        } catch (Exception e) {
//            throw new CustomException( "标签打印异常... " + e.getMessage());
//        }
    }

    @Override
    public void labelParameterAction(LabelParameterDto data) {
//        // 数据校验
//        if (data == null || StringUtils.isBlank(data.getActionType())
//                || StringUtils.isBlank(data.getParameterName())) {
//            throw new IllegalArgumentException("Data or actionType or parameterName is null or blank.");
//        }
//
//        String actionType = data.getActionType();
//        Map<String, String> bindMap = new HashMap<>();
//        bindMap.put(MessageTag.ENUMNAME, "LabelParameter");
//        bindMap.put(MessageTag.ENUMVALUE, data.getParameterName());
//        bindMap.put(MessageTag.DESCRIPTION, data.getDescription());
//
//        // 使用策略模式执行不同的操作
//        switch (actionType) {
//            case PolicyDef.Action_Create:
//                IDMFrameServiceProxy.getSqlTemplate().update(SqlStatement.INSERT_ENUMVALUE, bindMap);
//                log.info("Successfully inserted enum value: {}" + data.getParameterName());
//                break;
//            case PolicyDef.Action_Delete:
//                IDMFrameServiceProxy.getSqlTemplate().update(SqlStatement.DELETE_ENUMVALUE, bindMap);
//                log.info("Successfully deleted enum value: {}" + data.getParameterName());
//                break;
//            default:
//                log.warn("Unsupported actionType: {}" + actionType);
//                throw new IllegalArgumentException("Unsupported actionType: " + actionType);
//        }
    }

	@Override
	public void saveLabelPrintInfo(LabelPrintInfoDto data) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		
	}


	
	public static void main(String[] args) {
		new LabelServiceImpl().saveLabelPrintInfo(null);
	}
	/**
	 * 保存打印数据
	 * @param data
	 * @throws IllegalArgumentException
	 */
    //@Override
    @Transactional
    public void savePrintData(List<NcDataDto> data) throws IllegalArgumentException {
        String url = "jdbc:sqlserver://192.168.1.35:1433;databaseName=Kgm_SdkNcDb";
        String user = "kgm";
        String pwd = "kgm123!@#";
        String conTime = "";
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Long id = null;
        try {
            // 1.获取开始时间
            long startTime = System.currentTimeMillis();

            // 2. 建立数据库连接
            connection = DriverManager.getConnection(url, user, pwd);
            ps = null;

            System.out.println("数据库连接成功");

            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            String formattedDate = now.format(formatter);

            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMddHHmmssfff");
            String formattedDate1 = now.format(formatter1);

            for (NcDataDto dto : data) {
                String barCode = dto.getMaterialCode() + "|"+ dto.getMaterialVersion() +"|" + dto.getStageCode() + "|" +
                        dto.getSdkSpecifications() + "|" + dto.getBatch()+ "|" + formattedDate + "|" + dto.getMainUoc()+ "|" + dto.getAssistQty();
                dto.setBarcode(barCode);
                dto.setPrintBatch(dto.getOperator() + "_" + formattedDate1);
                // 3.通过传输器发送SQL到服务器执行并且返回执行结果
                String sql = "SELECT id FROM Wms_Record_PrintTemplate where Barcode=?";
                ps = connection.prepareStatement(sql);
                ps.setString(1, dto.getBarcode());
                //执行查询，返回结果集
                rs = ps.executeQuery();
                // 4.数据处理
                if (!rs.next()) {
                    sql = "INSERT INTO Kgm_SdkNcDb.dbo.Wms_Record_PrintTemplate " +
                            "(PrintBatch, Barcode, PrintType, SourcTtype, SourceOrder, SourceOrderId, SourceAutoid, OrgCode, MaterialId, MaterialCode, StageId, StageCode, WorkPlant, WorkShop, WorkShift, Machine, VolNumber, SupCode, CustomerCode, SupBarcode, CusBarcode, MaterialName, Specifications, SDKSpecificationsId, SDKSpecifications, Batch, JumboRollBatch, BatchDate, PrintBatchDate, ProductDate, ExpiryDate, MainUom, MainQty, AssistUom, AssistQty, PracticalSpec, PrintQty, PrintDate, Operator, Salesman, Remarks, DefineItem1, DefineItem2, DefineItem3, DefineItem4, DefineItem5, DefineItem6, DefineItem7, DefineItem8, DefineItem9, DefineItem10, DefineItem11, DefineItem12, DefineItem13, DefineItem14, DefineItem15, DefineItem16, DefineItem17, DefineItem18, DefineItem19, DefineItem20, CreatedTime, UpdatedTime, CreatedUserId, CreatedUserName, UpdatedUserId, UpdatedUserName, IsDeleted, TenantId, MaterialVersion, Piece, IsSame) " +
                            "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\n";//主键需要自动增长
                } else {
                    id = rs.getLong("Id");
                    sql = "UPDATE Kgm_SdkNcDb.dbo.Wms_Record_PrintTemplate " +
                            "SET PrintBatch=?, barcode=?, PrintType=?, SourcTtype=?, SourceOrder=?, SourceOrderId=?, SourceAutoid=?, OrgCode=?, MaterialId=?, MaterialCode=?, StageId=?, StageCode=?, WorkPlant=?, WorkShop=?, WorkShift=?, Machine=?, VolNumber=?, SupCode=?, CustomerCode=?, SupBarcode=?, CusBarcode=?, MaterialName=?, Specifications=?, SDKSpecificationsId=?, SDKSpecifications=?, Batch=?, JumboRollBatch=?, BatchDate=?, PrintBatchDate=?, ProductDate=?, ExpiryDate=?, MainUom=?, MainQty=?, AssistUom=?, AssistQty=?, PracticalSpec=?, PrintQty=?, PrintDate=?, Operator=?, Salesman=?, Remarks=?, DefineItem1=?, DefineItem2=?, DefineItem3=?, DefineItem4=?, DefineItem5=?, DefineItem6=?, DefineItem7=?, DefineItem8=?, DefineItem9=?, DefineItem10=?, DefineItem11=?, DefineItem12=?, DefineItem13=?, DefineItem14=?, DefineItem15=?, DefineItem16=?, DefineItem17=?, DefineItem18=?, DefineItem19=?, DefineItem20=?, CreatedTime=?, UpdatedTime=?, CreatedUserId=?, CreatedUserName=?, UpdatedUserId=?, UpdatedUserName=?, IsDeleted=?, TenantId=?, MaterialVersion=?, Piece=?, IsSame=? " +
                            "WHERE Id = ?;";

                }
                insertOrUpdate(connection, sql, dto, id);
            }
            // 6. 获取结束时间，并计算连接数据库，执行SQL语句时间
            long endTime = System.currentTimeMillis(); //获取结束时间
            conTime = "程序运行时间：" + (endTime - startTime) + "ms";
            System.out.println(conTime); //输出程序运行时间

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放连接资源
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void insertOrUpdate(Connection conn, String sql, NcDataDto data, Long id) {
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);

            ps.setString(1, data.getPrintBatch());
            ps.setString(2, data.getBarcode());
            ps.setString(3, data.getPrintType());
            ps.setString(4, data.getSourceType());
            ps.setString(5, data.getSourceOrder());
            ps.setString(6, data.getSourceOrderId());
            ps.setString(7, data.getSourceAutoid());
            ps.setString(8, data.getOrgCode());
            ps.setString(9, data.getMaterialId());
            ps.setString(10, data.getMaterialCode());
            ps.setString(11, data.getStageId());
            ps.setString(12, data.getStageCode());
            ps.setString(13, data.getWorkPlant());
            ps.setString(14, data.getWorkShop());
            ps.setString(15, data.getWorkShift());
            ps.setString(16, data.getMachine());
            ps.setString(17, data.getVolNumber());
            ps.setString(18, data.getSupCode());
            ps.setString(19, data.getCustomerCode());
            ps.setString(20, data.getSupBarcode());
            ps.setString(21, data.getCusBarcode());
            ps.setString(22, data.getMaterialName());
            ps.setString(23, data.getSpecifications());
            ps.setString(24, data.getSdkSpecificationsId());
            ps.setString(25, data.getSdkSpecifications());
            ps.setString(26, data.getBatch());
            ps.setString(27, data.getJumboRollBatch());
            ps.setDate(28, data.getBatchDate());
            ps.setDate(29, data.getPrintBatchDate());
            ps.setDate(30, data.getProductDate());
            ps.setDate(31, data.getExpiryDate());
            ps.setString(32, data.getMainUom());
            ps.setDouble(33, data.getMainQty());
            ps.setString(34, data.getAssistUom());
            ps.setString(35, data.getAssistQty());
            ps.setString(36, data.getPracticalSpec());
            ps.setDouble(37, data.getPrintQty());
            ps.setDate(38, data.getPrintDate());
            ps.setString(39, data.getOperator());
            ps.setString(40, data.getSalesman());
            ps.setString(41, data.getRemarks());
            ps.setString(42, data.getDefineItem1());
            ps.setString(43, data.getDefineItem2());
            ps.setString(44, data.getDefineItem3());
            ps.setString(45, data.getDefineItem4());
            ps.setString(46, data.getDefineItem5());
            ps.setString(47, data.getDefineItem6());
            ps.setString(48, data.getDefineItem7());
            ps.setString(49, data.getDefineItem8());
            ps.setString(50, data.getDefineItem9());
            ps.setString(51, data.getDefineItem10());
            ps.setString(52, data.getDefineItem11());
            ps.setString(53, data.getDefineItem12());
            ps.setString(54, data.getDefineItem13());
            ps.setString(55, data.getDefineItem14());
            ps.setString(56, data.getDefineItem15());
            ps.setString(57, data.getDefineItem16());
            ps.setString(58, data.getDefineItem17());
            ps.setString(59, data.getDefineItem18());
            ps.setString(60, data.getDefineItem19());
            ps.setString(61, data.getDefineItem20());
            ps.setDate(62, data.getCreatedTime());
            ps.setDate(63, data.getUpdatedTime());
            ps.setLong(64, data.getCreatedUserId());
            ps.setString(65, data.getCreatedUserName());
            ps.setLong(66, data.getUpdatedUserId());
            ps.setString(67, data.getUpdatedUserName());
            ps.setBoolean(68, data.getIsDeleted());
            ps.setLong(69, data.getTenantId());
            ps.setString(70, data.getMaterialVersion());
            ps.setInt(71, data.getPiece());
            ps.setString(72, data.getIsSame());
//            ps.setLong(73, id);
            int executeUpdate = ps.executeUpdate();
            System.out.println(executeUpdate);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
