/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.emergencySupportCenter.modular.onlinePlanFormulation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.emergencySupport.modular.es.entity.EsNetworkEntry;
import com.unis.emergencySupport.modular.es.mapper.EsNetworkEntryMapper;
import com.unis.emergencySupport.modular.esstorageenterprise.entity.BizEsStorageEnterprise;
import com.unis.emergencySupportCenter.modular.onlinePlanFormulationOrg.entity.OnlinePlanFormulationOrg;
import com.unis.emergencySupportCenter.modular.onlinePlanFormulationOrg.mapper.OnlinePlanFormulationOrgMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.emergencySupportCenter.modular.onlinePlanFormulation.entity.OnlinePlanFormulation;
import com.unis.emergencySupportCenter.modular.onlinePlanFormulation.mapper.OnlinePlanFormulationMapper;
import com.unis.emergencySupportCenter.modular.onlinePlanFormulation.param.OnlinePlanFormulationAddParam;
import com.unis.emergencySupportCenter.modular.onlinePlanFormulation.param.OnlinePlanFormulationEditParam;
import com.unis.emergencySupportCenter.modular.onlinePlanFormulation.param.OnlinePlanFormulationIdParam;
import com.unis.emergencySupportCenter.modular.onlinePlanFormulation.param.OnlinePlanFormulationPageParam;
import com.unis.emergencySupportCenter.modular.onlinePlanFormulation.service.OnlinePlanFormulationService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 在线方案制定Service接口实现类
 *
 * @author QSHan
 * @date 2024/06/28 14:23
 **/
@Service
public class OnlinePlanFormulationServiceImpl extends ServiceImpl<OnlinePlanFormulationMapper, OnlinePlanFormulation> implements OnlinePlanFormulationService {
    @Resource
    private OnlinePlanFormulationMapper onlinePlanFormulationMapper;
    @Resource
    private OnlinePlanFormulationOrgMapper onlinePlanFormulationOrgMapper;
    @Resource
    private EsNetworkEntryMapper esNetworkEntryMapper;

    @Override
    public Page<OnlinePlanFormulation> page(OnlinePlanFormulationPageParam onlinePlanFormulationPageParam) {
        QueryWrapper<OnlinePlanFormulation> queryWrapper = new QueryWrapper<>();
        // 自定义查询条件
        String planName = onlinePlanFormulationPageParam.getPlanName();
        if (StringUtils.isNotEmpty(planName)) {
            queryWrapper.lambda().like(OnlinePlanFormulation::getPlanName, planName);
        }
        Integer emergencyLevel = onlinePlanFormulationPageParam.getEmergencyLevel();
        if (ObjectUtils.isNotEmpty(emergencyLevel)) {
            queryWrapper.lambda().eq(OnlinePlanFormulation::getEmergencyLevel, emergencyLevel);
        }
        if (ObjectUtil.isAllNotEmpty(onlinePlanFormulationPageParam.getSortField(), onlinePlanFormulationPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(onlinePlanFormulationPageParam.getSortOrder());
            queryWrapper.orderBy(true, onlinePlanFormulationPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(onlinePlanFormulationPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(OnlinePlanFormulation::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(OnlinePlanFormulationAddParam onlinePlanFormulationAddParam) {
        OnlinePlanFormulation onlinePlanFormulation = BeanUtil.toBean(onlinePlanFormulationAddParam, OnlinePlanFormulation.class);
        this.save(onlinePlanFormulation);
        // 保存子表管理数据
        this.insertChild(onlinePlanFormulation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(OnlinePlanFormulationEditParam onlinePlanFormulationEditParam) {
        OnlinePlanFormulation onlinePlanFormulation = this.queryEntity(onlinePlanFormulationEditParam.getId());
        BeanUtil.copyProperties(onlinePlanFormulationEditParam, onlinePlanFormulation);
        this.updateById(onlinePlanFormulation);
        // 修改子表关联数据
        this.updateChild(onlinePlanFormulation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<OnlinePlanFormulationIdParam> onlinePlanFormulationIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(onlinePlanFormulationIdParamList, OnlinePlanFormulationIdParam::getId));
        // 删除子表关联数据
        onlinePlanFormulationIdParamList.forEach(ids -> this.deleteChild(ids.getId()));
    }

    @Override
    public OnlinePlanFormulation detail(OnlinePlanFormulationIdParam onlinePlanFormulationIdParam) {
        OnlinePlanFormulation onlinePlanFormulation = this.queryEntity(onlinePlanFormulationIdParam.getId());
        // 查询子表关联数据,拼接
        List<OnlinePlanFormulationOrg> lists = onlinePlanFormulationOrgMapper.selectList(this.selectChildByMasterId(onlinePlanFormulationIdParam.getId()));
        if (CollectionUtils.isNotEmpty(lists)) {
            onlinePlanFormulation.setSysOrgIds(
                    lists.stream().map(OnlinePlanFormulationOrg::getSysOrgId).collect(Collectors.joining(","))
            );
        }
        return onlinePlanFormulation;
    }

    @Override
    public OnlinePlanFormulation queryEntity(String id) {
        OnlinePlanFormulation onlinePlanFormulation = this.getById(id);
        if (ObjectUtil.isEmpty(onlinePlanFormulation)) {
            throw new CommonException("在线方案制定不存在，id值为：{}", id);
        }
        return onlinePlanFormulation;
    }

    @Override
    public List<Map<String, Object>> getEmergencyPointList() {
        return onlinePlanFormulationMapper.getEmergencyPointList();
    }

    @Override
    public List<Map<String, Object>> getPlanNameStatusOneList() {
        return onlinePlanFormulationMapper.getPlanNameStatusOneList();
    }

    // 新增子表关联数据
    private void insertChild(OnlinePlanFormulation onlinePlanFormulation) {
        String[] sysOrgIds = onlinePlanFormulation.getSysOrgIds().split(",");
        if (sysOrgIds.length > 0) {
            for (String sysOrgId : sysOrgIds) {
                OnlinePlanFormulationOrg org = new OnlinePlanFormulationOrg();
                org.setEsOnlinePlanFormulationId(onlinePlanFormulation.getId());
                org.setSysOrgId(sysOrgId);
                onlinePlanFormulationOrgMapper.insert(org);
            }
        }
    }

    // 编辑子表关联数据
    private void updateChild(OnlinePlanFormulation onlinePlanFormulation) {
        // 先删除
        this.deleteChild(onlinePlanFormulation.getId());
        // 在保存
        this.insertChild(onlinePlanFormulation);
    }

    // 删除子表关联数据
    private void deleteChild(String onlinePlanFormulationId) {
        // 先删除
        onlinePlanFormulationOrgMapper.delete(this.selectChildByMasterId(onlinePlanFormulationId));
    }

    // 根据主表id查询子表关联数据
    private QueryWrapper<OnlinePlanFormulationOrg> selectChildByMasterId(String onlinePlanFormulationId) {
        // 先删除
        QueryWrapper<OnlinePlanFormulationOrg> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OnlinePlanFormulationOrg::getEsOnlinePlanFormulationId, onlinePlanFormulationId);
        return wrapper;
    }

}
