package com.fjhx.service.abnormal.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.Condition;
import com.fjhx.constants.StatusConstant;
import com.fjhx.entity.abnormal.AbnormalDetails;
import com.fjhx.entity.abnormal.AbnormalInfo;
import com.fjhx.mapper.abnormal.AbnormalDetailsMapper;
import com.fjhx.params.abnormal.AbnormalDetailsVo;
import com.fjhx.service.abnormal.AbnormalDetailsService;
import com.fjhx.service.abnormal.AbnormalInfoService;
import com.fjhx.utils.Assert;
import com.fjhx.utils.UserClientUtil;
import com.fjhx.utils.wrapperUtil.IWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 异常处理详情 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-12-09
 */
@Service
public class AbnormalDetailsServiceImpl extends ServiceImpl<AbnormalDetailsMapper, AbnormalDetails> implements AbnormalDetailsService {

    @Autowired
    private AbnormalInfoService abnormalInfoService;

    @Override
    public Page<Map<String, Object>> getPage(Condition condition) {
        Long abnormalInfoId = condition.getLong("abnormalInfoId", "异常管理id不能为空");

        IWrapper<AbnormalDetails> wrapper = IWrapper.getWrapper(condition);
        wrapper.eq(AbnormalDetails::getAbnormalInfoId, abnormalInfoId);

        Page<Map<String, Object>> page = pageMaps(condition, wrapper);
        List<Map<String, Object>> records = page.getRecords();

        if (records.size() == 0) {
            return page;
        }

        UserClientUtil.setUserName(records, "createUser", "createUserName");

        return page;
    }

    @Override
    public void add(AbnormalDetailsVo abnormalDetailsVo) {
        Long abnormalInfoId = abnormalDetailsVo.getAbnormalInfoId();
        Assert.notEmpty(abnormalInfoId, "异常管理id不能为空");
        Assert.notEmpty(abnormalDetailsVo.getExplain(), "异常说明不能为空");

        Integer status = abnormalDetailsVo.getStatus();

        if (StatusConstant.YES.equals(status)) {
            AbnormalInfo abnormalInfo = new AbnormalInfo();
            abnormalInfo.setId(abnormalInfoId);
            abnormalInfo.setStatus(StatusConstant.YES);
            abnormalInfoService.updateById(abnormalInfo);
        }

        save(abnormalDetailsVo);
    }

    @Override
    public void edit(AbnormalDetailsVo abnormalDetailsVo) {
        updateById(abnormalDetailsVo);
    }

    @Override
    public void delete(AbnormalDetailsVo abnormalDetailsVo) {
        removeById(abnormalDetailsVo.getId());
    }

}
