package com.judong.chuanyiserver.service.impl;

import com.judong.chuanyiserver.dao.ConnectDao;
import com.judong.chuanyiserver.entity.ServerInformation;
import com.judong.chuanyiserver.enums.ResultEnum;
import com.judong.chuanyiserver.service.ConnectService;
import com.judong.chuanyiserver.util.*;
import lombok.extern.slf4j.Slf4j;
import org.jinterop.dcom.common.JIException;
import org.openscada.opc.dcom.da.OPCSERVERSTATE;
import org.openscada.opc.lib.common.AlreadyConnectedException;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.da.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.UnknownHostException;
import java.util.concurrent.Executors;

@Service
@Transactional
@Slf4j
public class ConnectServiceImpl implements ConnectService {

    @Autowired
    private ConnectDao connectDao;
    @Autowired
    private UserUtil userUtil;

    @Override
    public Result testConnect(ServerInformation serverInformation) throws AlreadyConnectedException, JIException, UnknownHostException {
        // 连接信息
        ConnectionInformation ci = new ConnectionInformation();
        //服务
        Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
        try {
            ci.setHost(serverInformation.getIpAddress()); // 安装opc电脑IP
            ci.setDomain(""); // 域，为空就行
            ci.setUser(serverInformation.getIpUserName()); // 电脑上自己建好的用户名
            ci.setPassword(serverInformation.getIpPassword()); // 用户名的密码
            ci.setClsid("7BC0CC8E-482C-47CA-ABDC-0FE7F9C6E729"); // KEPServer的注册表ID，可以在“组件服务”里看到
            // ci.setProgId("");

            // 连接到服务
            long start = System.currentTimeMillis();
            server.connect();
            long finish = System.currentTimeMillis();
            log.info("连接耗费时间为:" + (finish - start) + "毫秒");
            if (null == server.getServerState()) {
                return Result.no(ResultEnum.NOT_FOUND.getRespCode(), "连接失败");
            }
            if (OPCSERVERSTATE.OPC_STATUS_RUNNING == server.getServerState().getServerState()) {
                return Result.ok(true);
            }
        } finally {
            //关闭连接使用
            server.dispose();
        }
        return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), ResultEnum.SERVER_ERROR.getRespMsg());
    }

    @Override
    public synchronized Result saveConnect(ServerInformation serverInformation) {
        String userId = userUtil.getCurrentUserId();
        serverInformation.setUserId(userId);
        ServerInformation si = connectDao.getServerInformation(userId, serverInformation.getIpAddress());
        if (Blank.isNotEmpty(si)) {
            return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "该用户下此ip已被使保存，请更换其他ip");
        }
        if (connectDao.saveConnect(serverInformation) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "保存连接失败");
        }
        return Result.ok("保存连接成功");
    }

    @Override
    public Result selectAllConnect() {
        return Result.ok(connectDao.selectAllConnect(userUtil.getCurrentUserId()));
    }

    @Override
    public synchronized Result editConnect(ServerInformation serverInformation) {
        String userId = userUtil.getCurrentUserId();
        ServerInformation si = connectDao.getServerInformationEdit(serverInformation.getId(), userId, serverInformation.getIpAddress());
        if (Blank.isNotEmpty(si)) {
            return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "该用户下此ip已被使保存，请更换其他ip");
        }
        if (connectDao.editConnect(serverInformation) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "编辑连接失败");
        }
        return Result.ok("编辑连接成功");
    }

    @Override
    public Result deleteConnect(int id) {
        String userId = userUtil.getCurrentUserId();
        if (connectDao.deleteConnect(id, userId) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "删除连接失败");
        }
        return Result.ok("删除连接成功");
    }

    @Override
    public Result openConnect(int id) throws Exception {
        ServerInformation serverInformation = connectDao.getServerInformationById(id);
        if (Blank.isEmpty(serverInformation)) {
            return Result.no(ResultEnum.NOT_FOUND.getRespCode(), ResultEnum.NOT_FOUND.getRespMsg());
        }
        //如果协议类型为OPCDA
        if (serverInformation.getAgreementType() == ConstantStr.OPC_DA) {
            return OpcServerDaUtil.opcDaReadItemTree(serverInformation);
        }
        return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), ResultEnum.SERVER_ERROR.getRespMsg());
    }

    @Override
    public Result readItemValue(int id, String itemName) throws Exception {
        ServerInformation serverInformation = connectDao.getServerInformationById(id);
        if (Blank.isEmpty(serverInformation)) {
            return Result.no(ResultEnum.NOT_FOUND.getRespCode(), ResultEnum.NOT_FOUND.getRespMsg());
        }
        //如果协议类型为OPCDA
        if (serverInformation.getAgreementType() == ConstantStr.OPC_DA) {
            return OpcServerDaUtil.opcDaReadItemValue(serverInformation, itemName);
        }
        return Result.no(ResultEnum.NOT_FOUND.getRespCode(), ResultEnum.NOT_FOUND.getRespMsg());
    }

}
