package com.zd.airbottle.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.zd.airbottle.domain.QpSpecification;
import com.zd.airbottle.domain.QpSpecificationDetail;
import com.zd.airbottle.domain.dto.QpSpecificationDetailDto;
import com.zd.airbottle.domain.dto.QpSpecificationDto;
import com.zd.airbottle.domain.vo.QpSpecificationDetailVo;
import com.zd.airbottle.domain.vo.QpSpecificationVo;
import com.zd.airbottle.mapper.QpSpecificationMapper;
import com.zd.airbottle.service.IQpSpecificationDetailService;
import com.zd.airbottle.service.IQpSpecificationService;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.bean.TransferUtils;
import com.zd.common.security.service.TokenService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 气瓶规格Service业务层处理
 */
@Service
public class QpSpecificationServiceImpl implements IQpSpecificationService {
    @Autowired
    private QpSpecificationMapper qpSpecificationMapper;
    @Autowired
    private IQpSpecificationDetailService detailService;
    @Resource
    private TokenService tokenService;

    /**
     * 查询气瓶规格
     *
     * @param id 气瓶规格主键
     * @return 气瓶规格
     */
    @Override
    public QpSpecification selectQpSpecificationById(Long id) {
        return qpSpecificationMapper.selectQpSpecificationById(id);
    }

    /**
     * 根据ID查询气瓶规格详情
     *
     * @param id 气瓶规格主键
     * @return 气瓶规格显示类
     */
    @Override
    public QpSpecificationVo getById(Long id) {
        QpSpecification specification = qpSpecificationMapper.selectQpSpecificationById(id);
        QpSpecificationVo specificationVo = new QpSpecificationVo();
        BeanUtils.copyProperties(specification, specificationVo);

        List<QpSpecificationDetail> details = detailService.selectQpSpecificationDetailList(new QpSpecificationDetail().setSpecId(specification.getId()));
        TransferUtils.transferList(details, QpSpecificationDetailVo.class);
        specificationVo.setDetailVos(TransferUtils.transferList(details, QpSpecificationDetailVo.class));
        return specificationVo;
    }

    /**
     * 查询气瓶规格列表
     *
     * @param qpSpecification 气瓶规格
     * @return 气瓶规格
     */
    @Override
    public List<QpSpecification> selectQpSpecificationList(QpSpecification qpSpecification) {
        return qpSpecificationMapper.selectQpSpecificationList(qpSpecification);
    }

    @Override
    public List<QpSpecificationVo> list(List<QpSpecification> specifications) {

        List<QpSpecificationDetail> details = detailService.listBySpecIds(specifications.stream().map(QpSpecification::getId).collect(Collectors.toList()));
        List<QpSpecificationDetailVo> detailVos = TransferUtils.transferList(details, QpSpecificationDetailVo.class);

        Map<Long, List<QpSpecificationDetailVo>> detailMap = detailVos.stream().collect(Collectors.groupingBy(QpSpecificationDetailVo::getSpecId));
        List<QpSpecificationVo> specificationVos = TransferUtils.transferList(specifications, QpSpecificationVo.class);
        specificationVos.forEach(s -> {
            Long id = s.getId();
            if (CollUtil.isNotEmpty(detailMap) && detailMap.containsKey(id)) {
                List<QpSpecificationDetailVo> list = detailMap.get(id);
                s.setDetailVos(list).setDetailSum(Math.toIntExact(list.size()));
            }
        });
        return specificationVos;
    }

    /**
     * 新增气瓶规格
     *
     * @param specificationDto 气瓶规格
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertQpSpecification(QpSpecificationDto specificationDto) {
        QpSpecification specification = new QpSpecification();
        BeanUtils.copyProperties(specificationDto, specification);
        //设置其他公共字段
        specification.setCreateTime(DateUtils.getNowDate());
        specification.setCreateBy(tokenService.getLoginUser().getSysUser().getUserName());
        if (qpSpecificationMapper.insertQpSpecification(specification) > 0) {
            List<QpSpecificationDetailDto> detailDtos = specificationDto.getDetailDtos();
            detailDtos.forEach(d -> {
                QpSpecificationDetail detail = new QpSpecificationDetail().setSpecId(specification.getId());
                BeanUtils.copyProperties(d, detail);
                detailService.insertQpSpecificationDetail(detail);
            });
            return 1;
        } else {
            throw new ServiceException("气瓶规格新增失败");
        }
    }

    /**
     * 修改气瓶规格
     *
     * @param specificationDto 气瓶规格
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateQpSpecification(QpSpecificationDto specificationDto) {
        QpSpecification specification = new QpSpecification();
        BeanUtils.copyProperties(specificationDto, specification);
        specification.setUpdateTime(DateUtils.getNowDate());
        specification.setUpdateBy(tokenService.getLoginUser().getSysUser().getUserName());
        List<QpSpecificationDetailDto> detailDtos = specificationDto.getDetailDtos();

        List<QpSpecificationDetail> details = detailService.selectQpSpecificationDetailList(new QpSpecificationDetail().setSpecId(specification.getId()));
        List<Long> ids = details.stream().map(QpSpecificationDetail::getId).collect(Collectors.toList());
        List<Long> idList = Collections.synchronizedList(ids);
        detailDtos.forEach(d -> {
            QpSpecificationDetail detail = new QpSpecificationDetail();
            BeanUtils.copyProperties(d, detail);
            Long id = detail.getId();
            detail.setSpecId(specification.getId());
            if (id != null) {
                idList.remove(id);
            }
            if (detail.getId() == null) {
                detailService.insertQpSpecificationDetail(detail);
            } else {
                detailService.updateQpSpecificationDetail(detail);
            }
        });
        if (!idList.isEmpty()) {
            detailService.deleteQpSpecificationDetailByIds(idList.toArray(new Long[0]));
        }
        return qpSpecificationMapper.updateQpSpecification(specification);
    }

    /**
     * 批量删除气瓶规格
     *
     * @param ids 需要删除的气瓶规格主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQpSpecificationByIds(Long[] ids) {
        detailService.deleteBySpecIds(ids);
        return qpSpecificationMapper.deleteQpSpecificationByIds(ids);
    }

    /**
     * 删除气瓶规格信息
     *
     * @param id 气瓶规格主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQpSpecificationById(Long id) {
        return qpSpecificationMapper.deleteQpSpecificationById(id);
    }
}
