package com.steerinfo.ems.emswaterrealtime.service.impl;

import com.client.MswebserviceStub;
import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.emswaterrealtime.mapper.EmsWaterRealtimeMapper;
import com.steerinfo.ems.emswaterrealtime.model.EmsWaterRealtime;
import com.steerinfo.ems.emswaterrealtime.service.IEmsWaterRealtimeService;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.ifmesemsswapfile.service.impl.IfMesEmsSwapfileServiceImpl;
import com.steerinfo.ems.trmcalpoint.model.TRmCalpoint;
import com.steerinfo.framework.datasource.DataSourceKey;
import com.steerinfo.framework.datasource.TargetDataSource;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import org.apache.axis2.AxisFault;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.RemoteException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * EmsWaterRealtime服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2021-08-24 07:52
 * 类描述
 * 修订历史：
 * 日期：2021-08-24
 * 作者：generator
 * 参考：
 * 描述：EmsWaterRealtime服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "emsWaterRealtimeService")
public class EmsWaterRealtimeServiceImpl extends BaseServiceImpl<EmsWaterRealtime, String> implements IEmsWaterRealtimeService {

    private static final Logger logger = LoggerFactory.getLogger(IfMesEmsSwapfileServiceImpl.class);

    @Autowired
    private EmsWaterRealtimeMapper emsWaterRealtimeMapper;

    @Override
    protected IBaseMapper<EmsWaterRealtime, String> getMapper() {
        return emsWaterRealtimeMapper;
    }

