package com.jiayue.ssi.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiayue.ssi.backenum.ApproveOperaterEnum;
import com.jiayue.ssi.backenum.ApproveStatusEnum;
import com.jiayue.ssi.constant.ApproveConstants;
import com.jiayue.ssi.constant.CustomException;
import com.jiayue.ssi.entity.SysApprove;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.mapper.SysApproveMapper;
import com.jiayue.ssi.mapper.SysUserMapper;
import com.jiayue.ssi.service.SysApproveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
* 审核实现类
*
* @author xsl
* @since 2023/03/29
*/
@Service
public class SysApproveServiceImpl extends ServiceImpl<SysApproveMapper, SysApprove> implements SysApproveService {
    @Autowired
    SysUserMapper sysUserMapper;

    /**
     * 审核提交
     * @param sysApprove
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public void submitApprove(SysApprove sysApprove) throws CustomException {
        SysApprove newsysApprove = this.getById(sysApprove.getId());
        newsysApprove.setApproveStatus(ApproveStatusEnum.YSP.getCode() + "");
        newsysApprove.setApproveResult(sysApprove.getApproveResult());
        this.updateById(newsysApprove);

        if ("0".equals(newsysApprove.getApproveResult())){
            // 审核通过，执行业务操作。
            if (newsysApprove.getModuleName().equals(ApproveConstants.MODULE_NAME_USER)){
                SysUser sysUser = JSONUtil.toBean(newsysApprove.getParameterContent(),SysUser.class);
                if (newsysApprove.getOperation().equals(String.valueOf(ApproveOperaterEnum.DELETE.getCode()))){
                    // 用户管理删除操作
                    LambdaUpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<SysUser>().lambda();
                    updateWrapper.eq(SysUser::getId, sysUser.getId()).set(SysUser::getDelFlag, 1);
                    sysUserMapper.update(new SysUser(), updateWrapper);
                }
            }
        }
    }
}
