package com.hzya.frame.sys.flow.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.datasource.DataSourceUtilProperties;
import com.hzya.frame.serviceUtil.DsDataSourceUtil;
import com.hzya.frame.sys.flow.entity.SysFlowStepAccountEntity;
import com.hzya.frame.sys.flow.dao.ISysFlowStepAccountDao;
import com.hzya.frame.sys.flow.service.ISysFlowStepAccountService;
import com.hzya.frame.sysnew.application.database.entity.SysApplicationDatabaseEntity;
import com.hzya.frame.sysnew.application.database.service.ISysApplicationDatabaseService;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

import com.hzya.frame.basedao.service.impl.BaseService;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/**
 * 流程步骤账户表(SysFlowStepAccount)表服务实现类
 *
 * @author xiang2lin
 * @since 2025-04-29 10:16:28
 */
@Service(value = "sysFlowStepAccountService")
public class SysFlowStepAccountServiceImpl extends BaseService<SysFlowStepAccountEntity, String> implements ISysFlowStepAccountService {

    private ISysFlowStepAccountDao sysFlowStepAccountDao;
    @Resource
    private DsDataSourceUtil dsDataSourceUtil;
    @Autowired
    private ISysApplicationDatabaseService sysApplicationDatabaseService;

    @Autowired
    public void setSysFlowStepAccountDao(ISysFlowStepAccountDao dao) {
        this.sysFlowStepAccountDao = dao;
        this.dao = dao;
    }


    /**
     * 保存账户信息
     *
     * @param object
     * @return
     */
    @Override
    public JsonResultEntity saveAccount(JSONObject object) {
        SysFlowStepAccountEntity entity = getData("jsonStr", object, SysFlowStepAccountEntity.class);
        try {
            checkParam(entity, "save");
            //控制一下名字不能重复
            List<SysFlowStepAccountEntity> queryList = queryByName(entity);
            if (CollectionUtils.isNotEmpty(queryList) && queryList.size() > 0) {
                return BaseResult.getFailureMessageEntity(entity.getName() + "重复");
            }
            sysFlowStepAccountDao.save(entity);
            //保存数据源表，测试sql的时候要用动态数据源，动态数据源是从sys_application_database表查数据的
            saveOrDataBase(entity);
        } catch (Exception e) {
            return BaseResult.getFailureMessageEntity(e.getMessage());
        }
        return BaseResult.getSuccessMessageEntity("新增成功");
    }

    /**
     * 保存数据源表，测试sql的时候要用动态数据源，动态数据源是从sys_application_database表查数据的
     *
     * @param entity
     */
    private void saveOrDataBase(SysFlowStepAccountEntity entity) throws Exception {
        Assert.notNull(entity, "参数不能为空");
        Assert.notEmpty(entity.getName(), "账户名称不能为空");
        SysApplicationDatabaseEntity db = new SysApplicationDatabaseEntity();
        db.setSourceCode(entity.getName() + "_flow");
        List<SysApplicationDatabaseEntity> queryList = sysApplicationDatabaseService.query(db);
        if (CollectionUtils.isNotEmpty(queryList)) {
            for (SysApplicationDatabaseEntity sys : queryList) {
                sysApplicationDatabaseService.logicRemove(sys);
            }
        }
        SysApplicationDatabaseEntity databaseEntity = new SysApplicationDatabaseEntity();
        databaseEntity.setAppId(entity.getAppId());
        databaseEntity.setSourceCode(entity.getName() + "_flow");
        databaseEntity.setSourceName(entity.getName());
        databaseEntity.setSourceType(entity.getDbType());
        databaseEntity.setSourceIp(entity.getIpAddress());
        databaseEntity.setSourcePort(entity.getPort());
        databaseEntity.setLoginName(entity.getUserName());
        databaseEntity.setPassword(entity.getPassword());
        databaseEntity.setDbName(entity.getDbName());
        databaseEntity.setDbStatus("1");
        sysApplicationDatabaseService.save(databaseEntity);
    }

