package com.njcn.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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 com.njcn.common.pojo.constant.PatternRegex;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.system.enums.EventResponseEnum;
import com.njcn.system.mapper.EventTemplateMapper;
import com.njcn.system.mapper.TemplateRelMapper;
import com.njcn.system.pojo.param.EventTemplateParam;
import com.njcn.system.pojo.po.EventTemplate;
import com.njcn.system.pojo.po.TemplateRel;
import com.njcn.system.pojo.vo.EventReportDictVO;
import com.njcn.system.pojo.vo.EventTemplateVO;
import com.njcn.system.service.IEventTemplateService;
import com.njcn.web.factory.PageFactory;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static java.util.regex.Pattern.*;

/**
 * @author: hany
 * @date: 2022/09/07
 * @Description: <描述>
 */
@Service
@AllArgsConstructor
public class EventTemplateServiceImpl extends ServiceImpl<EventTemplateMapper, EventTemplate> implements IEventTemplateService {

    private final TemplateRelMapper templateRelMapper;

    /**
     * 查询所有模板
     *
     * @author hany
     * @date 2022/09/13
     */
    @Override
    public Page<EventTemplateVO> getList(EventTemplateParam.EventTemplateQueryParam queryParam) {
        QueryWrapper<EventTemplateVO> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(queryParam)) {
            //查询参数不为空，进行条件填充
            if (StrUtil.isNotBlank(queryParam.getSearchValue())) {
                //根据名称模糊查询
                queryWrapper
                        .and(param -> param.like("report_template.name", queryParam.getSearchValue()));
            }
        }
        queryWrapper.ne("report_template.state", DataStateEnum.DELETED.getCode());
        if (queryParam.getType().equals(0)) {
            queryWrapper.in("report_template.type", 0);
        } else if (queryParam.getType().equals(1)) {
            queryWrapper.eq("report_template.type", 1);
        }
        //初始化分页数据
        Page<EventTemplateVO> page = this.baseMapper.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper);
        List<String> list = page.getRecords().stream().map(EventTemplateVO::getId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(list)) {
            throw new BusinessException("查询模板为空");
        }
        List<TemplateRel> templateRels = templateRelMapper.selectRelevance(list);
        if (CollectionUtil.isNotEmpty(templateRels)) {
            Map<String, List<TemplateRel>> temMap = templateRels.stream().collect(Collectors.groupingBy(TemplateRel::getRtId));
            for (EventTemplateVO record : page.getRecords()) {
                if (Objects.nonNull(temMap.get(record.getId()))) {
                    record.setRdIds(temMap.get(record.getId()).stream().map(TemplateRel::getRdId).collect(Collectors.toList()));
                }

            }
        }

        return page;
    }

    /**
     * 根据id查询模板数据
     *
     * @author hany
     * @date 2022/09/26
     */
    @Override
    public EventTemplate getTemplateById(String id) {
        return this.getById(id);
    }

    /**
     * 新增模板
     *
     * @author hany
     * @date 2022/09/08
     */
    @Override
    public boolean add(EventTemplateParam eventTemplateParam) {
        checkName(eventTemplateParam, true);
        EventTemplate eventTemplate = new EventTemplate();
        BeanUtils.copyProperties(eventTemplateParam, eventTemplate);
        //设为正常状态
        eventTemplate.setState(DataStateEnum.ENABLE.getCode());
        this.save(eventTemplate);
        String id = eventTemplate.getId();
        List<TemplateRel> list = new ArrayList<>();
        eventTemplateParam.getIds().forEach(rdId -> {
            TemplateRel relevancy = new TemplateRel();
            // 字典表id
            relevancy.setRtId(id);
            relevancy.setRdId(rdId);
            list.add(relevancy);
        });
        return templateRelMapper.batchInsert(list);
    }

    /**
     * 修改模板
     */
    @Override
    public boolean update(EventTemplateParam.EventTemplateUpdateParam eventTemplateUpdateParam) {
        checkName(eventTemplateUpdateParam, false);
        String id = eventTemplateUpdateParam.getId();
        EventTemplate eventTemplate = new EventTemplate();
        BeanUtils.copyProperties(eventTemplateUpdateParam, eventTemplate);
        boolean flag = this.updateById(eventTemplate);
        // 先删除字典表
        templateRelMapper.deleteByRtId(id);
        if (CollUtil.isNotEmpty(eventTemplateUpdateParam.getIds())) {
            List<TemplateRel> list = new ArrayList<>();
            eventTemplateUpdateParam.getIds().forEach(rdId -> {
                TemplateRel relevancy = new TemplateRel();
                // 模版id
                relevancy.setRtId(id);
                relevancy.setRdId(rdId);
                list.add(relevancy);
            });
            if (CollUtil.isNotEmpty(list)) {
                flag = templateRelMapper.batchInsert(list);
            }
        }


        return flag;
    }


    @Override
    public boolean delete(List<String> ids) {
        //删除模板与字典的关系
        this.baseMapper.deleteRelevancy(ids);
        return this.lambdaUpdate().set(EventTemplate::getState, DataStateEnum.DELETED.getCode()).in(EventTemplate::getId, ids).update();
    }


    @Override
    public Boolean selectRelevance(List<String> ids) {
        //判断模板是否和字典绑定
        List<TemplateRel> templateRel = this.templateRelMapper.selectRelevance(ids);
        return !templateRel.isEmpty();
    }

    @Override
    public List<EventReportDictVO> selectRelation(String id) {
        List<EventReportDictVO> list = new ArrayList<>();
        List<String> configs = templateRelMapper.selectReleation(id);
        configs = configs.stream().filter(t -> !isContainChinese(t)).collect(Collectors.toList());
        configs.forEach(config -> {
            EventReportDictVO eventReportDictVO = new EventReportDictVO();
            eventReportDictVO.setName(config);
            eventReportDictVO.setFlag(true);
            list.add(eventReportDictVO);
        });
        return list;
    }

    /**
     * 字符串是否包含中文
     *
     * @param str 待校验字符串
     * @return true 包含中文字符 false 不包含中文字符
     */
    public static boolean isContainChinese(String str) {
        Pattern p = compile(PatternRegex.CHINESE_REGEX);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * 名称重复校验
     */
    private void checkName(EventTemplateParam eventTemplateParam, boolean flag) {
        LambdaQueryWrapper<EventTemplate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EventTemplate::getName, eventTemplateParam.getName())
                .eq(EventTemplate::getType, eventTemplateParam.getType());
        //修改
        if (!flag) {
            if (eventTemplateParam instanceof EventTemplateParam.EventTemplateUpdateParam) {
                lambdaQueryWrapper.ne(EventTemplate::getId, ((EventTemplateParam.EventTemplateUpdateParam) eventTemplateParam).getId());
            }
        }
        int result = this.count(lambdaQueryWrapper);
        //大于等于1个则表示重复
        if (result >= 1) {
            throw new BusinessException(EventResponseEnum.MODEL_NAME_REPEAT);
        }

    }
}
