package com.casic.missiles.service.Impl.equipment;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.dto.IdDTO;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.meter.MeterStaffMapper;
import com.casic.missiles.mapper.equipment.EquipmentStandardEquipmentUserMapper;
import com.casic.missiles.model.meter.MeterStaff;
import com.casic.missiles.model.equipment.EquipmentStandardEquipment;
import com.casic.missiles.model.equipment.EquipmentStandardEquipmentUser;
import com.casic.missiles.service.equipment.IEquipmentStandardEquipmentService;
import com.casic.missiles.service.equipment.IEquipmentStandardEquipmentUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 标准装置-计量人员表 服务实现类
 * </p>
 *
 * @author cuicheng
 * @since 2022-12-15
 */
@Service
public class EquipmentStandardEquipmentUserServiceImpl extends ServiceImpl<EquipmentStandardEquipmentUserMapper, EquipmentStandardEquipmentUser> implements IEquipmentStandardEquipmentUserService {

    @Autowired
    private EquipmentStandardEquipmentUserMapper meterStandardEquipmentUserMapper;

    @Autowired
    private MeterStaffMapper meterStaffMapper;

    @Autowired
    private IEquipmentStandardEquipmentService meterStandardEquipmentService;

    @Override
    public Page<EquipmentStandardEquipmentUser> listPage(Page<EquipmentStandardEquipmentUser> page, IdDTO request) throws Exception {
        // 获取列表
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("standard_equipment_id", request.getId());
        Page<EquipmentStandardEquipmentUser> equipmentUserPage = meterStandardEquipmentUserMapper.selectPage(page, wrapper);
        if (!CollectionUtils.isEmpty(equipmentUserPage.getRecords())) {
            for (EquipmentStandardEquipmentUser record : equipmentUserPage.getRecords()) {
                MeterStaff meterStaff = meterStaffMapper.selectStaffInfo(record.getUserId().toString());
                if(null != meterStaff){
                    BeanUtils.copyProperties(meterStaff, record);
                }
            }
            // 将已经不存在的计量人员排除
            equipmentUserPage.setRecords(equipmentUserPage.getRecords().stream().filter(item -> StringUtils.isNotEmpty(item.getStaffNo())).collect(Collectors.toList()));
            equipmentUserPage.setTotal(equipmentUserPage.getRecords().size());
        }
        return equipmentUserPage;
    }

    @Override
    public ReturnDTO add(EquipmentStandardEquipmentUser meterStandardEquipmentUser) throws Exception {
        // 人员信息校验
        validUserInfo(meterStandardEquipmentUser);
        // 首先判断是否存在，不存在再插入
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("standard_equipment_id", meterStandardEquipmentUser.getStandardEquipmentId());
        wrapper.eq("user_id", meterStandardEquipmentUser.getUserId());
        EquipmentStandardEquipmentUser existUser = meterStandardEquipmentUserMapper.selectOne(wrapper);
        if (existUser == null) {
            meterStandardEquipmentUserMapper.insert(meterStandardEquipmentUser);
        }
        return ReturnUtil.success();
    }

    @Override
    public ReturnDTO deleteById(Long id) {
        super.removeById(id);
        return ReturnUtil.success();
    }

    @Override
    public ReturnDTO batchDelete(List<Long> ids) {
        super.removeBatchByIds(ids);
        return ReturnUtil.success();
    }

    @Override
    public List<EquipmentStandardEquipmentUser> list(Long id) throws Exception {
        // 获取列表
        QueryWrapper<EquipmentStandardEquipmentUser> wrapper = new QueryWrapper();
        wrapper.eq("standard_equipment_id", id);
        List<EquipmentStandardEquipmentUser> equipmentUserList = meterStandardEquipmentUserMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(equipmentUserList)) {
            for (EquipmentStandardEquipmentUser record : equipmentUserList) {
                MeterStaff meterStaff = meterStaffMapper.selectStaffInfo(record.getUserId().toString());
                if(null != meterStaff){
                    meterStaff.setId(record.getId());
                    BeanUtils.copyProperties(meterStaff, record);
                }
            }
        }
        return equipmentUserList.stream().filter(item -> StringUtils.isNotEmpty(item.getStaffNo())).collect(Collectors.toList());
    }

    @Override
    public ReturnDTO addList(List<EquipmentStandardEquipmentUser> meterStandardEquipmentUserList) throws Exception {
        // 校验计量人员信息
        List<EquipmentStandardEquipmentUser> needInsertList = new ArrayList<>();
        for(EquipmentStandardEquipmentUser item:meterStandardEquipmentUserList) {
            validUserInfo(item);
            if (!isExist(item)) {
                needInsertList.add(item);
            }
        }
        if (!CollectionUtils.isEmpty(needInsertList)) {
            super.saveBatch(needInsertList);
        }
        return ReturnUtil.success();
    }

    private boolean validUserInfo(EquipmentStandardEquipmentUser meterStandardEquipmentUser) throws Exception {
        // 判断标准装置是否存在
        EquipmentStandardEquipment meterStandardEquipment = meterStandardEquipmentService.getById(meterStandardEquipmentUser.getStandardEquipmentId());
        if (meterStandardEquipment == null) {
            throw new BusinessException(BusinessExceptionEnum.STANDARD_EQUIPMENT_ID_EXIST);
        }
        // 判断人员是否存在
        MeterStaff meterStaff = meterStaffMapper.selectStaffInfo(meterStandardEquipmentUser.getUserId().toString());
        if (meterStaff == null) {
            throw new BusinessException(BusinessExceptionEnum.STANDARD_EQUIPMENT_USER_ID_EXIST);
        }
        return true;
    }

    private boolean isExist(EquipmentStandardEquipmentUser meterStandardEquipmentUser) {
        // 首先判断是否存在，不存在再插入
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("standard_equipment_id", meterStandardEquipmentUser.getStandardEquipmentId());
        wrapper.eq("user_id", meterStandardEquipmentUser.getUserId());
        return meterStandardEquipmentUserMapper.selectOne(wrapper) != null;
    }
}
