package com.njcn.gather.script.service.impl;

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.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.script.mapper.PqScriptMapper;
import com.njcn.gather.script.pojo.param.PqScriptParam;
import com.njcn.gather.script.pojo.po.PqScript;
import com.njcn.gather.script.service.IPqScriptCheckDataService;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.script.service.IPqScriptService;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author caozehui
 * @date 2024-11-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PqScriptServiceImpl extends ServiceImpl<PqScriptMapper, PqScript> implements IPqScriptService {

    private final IPqScriptDtlsService pqScriptDtlsService;
    private final IPqScriptCheckDataService pqScriptCheckDataService;

    @Override
    public Page<PqScript> listPqScript(PqScriptParam.QueryParam param) {
        QueryWrapper<PqScript> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(param)) {
            queryWrapper.like(StrUtil.isNotBlank(param.getName()), "pq_script.name", param.getName())
                    .eq(ObjectUtil.isNotNull(param.getType()), "pq_script.type", param.getType())
                    .eq(StrUtil.isNotBlank(param.getValueType()), "pq_script.Value_Type", param.getValueType())
                    .eq(StrUtil.isNotBlank(param.getPattern()), "pq_script.pattern", param.getPattern());
        }
        queryWrapper.eq("pq_script.state", DataStateEnum.ENABLE.getCode()).orderByAsc("pq_script.create_time");
        return this.page(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), queryWrapper);
    }

    @Override
    public PqScript getPqScriptById(String id) {
        return this.lambdaQuery().eq(PqScript::getId, id).eq(PqScript::getState, DataStateEnum.ENABLE.getCode()).one();
    }

    @Override
    @Transactional
    public String addPqScript(PqScriptParam param) {
        param.setName(param.getName().trim());
        this.checkRepeat(param, false);
        PqScript pqScript = new PqScript();
        BeanUtils.copyProperties(param, pqScript);
        pqScript.setStandardTime(LocalDate.of(Integer.parseInt(param.getStandardTime()), 1, 1));
        pqScript.setState(DataStateEnum.ENABLE.getCode());
        this.save(pqScript);
        return pqScript.getId();
    }

    @Override
    @Transactional
    public boolean updatePqScript(PqScriptParam.UpdateParam param) {
        param.setName(param.getName().trim());
        this.checkRepeat(param, true);
        PqScript pqScript = new PqScript();
        BeanUtils.copyProperties(param, pqScript);
        pqScript.setStandardTime(LocalDate.of(Integer.parseInt(param.getStandardTime()), 1, 1));
        pqScript.setState(DataStateEnum.ENABLE.getCode());
        return this.updateById(pqScript);
    }

    @Override
    @Transactional
    public boolean deletePqScript(List<String> ids) {
        Integer count = this.baseMapper.getBoundCountByScriptIds(ids);
        if (count > 0) {
            throw new BusinessException(DetectionResponseEnum.SCRIPT_BOUND_NOT_DELETE);
        }
        //删除对应的脚本详情
        pqScriptDtlsService.deletePqScriptDtlsByScriptId(ids);
        //删除对应的checkdata
        pqScriptCheckDataService.deleteByScriptIds(ids);
        LambdaUpdateWrapper<PqScript> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(PqScript::getState, DataStateEnum.DELETED.getCode())
                .in(PqScript::getId, ids);
        return this.update(updateWrapper);
    }

    @Override
    @Transactional
    public boolean upgradeToTemplate(String id) {
        PqScript pqScript = this.lambdaQuery().eq(PqScript::getId, id).one();
        if (pqScript != null) {
            pqScript.setType(1);
            return this.updateById(pqScript);
        }
        return false;
    }

    @Override
    public List<PqScript> listAllPqScript(String patternId) {
        List<PqScript> pqScriptList = this.lambdaQuery().eq(StrUtil.isNotBlank(patternId), PqScript::getPattern, patternId).eq(PqScript::getState, DataStateEnum.ENABLE.getCode()).list();
//        List<Map<String, Object>> result = pqScriptList.stream().map(pqScript -> {
//            Map<String, Object> map = new HashMap<>();
//            map.put("id", pqScript.getId());
//            map.put("name", pqScript.getName());
//            return map;
//        }).collect(Collectors.toList());
        return pqScriptList;
    }

    @Override
    public PqScript getPqScriptByName(String name) {
        return this.lambdaQuery().eq(PqScript::getName, name).eq(PqScript::getState, DataStateEnum.ENABLE.getCode()).one();
    }

    /**
     * 检查脚本是否重复
     *
     * @param param         计划参数
     * @param isExcludeSelf 是否排除自己
     */
    private void checkRepeat(PqScriptParam param, boolean isExcludeSelf) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("state", DataStateEnum.ENABLE.getCode());
        wrapper.eq("name", param.getName());
        if (isExcludeSelf) {
            if (param instanceof PqScriptParam.UpdateParam) {
                wrapper.ne("id", ((PqScriptParam.UpdateParam) param).getId());
            }
        }
        int count = this.count(wrapper);
        if (count > 0) {
            throw new BusinessException(DetectionResponseEnum.SCRIPT_NAME_REPEAT);
        }
    }
}
