package com.ruoyi.interfaces.service.impl;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.ruoyi.interfaces.core.page.Page;
import com.ruoyi.interfaces.core.page.PageUtils;
import com.ruoyi.interfaces.domain.PtServiceParamKey;
import com.ruoyi.interfaces.domain.PtServiceReturn;
import com.ruoyi.interfaces.mapper.PtServiceReturnMapper;
import com.ruoyi.interfaces.service.PtServiceReturnService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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

/**
 * @author LinQiLong
 * @date 2022/1/26 11:37
 */
@Service
public class PtServiceReturnServiceImpl implements PtServiceReturnService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final PtServiceReturnMapper ptServiceReturnMapper;

    public PtServiceReturnServiceImpl(PtServiceReturnMapper ptServiceReturnMapper) {
        this.ptServiceReturnMapper = ptServiceReturnMapper;
    }

    @Override
    public int insert(PtServiceReturn ptServiceReturn) {
        logger.info("insert:{}", JSON.toJSONString(ptServiceReturn));
        return ptServiceReturnMapper.insert(ptServiceReturn);
    }

    @Override
    public int update(PtServiceReturn ptServiceReturn) {
        logger.info("update:{}", JSON.toJSONString(ptServiceReturn));
        return ptServiceReturnMapper.updateByPrimaryKeySelective(ptServiceReturn);
    }

    @Override
    public int inserts(List<PtServiceReturn> serviceParamList) {
        List<PtServiceReturn> ptServiceParamList = serviceParamList.stream()
                .filter(p -> StringUtils.isNotBlank(p.getSrvId()))
                .filter(p -> StringUtils.isNotBlank(p.getParamCode()))
                .filter(p -> StringUtils.isNotBlank(p.getParamName()))
                .filter(p -> StringUtils.isNotBlank(p.getParamType()))
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(ptServiceParamList)) {
            return 0;
        }

        String srvId = ptServiceParamList.get(0).getSrvId();
        ptServiceReturnMapper.deleteBySrvId(srvId);
        ptServiceParamList.forEach(ptServiceReturnMapper::insert);
        return 1;
    }

    @Override
    public Page list(String srvId, int page, int rows) {
        PageHelper.startPage(page, rows);
        List<PtServiceReturn> list = ptServiceReturnMapper.listBySrvId(srvId);
        return PageUtils.convert(list);
    }

    @Override
    public List<PtServiceReturn> listBysrvId(String srvId) {
        return ptServiceReturnMapper.listBySrvId(srvId);
    }


    @Override
    public int delete(String srvId, String paramCode) {
        PtServiceParamKey key = PtServiceParamKey.builder().srvId(srvId).paramCode(paramCode).build();
        return ptServiceReturnMapper.deleteByPrimaryKey(key);
    }
}
