package com.hfkj.service.gas.impl;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.dao.BsGasClassGroupMapper;
import com.hfkj.entity.BsGasClassGroup;
import com.hfkj.entity.BsGasClassGroupExample;
import com.hfkj.service.gas.BsGasClassGroupService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

@Service("gasClassGroupService")
public class BsGasClassGroupServiceImpl implements BsGasClassGroupService {

    @Resource
    private BsGasClassGroupMapper gasClassGroupMapper;

    @Override
    public void editGroup(BsGasClassGroup gasClassGroup) {
        if (gasClassGroup.getId() == null) {
            gasClassGroup.setStatus(1);
            gasClassGroup.setCreateTime(new Date());
            gasClassGroup.setUpdateTime(new Date());
            gasClassGroupMapper.insert(gasClassGroup);
        } else {
            gasClassGroup.setUpdateTime(new Date());
            gasClassGroupMapper.updateByPrimaryKey(gasClassGroup);
        }
    }

    @Override
    public void delGroup(Long groupId) {
        BsGasClassGroup classGroup = getDetailById(groupId);
        if (classGroup == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到班组");
        }
        classGroup.setStatus(0);
        editGroup(classGroup);
    }

    @Override
    public BsGasClassGroup getDetailById(Long groupId) {
        return gasClassGroupMapper.selectByPrimaryKey(groupId);
    }

    @Override
    public List<BsGasClassGroup> getGroupList(Map<String, Object> param) {
        BsGasClassGroupExample example = new BsGasClassGroupExample();
        BsGasClassGroupExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(0);

        if (MapUtils.getLong(param, "merId") != null) {
            criteria.andMerIdEqualTo(MapUtils.getLong(param, "merId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "merName"))) {
            criteria.andMerNameLike("%" + MapUtils.getString(param, "merName") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "name"))) {
            criteria.andNameLike("%" + MapUtils.getString(param, "name") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "principalName"))) {
            criteria.andPrincipalNameLike("%" + MapUtils.getString(param, "principalName") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "principalPhone"))) {
            criteria.andPrincipalPhoneLike("%" + MapUtils.getString(param, "principalPhone") + "%");
        }

        example.setOrderByClause("create_time desc");
        return gasClassGroupMapper.selectByExample(example);
    }
}