    /**
     * 更新账户信息
     *
     * @param object
     * @return
     */
    @Override
    public JsonResultEntity updateAccount(JSONObject object) {
        SysFlowStepAccountEntity entity = getData("jsonStr", object, SysFlowStepAccountEntity.class);
        try {
            checkParam(entity, "update");
            //检查一下名字不能重复
            List<SysFlowStepAccountEntity> queryList = queryByName(entity);
            if (CollectionUtils.isNotEmpty(queryList) && queryList.size() > 0) {
                for (SysFlowStepAccountEntity acc : queryList) {
                    if (!acc.getId().equals(entity.getId())) {
                        return BaseResult.getFailureMessageEntity(entity.getName() + "重复");
                    }
                }
            }
            sysFlowStepAccountDao.update(entity);
            //保存数据源表，测试sql的时候要用动态数据源，动态数据源是从sys_application_database表查数据的
            saveOrDataBase(entity);
        } catch (Exception e) {
            return BaseResult.getFailureMessageEntity(e.getMessage());
        }
        return BaseResult.getSuccessMessageEntity("更新成功");
    }

    /**
     * 删除账户信息
     *
     * @param object
     * @return
     */
    @Override
    public JsonResultEntity deleteAccount(JSONObject object) {
        SysFlowStepAccountEntity entity = getData("jsonStr", object, SysFlowStepAccountEntity.class);
        try {
            checkParam(entity, "delete");
        } catch (Exception e) {
            return BaseResult.getFailureMessageEntity(e.getMessage());
        }
        sysFlowStepAccountDao.logicRemove(entity);
        return BaseResult.getSuccessMessageEntity("删除成功");
    }

    /**
     * 查询账户详情
     *
     * @param object
     * @return
     */
    @Override
    public JsonResultEntity getAccount(JSONObject object) {
        SysFlowStepAccountEntity entity = getData("jsonStr", object, SysFlowStepAccountEntity.class);
        try {
            checkParam(entity, "get");
        } catch (Exception e) {
            return BaseResult.getFailureMessageEntity(e.getMessage());
        }
        SysFlowStepAccountEntity SysFlowStepAccountEntity = sysFlowStepAccountDao.get(entity.getId());
        return BaseResult.getSuccessMessageEntity("查询账户详情成功", SysFlowStepAccountEntity);
    }

    /**
     * 查询账户列表数据
     *
     * @param object
     * @return
     */
    @Override
    public JsonResultEntity queryAccountList(JSONObject object) {
        SysFlowStepAccountEntity entity = getData("jsonStr", object, SysFlowStepAccountEntity.class);
        try {
            checkParam(entity, "queryList");
        } catch (Exception e) {
            return BaseResult.getFailureMessageEntity(e.getMessage());
        }
        List<SysFlowStepAccountEntity> queryList = sysFlowStepAccountDao.query(entity);
        return BaseResult.getSuccessMessageEntity("查询列表成功", queryList);
    }

    /**
     * 查询账户分页数据
     *
     * @param object
     * @return
     */
    @Override
    public JsonResultEntity queryAccountPaged(JSONObject object) {
        SysFlowStepAccountEntity entity = getData("jsonStr", object, SysFlowStepAccountEntity.class);
        try {
            checkParam(entity, "queryPaged");
        } catch (Exception e) {
            return BaseResult.getFailureMessageEntity(e.getMessage());
        }
        return null;
    }


    //根据账户名称查询
    private List<SysFlowStepAccountEntity> queryByName(SysFlowStepAccountEntity entity) {
        if (StrUtil.isNotEmpty(entity.getName())) {
            SysFlowStepAccountEntity account = new SysFlowStepAccountEntity();
            account.setName(entity.getName());
            List<SysFlowStepAccountEntity> queryList = sysFlowStepAccountDao.query(account);
            return queryList;
        }
        return null;
    }

