package com.ruoyi.ibs.draw.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ibs.draw.domain.dto.PassAuditDTO;
import com.ruoyi.ibs.draw.domain.entity.DrawLayerAudit;
import com.ruoyi.ibs.draw.domain.entity.DrawShape;
import com.ruoyi.ibs.draw.mapper.DrawLayerAuditMapper;
import com.ruoyi.ibs.draw.mapper.DrawShapeMapper;
import com.ruoyi.ibs.draw.service.DrawLayerAuditService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class DrawLayerAuditServiceImpl implements DrawLayerAuditService {

    @Resource
    DrawLayerAuditMapper mapper;

    @Resource
    DrawShapeMapper drawShapeMapper;

    @Override
    public List<DrawLayerAudit> selectAuditList() {
        String deptOps = SecurityUtils.getOpsDept();
        return mapper.selectList(new LambdaQueryWrapper<DrawLayerAudit>()
                .eq(DrawLayerAudit::getOpsDept, deptOps)
                .eq(DrawLayerAudit::getDeleteStatus, "0")
                .orderByDesc(DrawLayerAudit::getCreateTime));
    }

    @Override
    public Long selectAuditCount() {
        String deptOps = SecurityUtils.getOpsDept();
        return mapper.selectCount(new LambdaQueryWrapper<DrawLayerAudit>()
                .eq(DrawLayerAudit::getOpsDept, deptOps)
                .eq(DrawLayerAudit::getDeleteStatus, "0")
                .orderByDesc(DrawLayerAudit::getCreateTime));
    }

    @Override
    @Transactional
    public String passAudit( List<PassAuditDTO> passAuditDTOs) throws Exception {
        int num = 0;
        for (PassAuditDTO passAuditDTO:passAuditDTOs
             ) {
            DrawShape drawShape = drawShapeMapper.selectById(passAuditDTO.getShapeId());
            //更新区域状态以及审批意见
            drawShape.setAuditStatus(passAuditDTO.getAuditStatus());
            drawShape.setAuditRemark(passAuditDTO.getAuditRemark());
            drawShapeMapper.updateById(drawShape);
            DrawLayerAudit drawLayerAudit = mapper.selectOne(new LambdaQueryWrapper<DrawLayerAudit>()
                    .eq(DrawLayerAudit::getLayerId, passAuditDTO.getLayerId())
                    .eq(DrawLayerAudit::getShapeId, passAuditDTO.getShapeId())
                    .eq(DrawLayerAudit::getDeleteStatus, "0"));
            if (drawLayerAudit != null) {
                drawLayerAudit.setDeleteStatus(1);
                num += mapper.updateById(drawLayerAudit);
            }

        }
        if(num<passAuditDTOs.size()){
            throw new Exception("审批出错，请重试");
        }
        return "操作成功";
    }


}
