package com.ruoyi.dxp.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dxp.constant.DxpConstants;
import com.ruoyi.dxp.constant.DxpSyncStatusConstants;
import com.ruoyi.dxp.domain.*;
import com.ruoyi.dxp.dto.ServiceIntegrationSave;
import com.ruoyi.dxp.mapper.ServiceIntegrationMapper;
import com.ruoyi.dxp.mapper.ServiceShareMapper;
import com.ruoyi.dxp.service.IServiceIntegrationService;
import com.ruoyi.dxp.service.IServiceItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 整合服务Service业务层处理
 *
 * @author jy
 * @date 2022-11-29
 */
@Service
public class ServiceIntegrationServiceImpl implements IServiceIntegrationService {
    @Autowired
    private ServiceIntegrationMapper serviceIntegrationMapper;

    @Autowired
    private IServiceItemService serviceItemService;

    @Autowired
    private ServiceShareMapper serviceShareMapper;

    /**
     * 查询整合服务
     *
     * @param id 整合服务主键
     * @return 整合服务
     */
    @Override
    public ServiceIntegration selectServiceIntegrationById(Long id) {
        return serviceIntegrationMapper.selectServiceIntegrationById(id);
    }

    /**
     * 查询整合服务列表
     *
     * @param serviceIntegration 整合服务
     * @return 整合服务
     */
    @Override
    public List<ServiceIntegration> selectServiceIntegrationList(ServiceIntegration serviceIntegration) {
        return serviceIntegrationMapper.selectServiceIntegrationList(serviceIntegration);
    }

