/*
 * 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.lesJointInspectionTask.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.ObjectUtils;
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.lawEnforcementSupervision.modular.lesJointInspectionTaskItem.entity.LesJointInspectionTaskItem;
import com.unis.lawEnforcementSupervision.modular.lesJointInspectionTaskItem.mapper.LesJointInspectionTaskItemMapper;
import com.unis.policy.info.modular.auditRecord.entity.AuditRecord;
import com.unis.policy.info.modular.auditRecord.mapper.AuditRecordMapper;
import com.unis.policy.info.modular.auditRequest.entity.AuditRequest;
import com.unis.policy.info.modular.auditRequest.mapper.AuditRequestMapper;
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.lesJointInspectionTask.entity.LesJointInspectionTask;
import com.unis.lawEnforcementSupervision.modular.lesJointInspectionTask.mapper.LesJointInspectionTaskMapper;
import com.unis.lawEnforcementSupervision.modular.lesJointInspectionTask.param.LesJointInspectionTaskAddParam;
import com.unis.lawEnforcementSupervision.modular.lesJointInspectionTask.param.LesJointInspectionTaskEditParam;
import com.unis.lawEnforcementSupervision.modular.lesJointInspectionTask.param.LesJointInspectionTaskIdParam;
import com.unis.lawEnforcementSupervision.modular.lesJointInspectionTask.param.LesJointInspectionTaskPageParam;
import com.unis.lawEnforcementSupervision.modular.lesJointInspectionTask.service.LesJointInspectionTaskService;

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

/**
 * 联合检查-联合检查任务Service接口实现类
 *
 * @author QSHan
 * @date 2024/06/25 17:13
 **/
@Service
public class LesJointInspectionTaskServiceImpl extends ServiceImpl<LesJointInspectionTaskMapper, LesJointInspectionTask> implements LesJointInspectionTaskService {
    @Resource
    private LesJointInspectionTaskItemMapper lesJointInspectionTaskItemMapper;
    @Resource
    private LesJointInspectionTaskMapper lesJointInspectionTaskMapper;
    // 流程主表
    @Resource
    private AuditRequestMapper auditRequestMapper;
    // 流程记录
    @Resource
    private AuditRecordMapper auditRecordMapper;

