package com.fjhx.supply.service.supplier.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
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.ProductClassifyService;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.supply.entity.supplier.dto.SupplierPriceDto;
import com.fjhx.supply.entity.supplier.dto.SupplierPriceSelectDto;
import com.fjhx.supply.entity.supplier.po.SupplierInfo;
import com.fjhx.supply.entity.supplier.po.SupplierPrice;
import com.fjhx.supply.entity.supplier.vo.SupplierPriceAddVo;
import com.fjhx.supply.entity.supplier.vo.SupplierPriceVo;
import com.fjhx.supply.mapper.supplier.SupplierPriceMapper;
import com.fjhx.supply.service.supplier.SupplierPriceService;
import com.fjhx.tenant.utils.DeptUstil;
import com.ruoyi.common.core.domain.BaseIdPo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.common.utils.wrapper.SqlField;
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 zlj
 * @since 2023-03-17
 */
//@DS(SourceConstant.SUPPLY)
@Service
public class SupplierPriceServiceImpl extends ServiceImpl<SupplierPriceMapper, SupplierPrice> implements SupplierPriceService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductClassifyService productClassifyService;

    @Override
    public Page<SupplierPriceVo> getPage(SupplierPriceSelectDto dto) {

        IWrapper<SupplierPrice> wrapper = getWrapper();

        if (dto.getDefinition() != null) {

            List<Long> productIdList = productInfoService.listObject(BaseIdPo::getId,
                    q -> q.eq(ProductInfo::getDefinition, dto.getDefinition()));

            if (productIdList.size() == 0) {
                return new Page<>();
            }

            wrapper.in("sp", SupplierPrice::getProductInfoId, productIdList);
        }

        wrapper.orderByDesc("sp", SupplierPrice::getId);
        wrapper.eq("si", SupplierInfo::getType, dto.getSupplierType());
        wrapper.keyword(dto, new SqlField("si.name"));

        //权限过滤：供应商价格自己看自己
        wrapper.eq("sp", SupplierPrice::getCompanyId, SecurityUtils.getCompanyId());

        Page<SupplierPriceVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<SupplierPriceVo> records = page.getRecords();

        if (records.size() == 0) {
            return page;
        }

//        DynamicDataSourceContextHolder.push(SourceConstant.ITEM);
        productInfoService.attributeAssign(records, SupplierPrice::getProductInfoId, (item, product) -> {
            item.setDefinition(product.getDefinition());
            item.setProductClassifyId(product.getProductClassifyId());
            item.setProductType(product.getType());
            item.setProductCode(product.getCode());
            item.setProductName(product.getName());
            item.setProductSpec(product.getSpec());
            item.setProductUnit(product.getUnit());
        });

        productClassifyService.attributeAssign(records, SupplierPriceVo::getProductClassifyId, (item, productClassify) -> {
            item.setProductClassifyName(productClassify.getName());
        });

        //获取归属公司信息
        List<Long> companyIds = records.stream().map(SupplierPrice::getCompanyId).collect(Collectors.toList());
        Map<Long, String> companyNameMap = DeptUstil.getDeptNameMap(companyIds);

        for (SupplierPriceVo record : records) {
            //赋值生产公司名称
            record.setCompanyName(companyNameMap.get(record.getCompanyId()));
        }

//        DynamicDataSourceContextHolder.clear();
        return page;
    }

    @Override
    public SupplierPriceAddVo add(SupplierPriceDto supplierPriceDto) {
        SupplierPriceAddVo supplierPriceAddVo = new SupplierPriceAddVo();

        // 添加产品列表
        List<SupplierPrice> supplierPriceList = supplierPriceDto.getSupplierPriceList();
        for (SupplierPrice supplierPrice : supplierPriceList) {
            //赋值产品归属公司
            Long companyId = supplierPrice.getCompanyId();
            if (ObjectUtil.isEmpty(companyId)) {
                supplierPrice.setCompanyId(SecurityUtils.getCompanyId());
            }
        }

        // 添加产品id列表
        List<Long> productInfoIdList = supplierPriceList.stream().map(SupplierPrice::getProductInfoId).collect(Collectors.toList());

        // 供应商id
        Long supplierInfoId = supplierPriceDto.getSupplierInfoId();

        // 存在供应商价格列表
        List<SupplierPrice> existSupplierPriceList = list(q -> q
                .eq(SupplierPrice::getSupplierInfoId, supplierInfoId)
                .in(SupplierPrice::getProductInfoId, productInfoIdList));

        if (existSupplierPriceList.size() == 0) {
            supplierPriceList.forEach(item -> item.setSupplierInfoId(supplierPriceDto.getSupplierInfoId()));
            this.saveBatch(supplierPriceList);
            supplierPriceAddVo.setAddSuccess(true);
            return supplierPriceAddVo;
        }

        // 存在价格更新
        if (supplierPriceDto.isRenewWhileItExists()) {

            // 产品id,明细map
            Map<Long, SupplierPrice> map = existSupplierPriceList.stream()
                    .collect(Collectors.toMap(SupplierPrice::getProductInfoId, Function.identity()));

            for (SupplierPrice supplierPrice : supplierPriceList) {
                supplierPrice.setSupplierInfoId(supplierInfoId);

                SupplierPrice existSupplierPrice = map.get(supplierPrice.getProductInfoId());
                if (existSupplierPrice != null) {
                    supplierPrice.setId(existSupplierPrice.getId());
                }
            }
            this.saveOrUpdateBatch(supplierPriceList);
            supplierPriceAddVo.setAddSuccess(true);
            return supplierPriceAddVo;
        }

        // 存在价格不更新
        supplierPriceAddVo.setExistSupplierPriceList(existSupplierPriceList);
        return supplierPriceAddVo;
    }

    @Override
    public void edit(SupplierPriceDto supplierPriceDto) {
        supplierPriceDto.setSupplierInfoId(null);
        supplierPriceDto.setProductInfoId(null);

        this.updateById(supplierPriceDto);
    }

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

    @Override
    public Map<Long, BigDecimal> getSupplierPriceByProductIds(SupplierPriceDto dto) {
        Long supplierId = dto.getSupplierInfoId();
        if (ObjectUtils.isEmpty(supplierId)) {
            throw new ServiceException("供应商id不能为空");
        }
        List<Long> productIdList = dto.getProductIdList();
        if (ObjectUtils.isEmpty(productIdList)) {
            throw new ServiceException("产品id数组不能为空");
        }
        List<SupplierPrice> list = list(q -> q.eq(SupplierPrice::getSupplierInfoId, supplierId).in(SupplierPrice::getProductInfoId, productIdList));
        return list.stream().collect(Collectors.toMap(SupplierPrice::getProductInfoId, SupplierPrice::getPrice));
    }

    @Override
    public List<SupplierPriceVo> getTopPriceList(List<Long> productIds, Integer count) {
        return baseMapper.getTopPriceList(productIds, count);
    }


}