    /**
     * 新增整合服务
     *
     * @param serviceIntegration 整合服务
     * @return 结果
     */
    @Override
    public int insertServiceIntegration(ServiceIntegration serviceIntegration) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        serviceIntegration.setCreateBy(loginUser.getUsername());
        serviceIntegration.setCreateTime(DateUtils.getNowDate());
        return serviceIntegrationMapper.insertServiceIntegration(serviceIntegration);
    }

    /**
     * 修改整合服务
     *
     * @param serviceIntegration 整合服务
     * @return 结果
     */
    @Override
    public int updateServiceIntegration(ServiceIntegration serviceIntegration) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        serviceIntegration.setUpdateBy(loginUser.getUsername());
        serviceIntegration.setUpdateTime(DateUtils.getNowDate());
        return serviceIntegrationMapper.updateServiceIntegration(serviceIntegration);
    }

    /**
     * 保存整合服务
     *
     * @param serviceIntegration 保存对象
     * @return 保存结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult save(ServiceIntegrationSave serviceIntegration) {
        // 检查参数
        if (serviceIntegration.getCatalogueId() == null) {
            return AjaxResult.error("目录不能为空");
        }

        if (StringUtils.isEmpty(serviceIntegration.getServiceName())) {
            return AjaxResult.error("服务名称不能为空");
        }

        if (StringUtils.isEmpty(serviceIntegration.getServiceUrl())) {
            return AjaxResult.error("服务地址不能为空");
        }

        if (StringUtils.isEmpty(serviceIntegration.getNeedAuth())) {
            return AjaxResult.error("是否需要授权不能为空");
        }

        if (StringUtils.isEmpty(serviceIntegration.getAuthWay())) {
            return AjaxResult.error("授权方式不能为空");
        }

        if (StringUtils.isEmpty(serviceIntegration.getRequestMethod())) {
            return AjaxResult.error("请求方法不能为空");
        }

        if (StringUtils.isEmpty(serviceIntegration.getParamForm())) {
            return AjaxResult.error("参数形式不能为空");
        }

        if (StringUtils.isEmpty(serviceIntegration.getResponseForm())) {
            return AjaxResult.error("返回格式不能为空");
        }

        List<ServiceItem> serviceItems = serviceIntegration.getServiceItems();
        if (serviceItems == null || serviceItems.size() == 0) {
            return AjaxResult.error("参数不能为空");
        }

        for (ServiceItem serviceItem : serviceItems) {
            if (StringUtils.isEmpty(serviceItem.getParamType())) {
                return AjaxResult.error("参数类型不能为空");
            }

            if (StringUtils.isEmpty(serviceItem.getParamName())) {
                return AjaxResult.error("参数名称不能为空");
            }

            if (StringUtils.isEmpty(serviceItem.getDataType())) {
                return AjaxResult.error("参数数据类型不能为空");
            }
        }

        // 保存服务
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ServiceIntegration sIntegration = new ServiceIntegration();
        BeanUtils.copyProperties(serviceIntegration, sIntegration);
        sIntegration.setStatus(DxpConstants.STATUS_VALID);
        sIntegration.setCreateBy(loginUser.getUsername());
        sIntegration.setCreateTime(DateUtils.getNowDate());
        if (serviceIntegration.getId() != null) {
            sIntegration.setUpdateBy(loginUser.getUsername());
            sIntegration.setUpdateTime(DateUtils.getNowDate());
            serviceIntegrationMapper.updateServiceIntegration(sIntegration);

            // 删除已有明细
//            this.serviceItemService.deleteServiceItemByTypeAndDataId(DxpConstants.DATA_TYPE_INTEGRATION, sIntegration.getId());

            // 找到已经删除的
            ServiceItem itemReq = new ServiceItem();
            itemReq.setServiceId(serviceIntegration.getId());
            itemReq.setServiceType(DxpConstants.DATA_TYPE_INTEGRATION);
            List<ServiceItem> existServiceItems = serviceItemService.selectServiceItemList(itemReq);
            if (existServiceItems != null && existServiceItems.size() > 0) {
                for (ServiceItem existServiceItem : existServiceItems) {
                    // 已经存在的明细是否在本次提交内
                    long count = serviceItems.stream().filter(p -> p.getId() != null && p.getId().equals(existServiceItem.getId())).count();
                    if (count == 0) {
                        // 删除该serviceItem
                        this.serviceItemService.deleteServiceItemById(existServiceItem.getId());
                    }
                }
            }

            // 保存明细
            for (ServiceItem serviceItem : serviceItems) {
                if (serviceItem.getId() != null) {
                    serviceItem.setUpdateBy(loginUser.getUsername());
                    serviceItem.setUpdateTime(DateUtils.getNowDate());
                    serviceItemService.updateServiceItem(serviceItem);
                } else {
                    serviceItem.setServiceType(DxpConstants.DATA_TYPE_INTEGRATION);
                    serviceItem.setServiceId(sIntegration.getId());
                    serviceItem.setCreateBy(loginUser.getUsername());
                    serviceItem.setCreateTime(DateUtils.getNowDate());
                    serviceItemService.insertServiceItem(serviceItem);
                }
            }

            // 检查整合数据，共享数据是否有更新
            this.compareIntegrationAndShare(sIntegration.getId());
        } else {
            serviceIntegrationMapper.insertServiceIntegration(sIntegration);

            // 保存明细
            for (ServiceItem serviceItem : serviceItems) {
                serviceItem.setServiceType(DxpConstants.DATA_TYPE_INTEGRATION);
                serviceItem.setServiceId(sIntegration.getId());
                serviceItem.setCreateBy(loginUser.getUsername());
                serviceItem.setCreateTime(DateUtils.getNowDate());
                serviceItemService.insertServiceItem(serviceItem);
            }
        }

        return AjaxResult.success(sIntegration.getId());
    }

//    /**
//     * 批量删除整合服务
//     *
//     * @param ids 需要删除的整合服务主键
//     * @return 结果
//     */
//    @Override
//    public int deleteServiceIntegrationByIds(Long[] ids)
//    {
//        return serviceIntegrationMapper.deleteServiceIntegrationByIds(ids);
//    }

    /**
     * 删除整合服务信息
     *
     * @param id 整合服务主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteServiceIntegrationById(Long id) {
        // 删除服务
        ServiceShare ssReq = new ServiceShare();
        ssReq.setServiceId(id);
        List<ServiceShare> serviceShares = serviceShareMapper.selectServiceShareList(ssReq);
        if (serviceShares != null && serviceShares.size() > 0) {
            return AjaxResult.error("当前服务已经关联共享服务，不能删除");
        }

        ServiceIntegration serviceIntegration = serviceIntegrationMapper.selectServiceIntegrationById(id);
        if (serviceIntegration == null) {
            return AjaxResult.error("服务不存在");
        }

        // 删除服务
        serviceIntegrationMapper.deleteServiceIntegrationById(id);

        // 删除服务明细
        serviceItemService.deleteServiceItemByTypeAndDataId(DxpConstants.DATA_TYPE_INTEGRATION, serviceIntegration.getId());
        return AjaxResult.success();
    }

    @Override
    public void alterTable() {
        serviceIntegrationMapper.alterTable();
    }

    /**
     * 对比整合和共享参数
     * @param integrationId
     */
    private void compareIntegrationAndShare(Long integrationId) {
        // 查询整合数据对应的共享数据
        ServiceShare dsReq = new ServiceShare();
        dsReq.setServiceId(integrationId);
        List<ServiceShare> serviceShares = serviceShareMapper.selectServiceShareList(dsReq);
        if (serviceShares == null || serviceShares.size() == 0) {
            return;
        }

        // 查询整合数据明细
        ServiceItem req = new ServiceItem();
        req.setServiceType(DxpConstants.DATA_TYPE_INTEGRATION);
        req.setServiceId(integrationId);
        List<ServiceItem> integrationServiceItems = serviceItemService.selectServiceItemList(req);

        // 循环检查共享数据
        for (ServiceShare serviceShare : serviceShares) {
            // 查询共享数据的明细
            ServiceItem sReq = new ServiceItem();
            sReq.setServiceType(DxpConstants.DATA_TYPE_SHARE);
            sReq.setServiceId(serviceShare.getId());
            List<ServiceItem> shareServiceItems = serviceItemService.selectServiceItemList(sReq);

            // 比较明细是否有变化
            if (checkChange(integrationServiceItems, shareServiceItems)) {
                // 设置共享数据变化标志
                serviceShare.setSyncFlag(DxpSyncStatusConstants.HAS_NEW_UPDATE);
                serviceShareMapper.updateServiceShare(serviceShare);
            }
        }
    }

    /**
     * 检查是否变化
     *
     * @param sources 源数据项
     * @param targets 目标数据项
     * @return 是否变化
     */
    private boolean checkChange(List<ServiceItem> sources, List<ServiceItem> targets) {
        Boolean changFlag = false;
        if (sources == null || targets == null) {
            // 任意源或目标为空，则表示有变化
            return true;
        } else if (sources.size() == 0 && targets.size() == 0) {
            // 源和目标都没有值
            return false;
        } else if (sources.size() != targets.size()) {
            // 源和目标长度不一致
            return true;
        } else {
            // 逐字段对比
            for (ServiceItem source : sources) {
                ServiceItem findTarget = targets.stream().filter(p -> p.getRelationId().equals(source.getId())).findAny().orElse(null);
                if (findTarget == null) {
                    return true;
                }

                if (!StringUtils.equals(source.getParamName(), findTarget.getParamName())) {
                    return true;
                }

                if (!StringUtils.equals(source.getDataType(), findTarget.getDataType())) {
                    return true;
                }

                if (!StringUtils.equals(source.getRemark(), findTarget.getRemark())) {
                    return true;
                }

                if (!StringUtils.equals(source.getMapColumnName(), findTarget.getMapColumnName())) {
                    return true;
                }
            }

            for (ServiceItem target : targets) {
                ServiceItem findSource = sources.stream().filter(p -> p.getId().equals(target.getRelationId())).findAny().orElse(null);
                if (findSource == null) {
                    return true;
                }

                if (!StringUtils.equals(target.getParamName(), findSource.getParamName())) {
                    return true;
                }

                if (!StringUtils.equals(target.getDataType(), findSource.getDataType())) {
                    return true;
                }

                if (!StringUtils.equals(target.getRemark(), findSource.getRemark())) {
                    return true;
                }

                if (!StringUtils.equals(target.getMapColumnName(), findSource.getMapColumnName())) {
                    return true;
                }
            }

            return false;
        }
    }
}
