package com.fjhx.victoriatourist.service.jd.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.item.entity.product.po.ProductInfo;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.victoriatourist.entity.jd.dto.JdBackQualityDetailsDto;
import com.fjhx.victoriatourist.entity.jd.dto.JdBackQualityDetailsSelectDto;
import com.fjhx.victoriatourist.entity.jd.po.JdBackQualityDetails;
import com.fjhx.victoriatourist.entity.jd.po.JdBackQualityWait;
import com.fjhx.victoriatourist.entity.jd.vo.JdBackQualityDetailsVo;
import com.fjhx.victoriatourist.mapper.jd.JdBackQualityDetailsMapper;
import com.fjhx.victoriatourist.service.jd.JdBackQualityDetailsService;
import com.fjhx.victoriatourist.service.jd.JdBackQualityWaitService;
import com.fjhx.victoriatourist.utils.CodeEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * <p>
 * 京东退货质检明细 服务实现类
 * </p>
 *
 * @author
 * @since 2023-04-19
 */
@Service
public class JdBackQualityDetailsServiceImpl extends ServiceImpl<JdBackQualityDetailsMapper, JdBackQualityDetails> implements JdBackQualityDetailsService {
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private JdBackQualityWaitService jdBackQualityWaitService;

    @Override
    public Page<JdBackQualityDetailsVo> getPage(JdBackQualityDetailsSelectDto dto) {
        IWrapper<JdBackQualityDetails> wrapper = getWrapper();
        wrapper.orderByDesc("jbqd", JdBackQualityDetails::getId);
        if (ObjectUtil.isNotEmpty(dto.getKeyword())) {
            wrapper.and(q -> q.like(JdBackQualityDetails::getCode, dto.getKeyword()));
        }
        Page<JdBackQualityDetailsVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<JdBackQualityDetailsVo> records = page.getRecords();
        //赋值产品信息
        productInfoService.attributeAssign(records, JdBackQualityDetailsVo::getProductId, (item, productinfo) -> {
            item.setProductCode(productinfo.getCode());
            item.setProductName(productinfo.getName());
            item.setProductSpec(productinfo.getSpec());
            item.setProductUnit(productinfo.getUnit());
        });
        //赋值质检人名字
        UserUtil.assignmentNickName(records, JdBackQualityDetailsVo::getCreateUser, JdBackQualityDetailsVo::setQualityUserName);
        return page;
    }

    @Override
    public List<JdBackQualityDetailsVo> detail(String code) {
        List<JdBackQualityDetails> list = list(q -> q.eq(JdBackQualityDetails::getCode, code));
        List<JdBackQualityDetailsVo> result = BeanUtil.copyToList(list, JdBackQualityDetailsVo.class);
        //赋值产品信息
        productInfoService.attributeAssign(result, JdBackQualityDetailsVo::getProductId, (item, productinfo) -> {
            item.setProductCode(productinfo.getCode());
            item.setProductName(productinfo.getName());
            item.setProductSpec(productinfo.getSpec());
            item.setProductUnit(productinfo.getUnit());
        });
        //赋值质检人名字
        UserUtil.assignmentNickName(result, JdBackQualityDetailsVo::getCreateUser, JdBackQualityDetailsVo::setQualityUserName);
        return result;
    }

    @DSTransactional
    @Override
    public void add(List<JdBackQualityDetailsDto> jdBackQualityDetailsDtoList) {
        if (ObjectUtil.isEmpty(jdBackQualityDetailsDtoList)) {
            throw new ServiceException("质检列表不能为空");
        }
        String code = CodeEnum.JD_BACK_QUALITY.getCode();
        List<JdBackQualityDetails> jdBackQualityDetailsList = BeanUtil.copyToList(jdBackQualityDetailsDtoList, JdBackQualityDetails.class);
        //获取质检产品id列表
        List<Long> productIds = jdBackQualityDetailsList.stream().map(JdBackQualityDetails::getProductId).collect(Collectors.toList());
        List<JdBackQualityWait> jdBackQualityWaitList = jdBackQualityWaitService.list(q -> q.in(JdBackQualityWait::getProductId, productIds));
        Map<Long, JdBackQualityWait> jdBackQualityWaitMap = jdBackQualityWaitList.stream().collect(Collectors.toMap(JdBackQualityWait::getProductId, Function.identity()));

        for (JdBackQualityDetails jdBackQualityDetailsDto : jdBackQualityDetailsList) {
            jdBackQualityDetailsDto.setCode(code);
            //减少待质检数量
            BigDecimal quality = jdBackQualityDetailsDto.getQualifiedQuantity().add(jdBackQualityDetailsDto.getDisqualificationQuantity());
            JdBackQualityWait jdBackQualityWait = jdBackQualityWaitMap.get(jdBackQualityDetailsDto.getProductId());
            if (ObjectUtil.isEmpty(jdBackQualityWait)) {
                ProductInfo productInfo = productInfoService.getById(jdBackQualityDetailsDto.getProductId());
                if (ObjectUtil.isEmpty(productInfo)) {
                    throw new ServiceException("产品不存在，产品id" + jdBackQualityDetailsDto.getProductId());
                }
                throw new ServiceException("待质检数据不存在，产品-" + productInfo.getName());
            }
            if (jdBackQualityWait.getQuantity().subtract(quality).compareTo(BigDecimal.ZERO) < 0) {
                ProductInfo productInfo = productInfoService.getById(jdBackQualityDetailsDto.getProductId());
                if (ObjectUtil.isEmpty(productInfo)) {
                    throw new ServiceException("产品不存在，产品id" + jdBackQualityDetailsDto.getProductId());
                }
                throw new ServiceException("质检数量大于待质检数量请检查，产品id" + productInfo.getName());
            }
//            BigDecimal oldQuantity = jdBackQualityWait.getQuantity();
//            jdBackQualityWait.setQuantity(oldQuantity.subtract(quality));
            jdBackQualityWaitService.update(q -> q
                    .eq(JdBackQualityWait::getId, jdBackQualityWait.getId())
                    .setSql("quantity = quantity - " + quality));
        }
        saveBatch(jdBackQualityDetailsList);
    }

    @Override
    public void edit(JdBackQualityDetailsDto jdBackQualityDetailsDto) {
        this.updateById(jdBackQualityDetailsDto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

}