    @Override
    public Page<LesJointInspectionTask> page(LesJointInspectionTaskPageParam lesJointInspectionTaskPageParam) {
        QueryWrapper<LesJointInspectionTask> queryWrapper = new QueryWrapper<>();
        // 检查任务名称
        if (StringUtils.isNotEmpty(lesJointInspectionTaskPageParam.getInspectionTaskName())) {
            queryWrapper.lambda().like(LesJointInspectionTask::getInspectionTaskName, lesJointInspectionTaskPageParam.getInspectionTaskName());
        }
        // 检查任务审核,查询状态非0的数据(状态 0：保存状态；1：发布（申请中）；2：审核通过；3：驳回)
        if (ObjectUtils.isNotEmpty(lesJointInspectionTaskPageParam.getStatus())) {
            if (0 != lesJointInspectionTaskPageParam.getStatus()) {
                queryWrapper.lambda().ne(LesJointInspectionTask::getStatus, 0);
            }
        }
        if (ObjectUtil.isAllNotEmpty(lesJointInspectionTaskPageParam.getSortField(), lesJointInspectionTaskPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(lesJointInspectionTaskPageParam.getSortOrder());
            queryWrapper.orderBy(true, lesJointInspectionTaskPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(lesJointInspectionTaskPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(LesJointInspectionTask::getId);
        }
        return lesJointInspectionTaskMapper.pageList(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(LesJointInspectionTaskAddParam lesJointInspectionTaskAddParam) {
        LesJointInspectionTask lesJointInspectionTask = BeanUtil.toBean(lesJointInspectionTaskAddParam, LesJointInspectionTask.class);
        this.save(lesJointInspectionTask);
        if (CollectionUtils.isNotEmpty(lesJointInspectionTaskAddParam.getItems())) {
            // 保存子表关联数据
            this.insertChild(lesJointInspectionTask);
        }
        // 添加审批
        this.audit(lesJointInspectionTask);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(LesJointInspectionTaskEditParam lesJointInspectionTaskEditParam) {
        LesJointInspectionTask lesJointInspectionTask = this.queryEntity(lesJointInspectionTaskEditParam.getId());
        BeanUtil.copyProperties(lesJointInspectionTaskEditParam, lesJointInspectionTask);
        this.updateById(lesJointInspectionTask);
        if (CollectionUtils.isNotEmpty(lesJointInspectionTask.getItems())) {
            // 先删除
            this.deleteChild(lesJointInspectionTask.getId());
            // 在新增
            this.insertChild(lesJointInspectionTask);
        }
        // 添加审批
        this.audit(lesJointInspectionTask);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<LesJointInspectionTaskIdParam> lesJointInspectionTaskIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(lesJointInspectionTaskIdParamList, LesJointInspectionTaskIdParam::getId));
        // 删除子表关联数据
        lesJointInspectionTaskIdParamList.forEach(ids -> this.deleteChild(ids.getId()));
    }

    @Override
    public LesJointInspectionTask detail(LesJointInspectionTaskIdParam lesJointInspectionTaskIdParam) {
        LesJointInspectionTask lesJointInspectionTask = this.queryEntity(lesJointInspectionTaskIdParam.getId());
        // 查询子表关联数据
        List<LesJointInspectionTaskItem> items = lesJointInspectionTaskItemMapper.selectList(this.queryObject(lesJointInspectionTask.getId()));
        if (CollectionUtils.isNotEmpty(items)) {
            lesJointInspectionTask.setItems(items);
        }
        // 查询审批意见
        QueryWrapper<AuditRequest> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AuditRequest::getRequestId, lesJointInspectionTask.getId());
        wrapper.lambda().eq(AuditRequest::getType, 12);
        wrapper.lambda().eq(AuditRequest::getStep, 12);
        AuditRequest request = auditRequestMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(request)) {
            lesJointInspectionTask.setAuditAdvice(request.getAuditAdvice());
        }
        return lesJointInspectionTask;
    }

    @Override
    public LesJointInspectionTask queryEntity(String id) {
        LesJointInspectionTask lesJointInspectionTask = this.getById(id);
        if (ObjectUtil.isEmpty(lesJointInspectionTask)) {
            throw new CommonException("联合检查-联合检查任务不存在，id值为：{}", id);
        }
        return lesJointInspectionTask;
    }

    // 新增关联主表数据
    private void insertChild(LesJointInspectionTask lesJointInspectionTask) {
        lesJointInspectionTask.getItems().forEach(item -> {
            item.setLesJointInspectionTaskId(lesJointInspectionTask.getId());
            // 保存子表关联数据
            lesJointInspectionTaskItemMapper.insert(item);
        });
    }

    // 删除关联主表数据
    private void deleteChild(String lesJointInspectionTaskId) {
        lesJointInspectionTaskItemMapper.delete(this.queryObject(lesJointInspectionTaskId));
    }

    // 条件对象
    private QueryWrapper<LesJointInspectionTaskItem> queryObject(String lesJointInspectionTaskId) {
        QueryWrapper<LesJointInspectionTaskItem> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(LesJointInspectionTaskItem::getLesJointInspectionTaskId, lesJointInspectionTaskId);
        return wrapper;
    }

    // 流程
    private void audit(LesJointInspectionTask lesJointInspectionTask) {
        // 状态 0：保存状态；1：发布（申请中）；2：审核通过；3：驳回
        Integer status = lesJointInspectionTask.getStatus();
        if (1 == status) {
            // 判断驳回在提交
            if (StringUtils.isEmpty(lesJointInspectionTask.getId())) {
                // 添加审批(状态 0：待审核；1：已审核；2：驳回)
                AuditRequest request = this.addAuditRequest(lesJointInspectionTask);
                // 添加审批流程记录
                this.addAuditRecord(lesJointInspectionTask, request.getId(), 0);
            } else {
                this.editAuditRequest(lesJointInspectionTask, 0);
            }
        } else if (2 == status) {
            this.editAuditRequest(lesJointInspectionTask, 1);
        } else if (3 == status) {
            this.editAuditRequest(lesJointInspectionTask, 2);
        }
    }

    // 新增流程主表关联数据
    private AuditRequest addAuditRequest(LesJointInspectionTask lesJointInspectionTask) {
        AuditRequest request = new AuditRequest();
        request.setType(12);
        request.setStep(12);
        request.setRequestId(lesJointInspectionTask.getId());
        // 状态 0：待审核；1：已审核；2：驳回
        request.setAuditStatus(0);
        request.setAuditAdvice(lesJointInspectionTask.getAuditAdvice());
        request.setAuditUserId(lesJointInspectionTask.getAuditUserId());
        auditRequestMapper.insert(request);
        return request;
    }

    // 增加一条流程记录
    private void addAuditRecord(LesJointInspectionTask lesJointInspectionTask, String requestId, Integer status) {
        AuditRecord record = new AuditRecord();
        record.setAuditRequestId(requestId);
        record.setType(12);
        record.setStep(12);
        record.setRequestId(lesJointInspectionTask.getId());
        // 状态 0：待审核；1：已审核；2：驳回
        record.setAuditStatus(status);
        record.setAuditAdvice(lesJointInspectionTask.getAuditAdvice());
        record.setAuditUserId(lesJointInspectionTask.getAuditUserId());
        auditRecordMapper.insert(record);
    }

    // 更新流程主表关联数据
    private void editAuditRequest(LesJointInspectionTask lesJointInspectionTask, Integer status) {
        QueryWrapper<AuditRequest> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AuditRequest::getRequestId, lesJointInspectionTask.getId());
        AuditRequest request = new AuditRequest();
        // 状态 0：待审核；1：已审核；2：驳回
        request.setAuditStatus(status);
        request.setAuditAdvice(lesJointInspectionTask.getAuditAdvice());
        request.setAuditUserId(lesJointInspectionTask.getAuditUserId());
        auditRequestMapper.update(request, wrapper);

        // 新增流程记录
        this.addAuditRecord(lesJointInspectionTask, lesJointInspectionTask.getId(), status);
    }
}