    /**
     * 验证账户
     *
     * @param object
     * @return
     */
    @Override
    public JsonResultEntity verifyDataBase(JSONObject object) {
        SysFlowStepAccountEntity entity = getData("jsonStr", object, SysFlowStepAccountEntity.class);
        try {
            checkParam(entity, "verify");
            String dbType = entity.getDbType();
            String driveClass = "";
            StringBuffer sourceUrl = new StringBuffer();
            if (StrUtil.isNotEmpty(dbType)) {
                if ("mysql".equals(dbType)) {
                    driveClass = DataSourceUtilProperties.MYSQLDRIVER_6;
                    sourceUrl.append("jdbc:mysql://").append(entity.getIpAddress()).append(":").append(entity.getPort()).append("/").append(entity.getDbName()).append("?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowLoadLocalInfile=false&autoReconnect=true&failOverReadOnly=false&connectTimeout=30000&socketTimeout=30000&autoReconnectForPools=true");
                } else if ("oracle".equals(dbType)) {
                    driveClass = DataSourceUtilProperties.ORACLEDRIVER;
                    sourceUrl.append("jdbc:oracle:thin:@").append(entity.getIpAddress()).append(":").append(entity.getPort()).append(":").append(entity.getDbName());
                } else if ("sqlserver2000".equals(dbType)) {
                    driveClass = DataSourceUtilProperties.SQL2000DRIVER;
                    sourceUrl.append("jdbc:sqlserver://").append(entity.getIpAddress()).append(":").append(entity.getPort()).append(";DatabaseName=").append(entity.getDbName()).append(";encrypt=false;trustServerCertificate=true");
                } else if ("sqlserver2005".equals(dbType)) {
                    driveClass = DataSourceUtilProperties.SQL2005DRIVER;
                    sourceUrl.append("jdbc:sqlserver://").append(entity.getIpAddress()).append(":").append(entity.getPort()).append(";DatabaseName=").append(entity.getDbName()).append(";encrypt=false;trustServerCertificate=true");
                }
                //测试连接
                Class.forName(driveClass);
                Connection connection = DriverManager.getConnection(sourceUrl.toString(), entity.getUserName(), entity.getPassword());// 相当于连接数据库
                if (null != connection) {
                    return BaseResult.getSuccessMessageEntity("验证成功");
                } else {
                    return BaseResult.getFailureMessageEntity("验证失败");
                }
            }
        } catch (Exception e) {
            return BaseResult.getFailureMessageEntity(e.getMessage());
        }
        return null;
    }

    //数据检查
    private void checkParam(SysFlowStepAccountEntity entity, String type) {
        Assert.notNull(entity, "参数不能为空");
        if ("save".equals(type)) {
            Assert.notEmpty(entity.getFlowId(), "flowId不能为空");
            Assert.notEmpty(entity.getAppId(), "appId不能为空");
            Assert.notEmpty(entity.getName(), "账户名称不能为空");
        } else if ("update".equals(type)) {
            Assert.notEmpty(entity.getId(), "id不能为空");
        } else if ("delete".equals(type)) {
            Assert.notEmpty(entity.getId(), "id不能为空");
        } else if ("get".equals(type)) {
            Assert.notEmpty(entity.getId(), "id不能为空");
        } else if ("queryList".equals(type)) {
            Assert.notEmpty(entity.getFlowId(), "flowId不能为空");
            Assert.notEmpty(entity.getStepId(), "stepId不能为空");
            Assert.notEmpty(entity.getAppId(), "appId不能为空");
        } else if ("queryPaged".equals(type)) {
            Assert.notNull(entity.getPageNum(), "pageNum不能为空");
            Assert.notNull(entity.getPageSize(), "pageSize不能为空");
        } else if ("verify".equals(type)) {

        }
    }
}