    List<EmsWaterRealtime> emsWaterRealtimeList;

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_OTHER)
    public List<EmsWaterRealtime> getWaterListByArmMeter() {
           // emsWaterRealtimeMapper.selectByPrimaryKey("1");//.getWaterListByArmMeter();
        //List<EmsWaterRealtime>
                emsWaterRealtimeList = emsWaterRealtimeMapper.getWaterListByArmMeter();
        return emsWaterRealtimeList;
    }

    @Override
    public int dataGeneration() {

        int addSize = 0;
        int updateSize = 0;
        try {
            EmsWaterRealtime model;
            // emsWaterRealtimeMapper.selectByPrimaryKey("1");//.getWaterListByArmMeter();
            //List<EmsWaterRealtime> emsWaterRealtimeList = getWaterListByArmMeter();
            for (EmsWaterRealtime emsWaterRealtime : emsWaterRealtimeList){
                emsWaterRealtime.setReadtime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
                model = emsWaterRealtimeMapper.selectByPrimaryKey(emsWaterRealtime.getMeterid());
                if(model !=null){
                    emsWaterRealtimeMapper.updateByPrimaryKey(emsWaterRealtime);
                    updateSize+=1;
                    continue;
                }else {
                    addSize+= emsWaterRealtimeMapper.insert(emsWaterRealtime);
                }
            }
            String clock = DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
            HashMap<String,Object> hashMap = new HashMap<String,Object>();
            hashMap.put("clock",clock);
            List<EmsWaterRealtime> emsWaterRealtimeList = emsWaterRealtimeMapper.getWaterTenMinutes();
            StringBuffer sub = new StringBuffer();
            String table="EMS_WATER";
            for (EmsWaterRealtime emsWaterRealtime : emsWaterRealtimeList){
                String[] tens = emsWaterRealtime.getmMaterial().split("\\.");
                String tag = tens[1];
                //多个表生成数据就填加table;
                table = tens[0];
                String sql = ","+tag + " = " + "'" + emsWaterRealtime.getSumvalue() + "'";
                sub.append(sql);
            }
            hashMap.put("table",table);
            hashMap.put("sql",sub.toString());
            updateSize += emsWaterRealtimeMapper.updateWaterMinutes(hashMap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        logger.info("本次总共新增水数据条数：" + addSize);
        logger.info("本次总共更新水数据条数：" + updateSize);
        return addSize+updateSize;
    }


    @Override
    public void getWaterTenMinutes() {
        int addSize = 0;
        int updateSize = 0;
        int i = 0;
        try {
            EmsWaterRealtime model;
            // emsWaterRealtimeMapper.selectByPrimaryKey("1");//.getWaterListByArmMeter();
            String clock1 = DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
            String clock2 = DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
            HashMap<String,Object> hashMap = new HashMap<String,Object>();
            hashMap.put("clock1",clock1);
            hashMap.put("clock2",clock2);
            addSize += emsWaterRealtimeMapper.insertWaterTenMinutes(hashMap);
            List<EmsWaterRealtime> emsWaterRealtimeList = emsWaterRealtimeMapper.getWaterTenMinutes();
            StringBuffer sub = new StringBuffer();
            String table="EMS_WATER_TIMING";
            for (EmsWaterRealtime emsWaterRealtime : emsWaterRealtimeList){
                i++;
                String[] tens = emsWaterRealtime.getmType().split("\\.");
                String tag = tens[1];
                //多个表生成数据就填加table;
                table = tens[0];
                String sql = ","+tag + " = " + "'" + emsWaterRealtime.getSumvalue() + "'";
                sub.append(sql);
            }
            clock2 = DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
            hashMap.put("table",table);
            hashMap.put("clock2",clock2);
            hashMap.put("sql",sub.toString());
            updateSize += emsWaterRealtimeMapper.updateWaterTenMinutes(hashMap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        logger.info("本次总共新增水数据条数：" + addSize);
        logger.info("本次总共更新水数据条数：" + updateSize);
        //return addSize+updateSize;
    }

    static MswebserviceStub.UserInfo userInfo = new MswebserviceStub.UserInfo();

    /***
     * 从大用户水系统获取数据到Mosaic
     */
    @Override
    public void getWaterListToMosaic() {
        List<EmsWaterRealtime> emsWaterRealtimeList = emsWaterRealtimeMapper.getWaterListToMosaic();
        MswebserviceStub stub;
        userInfo = new MswebserviceStub.UserInfo();
        //0x0069:032e:0 瞬时流量
        //0x020b:483d:0 累计流量
        //0x006b:41df:0 压力
        final String SS="0x0069:032e:0";
        final String LJ="0x020b:483d:0";
        final String YL="0x006b:41df:0";
        try {
         stub=new MswebserviceStub("http://172.16.90.229:9900");
        userInfo.setMdbName("scada");
        userInfo.setMdbInstance("master");
        userInfo.setComText("");
        userInfo.setMIP("");
        userInfo.setMUserID("");
        userInfo.setMUserName("mosaic");
        userInfo.setMUserPass("mosaic");
        // Open
        SetOpenConnSample(stub);
        for(EmsWaterRealtime emswater:emsWaterRealtimeList) {
            //Equip:Desig='11KV变电站' and Quantity:Name='累计流量'
            if(emswater.getMosaicid()==null||"".equals(emswater.getMosaicid()))
            {
                continue;
            }
            String sql="update Ana set Eng='"+emswater.getSumvalue()+"' where Equip="+emswater.getMosaicid()+"";
           switch (emswater.getmType()){
               case "SS":
                   sql+=" AND Quantity="+SS+"";
               break;
               case "YL":
                   sql+=" AND Quantity="+YL+"";
               break;
               default:
                   sql+=" AND Quantity="+LJ+"";
               break;
            }
            // Update
            SetUpdateValue(stub,sql);
        }
        // Close
        SetCloseConnSample(stub);
    } catch (AxisFault e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

    private static void SetOpenConnSample(MswebserviceStub stub) {
        try {
            MswebserviceStub.WSConnectOpen openReq = new MswebserviceStub.WSConnectOpen();
            MswebserviceStub.WSConnectOpenResponse openResp = null;
            // Open
            openReq.setUserInfo(userInfo);

            openResp = stub.wSConnectOpen(openReq);
            System.out.println("打开mosaic链接成功");
            // Save UserID
            userInfo.setMUserID(openResp.getId());

        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("打开mosaic链接失败");
        }

    }

    // 更新点的值
    private static void SetUpdateValue(MswebserviceStub stub,String sql) {
        // 0x0002:5365:2e
        MswebserviceStub.DataResult queryData = new MswebserviceStub.DataResult();

        try {

            //String sql = "update Ana set(Eng,User)=(100,0x0002:5365:2e) where AltId='PUMP1_SPEED' ";
            // Dig表为 update Dig set(Cs,User)=(1,0x0002:5365:2e) update Ana set Eng='1812482' where Equip='0x06f4:0bfe:1e' AND Quantity='0x006a:489c:22'

            userInfo.setComText(sql);
            MswebserviceStub.WSQueryExecute query = new MswebserviceStub.WSQueryExecute();
            query.setUserInfo(userInfo);
            queryData = stub.wSQueryExecute(query);
            //System.out.println(queryData.getData());

        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 关闭mosaic链接
    private static void SetCloseConnSample(MswebserviceStub stub) {
        MswebserviceStub.WSConnectClose closeReq = new MswebserviceStub.WSConnectClose();
        closeReq.setUserInfo(userInfo);
        try {
            stub.wSConnectClose(closeReq);
            userInfo = null;
            System.out.println("关闭mosaic链接成功");
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Autowired
    IFormulaService formulaService;

    @Override
    public void getcalpoint() {
        List<TRmCalpoint> tRmCalpoints = emsWaterRealtimeMapper.getcalpoint();
        for(TRmCalpoint model : tRmCalpoints){
            Formula formula = new Formula();
            formula.setCode(model.getItemid());
            String itemdesc = model.getItemdesc(); // 项目描述
            formula.setDescription(itemdesc!=null && !itemdesc.trim().isEmpty() ? itemdesc : model.getTagAlias());
            // formula.setClock(DateUtils.getCurrentTime("yyyyMM"));
            formula.setClock("202001");
            formula.setIsavailable("1");
            formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
            formula.setTablename("T_RM_CALPOINT_VALUE");
            formula.setSourcecode("R(T_RM_CALPOINT_VALUE," + model.getItemid() + ")");
            formula.setRevisor(JwtUtil.getUseridByToken());

            formulaService.add(formula);
        }

    }
}
