package com.cisdi.data.DIClient.gateway;

import com.alibaba.fastjson.JSON;
import com.cisdi.data.DIClient.bean.DBFieldVo;
import com.cisdi.data.DIClient.bean.DBTableTaskCnfg;
import com.cisdi.data.DIClient.bean.PDIOVo;
import com.cisdi.data.sdk.consts.ServiceName;
import com.cisdi.data.sdk.gateway.base.SocketGatewayBase;
import com.cisdi.data.sdk.gateway.message.SocketMessage;
import com.cisdi.data.sdk.service.DynamicCodecService;
import com.cisdi.data.sdk.service.SendService;
import com.cisdi.data.sdk.service.ServiceProvider;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DBTask extends Thread {

    Logger logger= LoggerFactory.getLogger(DBTask.class);
    private ServiceProvider serviceProvider;
    private SocketGatewayBase socketGateway;
    private DBReader dbReader;
    private Long cycleTime;
    private boolean shouldRun;
    private String deviceId;
    private long lastTime=0;
    private int lastNo=0;
    public DBTask(ServiceProvider serviceProvider, SocketGatewayBase socketGateway, DBReader dbReader,Long cycleTime,String deviceId) {
        this.serviceProvider = serviceProvider;
        this.socketGateway = socketGateway;
        this.dbReader = dbReader;
        this.cycleTime=cycleTime;
        shouldRun=true;
        this.deviceId=deviceId;
    }

    public boolean close() throws SQLException {
        dbReader.close();
        shouldRun=false;
        return true;
    }

    public void sendMessage(PDIOVo pdioVo)
    {
        dbReader.addPDIOs(pdioVo);
    }

    @Override
    public void run() {
        while (shouldRun)
        {
            long startTime=System.currentTimeMillis();
            while(true)
            {
                int total=dbReader.getTotal();
                List<PDIOVo> pdioVoList=dbReader.getPDIOs(2000);
                if(pdioVoList!=null&&pdioVoList.size()>0)
                {
                    List<PDIOVo> successList=new ArrayList<>();
                    List<PDIOVo> errorList=new ArrayList<>();
                    String error="";
                    if(serviceProvider==null||socketGateway==null)
                    {
                        for(PDIOVo pdioVo:pdioVoList)
                        {
                            sendMessage(pdioVo);
                            System.out.println(JSON.toJSONString(pdioVo));
                        }
                    }
                    else
                    {
                        SendService service = (SendService)serviceProvider.getByName(ServiceName.Send);
                        DynamicCodecService dynamicCodecService=(DynamicCodecService)serviceProvider.getByName(ServiceName.DynamicCodec);
                        for(PDIOVo pdioVo:pdioVoList)
                        {
                            try
                            {
                                String paramObj = dynamicCodecService.findByRunIdAndMsgKey(socketGateway.getInstanceVo().getRunId(), pdioVo.getQueueId());
                                if(StringUtils.isBlank(paramObj))
                                {
                                    continue;
                                }
                            }
                            catch (Exception e)
                            {
                                continue;
                            }
                            try
                            {

                                SocketMessage socketMessage = socketGateway.buildSocketMessage();
                                socketMessage.setDeviceId(this.deviceId);
                                socketMessage.setMsgKey(pdioVo.getQueueId());
                                socketMessage.setData(pdioVo.getData().getBytes("GBK"));
                                socketMessage.getPropsMap().put("charset",  Charset.forName("GBK"));
                                service.sendMessage(socketMessage);
                                successList.add(pdioVo);
                            }
                            catch (Exception e)
                            {
                                pdioVo.setDescription(e.getLocalizedMessage());
                                errorList.add(pdioVo);
                                error=e.getLocalizedMessage();
                            }
                        }
                        if(errorList.size() > 0)
                        {
                            dbReader.updateStatus(errorList,'E',error);
                        }
                        if(successList.size() > 0)
                        {
                            dbReader.updateStatus(successList,'O',"");
                        }
                    }
                }
                if(pdioVoList.size()==0||pdioVoList.size()==total)
                {
                    break;
                }
            }
            long endTime=System.currentTimeMillis();
            try {
                if(endTime-startTime<=cycleTime)
                {
                    Thread.sleep(cycleTime-(endTime-startTime));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
