/*
 * 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.biz.modular.sysUserWxOpenSendSet.service;

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.alibaba.fastjson.JSONArray;
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.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.core.exception.BizExceptionEnum;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.sysUserWxOpenSendSet.entity.SysUserWxOpenSendSet;
import vip.xiaonuo.biz.modular.sysUserWxOpenSendSet.mapper.SysUserWxOpenSendSetMapper;
import vip.xiaonuo.biz.modular.sysUserWxOpenSendSet.param.SysUserWxOpenSendSetAddParam;
import vip.xiaonuo.biz.modular.sysUserWxOpenSendSet.param.SysUserWxOpenSendSetEditParam;
import vip.xiaonuo.biz.modular.sysUserWxOpenSendSet.param.SysUserWxOpenSendSetIdParam;
import vip.xiaonuo.biz.modular.sysUserWxOpenSendSet.param.SysUserWxOpenSendSetPageParam;
import vip.xiaonuo.sys.api.SysRelationApi;
import vip.xiaonuo.sys.modular.role.entity.SysRole;
import vip.xiaonuo.sys.modular.role.service.SysRoleService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户微信推送内容订阅表Service接口实现类
 *
 * @author xiang
 * @date 2023/12/13 09:05
 **/
@Service
public class SysUserWxOpenSendSetService extends ServiceImpl<SysUserWxOpenSendSetMapper, SysUserWxOpenSendSet> {

    @Resource
    SysRoleService sysRoleService;
    @Resource
    SysRelationApi sysRelationApi;

    public Page<SysUserWxOpenSendSet> page(SysUserWxOpenSendSetPageParam param) {
        QueryWrapper<SysUserWxOpenSendSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ObjectUtil.isNotEmpty(param.getLogType()), SysUserWxOpenSendSet::getLogType, param.getLogType());
        queryWrapper.lambda().like(ObjectUtil.isNotEmpty(param.getLogRoles()), SysUserWxOpenSendSet::getLogRoles, param.getLogRoles());
        queryWrapper.lambda().eq(ObjectUtil.isNotEmpty(param.getSubscribesFlag()), SysUserWxOpenSendSet::getSubscribesFlag, param.getSubscribesFlag());
        if (ObjectUtil.isAllNotEmpty(param.getSortField(), param.getSortOrder())) {
            CommonSortOrderEnum.validate(param.getSortOrder());
            queryWrapper.orderBy(true, param.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(param.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SysUserWxOpenSendSet::getId);
        }
        Page<SysUserWxOpenSendSet> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        //匹配角色名
        putRoleName(page.getRecords());
        return page;
    }

    public List<SysUserWxOpenSendSet> list(SysUserWxOpenSendSet param) {
        return list(new LambdaQueryWrapper<>(param));
    }

    /**
     * 根据类型获取角色人员
     *
     * @author xiang
     * @date 2023/12/13 09:05
     **/
    public List<String> grepUser(String logType) {
        List<String> userIds = null;
        //订阅角色
        List<SysUserWxOpenSendSet> sendSets = list(new SysUserWxOpenSendSet(null, logType, "subscribe"));
        if (sendSets.isEmpty()) return userIds;
        List<String> roles = JSONArray.parseArray(sendSets.get(0).getLogRoles(), String.class);
        if (roles.isEmpty()) return userIds;
        return sysRelationApi.getUserIdListByRoleIdList(roles);
    }


    public void add(SysUserWxOpenSendSetAddParam sysUserWxOpenSendSetAddParam) {
        SysUserWxOpenSendSet sysUserWxOpenSendSet = BeanUtil.toBean(sysUserWxOpenSendSetAddParam, SysUserWxOpenSendSet.class);
        //重复检查
        checkLogType(null, sysUserWxOpenSendSetAddParam.getLogType());
        this.save(sysUserWxOpenSendSet);
    }

    public void edit(SysUserWxOpenSendSetEditParam sysUserWxOpenSendSetEditParam) {
        SysUserWxOpenSendSet sysUserWxOpenSendSet = this.queryEntity(sysUserWxOpenSendSetEditParam.getId());
        //重复检查
        checkLogType(sysUserWxOpenSendSetEditParam.getId(), sysUserWxOpenSendSetEditParam.getLogType());
        BeanUtil.copyProperties(sysUserWxOpenSendSetEditParam, sysUserWxOpenSendSet);
        this.updateById(sysUserWxOpenSendSet);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<SysUserWxOpenSendSetIdParam> sysUserWxOpenSendSetIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(sysUserWxOpenSendSetIdParamList, SysUserWxOpenSendSetIdParam::getId));
    }

    public SysUserWxOpenSendSet detail(SysUserWxOpenSendSetIdParam sysUserWxOpenSendSetIdParam) {
        return this.queryEntity(sysUserWxOpenSendSetIdParam.getId());
    }

    public SysUserWxOpenSendSet queryEntity(String id) {
        SysUserWxOpenSendSet sysUserWxOpenSendSet = this.getById(id);
        if (ObjectUtil.isEmpty(sysUserWxOpenSendSet)) {
            throw new CommonException("用户微信推送内容订阅表不存在，id值为：{}", id);
        }
        return sysUserWxOpenSendSet;
    }

    //重复检查
    private void checkLogType(String id, String logType) {
        if (Strings.isBlank(logType)) return;
        List<SysUserWxOpenSendSet> list = list(new SysUserWxOpenSendSet(null, logType));
        if (list.isEmpty()) return;
        if (list.size() > 1 || !list.get(0).getId().equals(id))
            throw new CommonException(BizExceptionEnum.ERROR15001.getMessage());
    }

    //匹配角色名
    private void putRoleName(List<SysUserWxOpenSendSet> list) {
        List<SysRole> sysRoles = sysRoleService.roleBizLst();
        for (SysUserWxOpenSendSet one : list) {
            for (SysRole role : sysRoles) {
                if (one.getLogRoles().contains(role.getId()))
                    one.getLogRoleNames().add(role.getName());
            }
        }
    }

}
