/*
 * 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.lawEnforcementSupervision.modular.lesInspectionResultCollect.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.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.common.util.DateUtil;
import com.unis.common.util.OrderNumberUtil;
import com.unis.lawEnforcementSupervision.modular.lesInspectionResultCollectItem.entity.LesInspectionResultCollectItem;
import com.unis.lawEnforcementSupervision.modular.lesInspectionResultCollectItem.mapper.LesInspectionResultCollectItemMapper;
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.lawEnforcementSupervision.modular.lesInspectionResultCollect.entity.LesInspectionResultCollect;
import com.unis.lawEnforcementSupervision.modular.lesInspectionResultCollect.mapper.LesInspectionResultCollectMapper;
import com.unis.lawEnforcementSupervision.modular.lesInspectionResultCollect.param.LesInspectionResultCollectAddParam;
import com.unis.lawEnforcementSupervision.modular.lesInspectionResultCollect.param.LesInspectionResultCollectEditParam;
import com.unis.lawEnforcementSupervision.modular.lesInspectionResultCollect.param.LesInspectionResultCollectIdParam;
import com.unis.lawEnforcementSupervision.modular.lesInspectionResultCollect.param.LesInspectionResultCollectPageParam;
import com.unis.lawEnforcementSupervision.modular.lesInspectionResultCollect.service.LesInspectionResultCollectService;

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

/**
 * 专项检查-检查结果采集汇总Service接口实现类
 *
 * @author QSHan
 * @date 2024/06/25 14:29
 **/
@Service
public class LesInspectionResultCollectServiceImpl extends ServiceImpl<LesInspectionResultCollectMapper, LesInspectionResultCollect> implements LesInspectionResultCollectService {
    @Resource
    private LesInspectionResultCollectMapper lesInspectionResultCollectMapper;
    @Resource
    private LesInspectionResultCollectItemMapper lesInspectionResultCollectItemMapper;

    @Override
    public Page<LesInspectionResultCollect> page(LesInspectionResultCollectPageParam lesInspectionResultCollectPageParam) {
        QueryWrapper<LesInspectionResultCollect> queryWrapper = new QueryWrapper<>();
        String taskName = lesInspectionResultCollectPageParam.getTaskName();
        if (StringUtils.isNotEmpty(taskName)) {
            queryWrapper.lambda().like(LesInspectionResultCollect::getTaskName, taskName);
        }
        String startTime = lesInspectionResultCollectPageParam.getStartTime();
        String endTime = lesInspectionResultCollectPageParam.getEndTime();
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            queryWrapper.lambda().between(LesInspectionResultCollect::getStartTime, startTime + DateUtil.startTime, endTime + DateUtil.endTime)
                    .or().between(LesInspectionResultCollect::getEndTime, startTime + DateUtil.startTime, endTime + DateUtil.endTime);
        }
        if (ObjectUtil.isAllNotEmpty(lesInspectionResultCollectPageParam.getSortField(), lesInspectionResultCollectPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(lesInspectionResultCollectPageParam.getSortOrder());
            queryWrapper.orderBy(true, lesInspectionResultCollectPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(lesInspectionResultCollectPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(LesInspectionResultCollect::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(LesInspectionResultCollectAddParam lesInspectionResultCollectAddParam) {
        LesInspectionResultCollect lesInspectionResultCollect = BeanUtil.toBean(lesInspectionResultCollectAddParam, LesInspectionResultCollect.class);
        // 查询任务编号
        String taskNumber = lesInspectionResultCollectMapper.selectTaskNumber();
        // 任务编号(JCJGCJ+年月日+5位顺序号)
        lesInspectionResultCollect.setTaskNumber(OrderNumberUtil.initNum("JCJGCJ", 3, taskNumber));
        this.save(lesInspectionResultCollect);
        // 保存子表数据
        if (CollectionUtils.isNotEmpty(lesInspectionResultCollectAddParam.getItems())) {
            lesInspectionResultCollectAddParam.getItems().forEach(item -> {
                item.setLesInspectionResultCollectId(lesInspectionResultCollect.getId());
                lesInspectionResultCollectItemMapper.insert(item);
            });
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(LesInspectionResultCollectEditParam lesInspectionResultCollectEditParam) {
        LesInspectionResultCollect lesInspectionResultCollect = this.queryEntity(lesInspectionResultCollectEditParam.getId());
        BeanUtil.copyProperties(lesInspectionResultCollectEditParam, lesInspectionResultCollect);
        this.updateById(lesInspectionResultCollect);
        // 修改子表
        if (CollectionUtils.isNotEmpty(lesInspectionResultCollectEditParam.getItems())) {
            // 先删除
            QueryWrapper<LesInspectionResultCollectItem> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(LesInspectionResultCollectItem::getLesInspectionResultCollectId, lesInspectionResultCollect.getId());
            lesInspectionResultCollectItemMapper.delete(wrapper);
            // 在新增
            lesInspectionResultCollectEditParam.getItems().forEach(item -> {
                item.setLesInspectionResultCollectId(lesInspectionResultCollect.getId());
                lesInspectionResultCollectItemMapper.insert(item);
            });
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<LesInspectionResultCollectIdParam> lesInspectionResultCollectIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(lesInspectionResultCollectIdParamList, LesInspectionResultCollectIdParam::getId));
        // 删除子表数据
        lesInspectionResultCollectIdParamList.forEach(ids -> {
            QueryWrapper<LesInspectionResultCollectItem> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(LesInspectionResultCollectItem::getLesInspectionResultCollectId, ids.getId());
            lesInspectionResultCollectItemMapper.delete(wrapper);
        });
    }

    @Override
    public LesInspectionResultCollect detail(LesInspectionResultCollectIdParam lesInspectionResultCollectIdParam) {
        LesInspectionResultCollect collect = this.queryEntity(lesInspectionResultCollectIdParam.getId());
        // 查询子表数据
        QueryWrapper<LesInspectionResultCollectItem> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(LesInspectionResultCollectItem::getLesInspectionResultCollectId, lesInspectionResultCollectIdParam.getId());
        List<LesInspectionResultCollectItem> items = lesInspectionResultCollectItemMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(items)) {
            collect.setItems(items);
        }
        return collect;
    }

    @Override
    public LesInspectionResultCollect queryEntity(String id) {
        LesInspectionResultCollect lesInspectionResultCollect = this.getById(id);
        if (ObjectUtil.isEmpty(lesInspectionResultCollect)) {
            throw new CommonException("专项检查-检查结果采集汇总不存在，id值为：{}", id);
        }
        return lesInspectionResultCollect;
    }
}
