/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.comm.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tofly.api.UserClent;
import com.tofly.gpsboot.common.system.AuditSateEnum;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.comm.vo.AuditVo;
import com.tofly.gpsboot.mapper.comm.AuditMapper;
import com.tofly.gpsboot.service.comm.IAuditService;
import com.tofly.pojo.comm.Audit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;


/**
 * 审批表
 *
 * @author zev
 * @date Fri May 21 00:00:00 CST 2021
 */
@Service("auditService")
public class AuditServiceImpl extends ServiceImpl<AuditMapper, Audit> implements IAuditService {
    @Autowired
    private UserClent userClent;

    @Override
    public List<AuditVo> viewConversion(List<Audit> infoList) {
        List<AuditVo> voList = new ArrayList<>();
        infoList.forEach(info->{
            AuditVo vo = JSONObject.parseObject(JSON.toJSONString(info),AuditVo.class);
            // 添加审核人名称 转换审核状态
            if(null!=info.getAuditTime()){
               vo.setAuditTimeStr(DateTimeUtil.getLocalDateTime(DateTimeUtil.fromLong2LocalDateTime(info.getAuditTime().getTime()),DateTimeUtil.FULL_FORMAT));
            }
            vo.setAuditState(AuditSateEnum.getCodeForValue(info.getAuditState()));
            voList.add(vo);
        });
        return voList;
    }

    @Override
    public Audit getNextAudit(List<Audit> list,Integer auditLevel){
        AtomicReference<Audit> audit = new AtomicReference<>();
        AtomicBoolean flag = new AtomicBoolean(true);
        list.forEach(info ->{
            if(flag.get()){
                if(auditLevel<info.getAuditLevel()){
                    // 判断是否传入审核人
                    if(null!=info.getAuditUser()){
                        audit.set(info);
                        flag.set(false);
                    }else {
                        // 修改当前对象的审核状态为待审核
                        info.setAuditState(AuditSateEnum.AUDIT_UNCOMMITTED.getCode());
                        this.updateById(info);
                    }
                }
            }
        });
        return audit.get();
    }
}
