/*
 * 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 vip.xiaonuo.modular.base.baseConfig.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.org.entity.BizOrg;
import vip.xiaonuo.biz.modular.org.mapper.BizOrgMapper;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.core.enums.BaseDataTypeEnum;
import vip.xiaonuo.core.param.OrgIdParam;
import vip.xiaonuo.modular.base.baseConfig.entity.BaseConfig;
import vip.xiaonuo.modular.base.baseConfig.mapper.BaseConfigMapper;
import vip.xiaonuo.modular.base.baseConfig.param.*;
import vip.xiaonuo.modular.base.baseConfig.service.BaseConfigService;

import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 基础设置Service接口实现类
 *
 * @author newspaper
 * @date  2023/12/08 10:22
 **/
@Service
public class BaseConfigServiceImpl extends ServiceImpl<BaseConfigMapper, BaseConfig> implements BaseConfigService {
    @Autowired
    private BizOrgMapper bizOrgMapper;

    @Override
    public List<Tree<String>> tree(OrgIdParam orgIdParam) {
        String orgId = orgIdParam.getOrgId();
        List<BaseConfig> allConfigs = new ArrayList<>();
        List<BaseConfig> baseConfigs = this.list(new LambdaQueryWrapper<BaseConfig>().eq(BaseConfig::getParentId, 0).orderByAsc(BaseConfig::getSortCode));
        List<BaseConfig> childConfigs = this.list(new LambdaQueryWrapper<BaseConfig>().eq(BaseConfig::getOrgId, orgId).orderByAsc(BaseConfig::getSortCode));

        allConfigs.addAll(baseConfigs);
        allConfigs.addAll(childConfigs);
        List<TreeNode<String>> treeNodeList = allConfigs.stream().filter(baseConfig -> !"预警类型".equals(baseConfig.getConfigName())).map(baseConfig ->
                new TreeNode<>(baseConfig.getId(), baseConfig.getParentId(),
                        baseConfig.getConfigName(), baseConfig.getSortCode()).setExtra(JSONUtil.parseObj(baseConfig)))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BaseConfigAddParam baseConfigAddParam) {
        BaseConfig baseConfig = BeanUtil.toBean(baseConfigAddParam, BaseConfig.class);
        if (this.count(new QueryWrapper<BaseConfig>().lambda()
                .eq(BaseConfig::getOrgId,baseConfigAddParam.getOrgId())
                .eq(BaseConfig::getParentId,baseConfigAddParam.getParentId())
                .eq(BaseConfig::getConfigName,baseConfig.getConfigName())) > 0) {
            throw new CommonException("存在重复配置名称!");
        }
        this.save(baseConfig);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BaseConfigEditParam baseConfigEditParam) {
        BaseConfig baseConfig = this.queryEntity(baseConfigEditParam.getId());
        BeanUtil.copyProperties(baseConfigEditParam, baseConfig);
        if (this.count(new QueryWrapper<BaseConfig>().lambda()
                .ne(BaseConfig::getId,baseConfig.getId())
                .eq(BaseConfig::getOrgId,baseConfig.getOrgId())
                .eq(BaseConfig::getParentId,baseConfig.getParentId())
                .eq(BaseConfig::getConfigName,baseConfig.getConfigName())) > 0) {
            throw new CommonException("存在重复配置名称!");
        }
        this.updateById(baseConfig);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BaseConfigIdParam> baseConfigIdParamList) {
        List<String> toDeleteBaseConfigIdList = CollStreamUtil.toList(baseConfigIdParamList, BaseConfigIdParam::getId);
        // 执行删除
        this.removeByIds(toDeleteBaseConfigIdList);
    }

    @Override
    public BaseConfig detail(BaseConfigIdParam baseConfigIdParam) {
        return this.queryEntity(baseConfigIdParam.getId());
    }

    @Override
    public BaseConfig queryEntity(String id) {
        BaseConfig baseConfig = this.getById(id);
        if(ObjectUtil.isEmpty(baseConfig)) {
            throw new CommonException("基础设置不存在，id值为：{}", id);
        }
        return baseConfig;
    }

    @Override
    public Page<BaseConfig> listChild(BaseConfigListChildParam baseConfigListChildParam) {
        String orgId = baseConfigListChildParam.getOrgId();
        String parentId = baseConfigListChildParam.getParentId();
        QueryWrapper<BaseConfig> queryWrapper = new QueryWrapper();
        if (ObjectUtil.isEmpty(parentId)){
            OrgIdParam orgIdParam = new OrgIdParam();
            orgIdParam.setOrgId(orgId);
            parentId = tree(orgIdParam).get(0).getId();
        }
        queryWrapper.lambda().eq(BaseConfig::getParentId, parentId).eq(BaseConfig::getOrgId, orgId);
        Page<BaseConfig> baseConfigList = this.page(CommonPageRequest.defaultPage(),queryWrapper);
        return baseConfigList;
    }

    @Override
    public List<BizOrg> listOrgId() {
        List<BizOrg> bizOrgs = new ArrayList<>();
        String orgId = StpLoginUserUtil.getLoginUser().getOrgId();
        BizOrg bizOrg = bizOrgMapper.selectById(orgId);
        if (bizOrg.getParentId().equals("0")){
            List<BizOrg> bizOrgs1 = bizOrgMapper.selectList(new QueryWrapper<BizOrg>().lambda().eq(BizOrg::getParentId, orgId));
            bizOrgs.addAll(bizOrgs1);
        }else {
            bizOrgs.add(bizOrg);
        }
        return bizOrgs;
    }


}
