package com.njzscloud.supervisory.biz.service;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.supervisory.biz.contant.AuditStatus;
import com.njzscloud.supervisory.biz.mapper.BizProjectMapper;
import com.njzscloud.supervisory.biz.pojo.entity.BizProjectEntity;
import com.njzscloud.supervisory.biz.pojo.result.SearchBizProjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 项目信息
 */
@Slf4j
@Service
public class BizProjectService extends ServiceImpl<BizProjectMapper, BizProjectEntity> implements IService<BizProjectEntity> {

    /**
     * 新增
     */
    public void add(BizProjectEntity bizProjectEntity) {
        this.save(bizProjectEntity.setAuditStatus(AuditStatus.DaiShenHe));
    }

    /**
     * 修改
     */
    public void modify(BizProjectEntity bizProjectEntity) {
        this.updateById(bizProjectEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     */
    public BizProjectEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     */
    public PageResult<SearchBizProjectResult> paging(PageParam pageParam, BizProjectEntity bizProjectEntity) {
        return PageResult.of(baseMapper.paging(pageParam.toPage(), Wrappers.<BizProjectEntity>query(bizProjectEntity)));
    }

    @Transactional(rollbackFor = Exception.class)
    public void audit(Long id, AuditStatus auditStatus, String auditMemo) {
        Assert.isTrue(auditStatus == AuditStatus.TongGuo || auditStatus == AuditStatus.BoHui, "错误的审核状态");
        BizProjectEntity oldData = getById(id);
        if (oldData == null) {
            throw Exceptions.exception("未找到要审核的数据");
        }
        if (oldData.getAuditStatus() != AuditStatus.DaiShenHe) {
            throw Exceptions.exception("当前状态不能审核");
        }
        boolean updated = update(Wrappers.<BizProjectEntity>lambdaUpdate()
                .set(BizProjectEntity::getAuditStatus, auditStatus)
                .set(BizProjectEntity::getAuditMemo, auditStatus == AuditStatus.TongGuo ? "" : auditMemo)
                .eq(BizProjectEntity::getId, id)
                .eq(BizProjectEntity::getAuditStatus, AuditStatus.DaiShenHe));
        if (!updated) {
            throw Exceptions.exception("数据状态已改变，无法审核");
        }
    }
}
