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

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.item.util.excel.util.ExcelUtil;
import com.fjhx.victoriatourist.entity.sales.bo.ExcelImportBo;
import com.fjhx.victoriatourist.entity.sales.dto.SalesRecordSelectDto;
import com.fjhx.victoriatourist.entity.sales.po.SalesRecord;
import com.fjhx.victoriatourist.entity.sales.vo.SalesRecordVo;
import com.fjhx.victoriatourist.mapper.sales.SalesRecordMapper;
import com.fjhx.victoriatourist.service.sales.SalesRecordService;
import com.fjhx.wms.entity.stock.bo.InOutBo;
import com.fjhx.wms.entity.stock.emums.JournalType;
import com.fjhx.wms.service.stock.StockService;
import com.ruoyi.common.core.domain.BaseIdPo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.wrapper.IWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 销售数据 服务实现类
 * </p>
 *
 * @author
 * @since 2023-04-19
 */
@Service
public class SalesRecordServiceImpl extends ServiceImpl<SalesRecordMapper, SalesRecord> implements SalesRecordService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductClassifyService productClassifyService;

    @Autowired
    private StockService stockService;

    @Override
    public Page<SalesRecordVo> getPage(SalesRecordSelectDto dto) {
        IWrapper<SalesRecord> wrapper = getWrapper();
        wrapper.orderByDesc("sr", SalesRecord::getId);
        Page<SalesRecordVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<SalesRecordVo> records = page.getRecords();
        if (records.size() == 0) {
            return page;
        }

        productInfoService.attributeAssign(records, SalesRecord::getProductId, (item, product) -> {
            item.setClassifyId(product.getProductClassifyId());
            item.setProductCode(product.getCode());
            item.setProductName(product.getName());
            item.setProductUnit(product.getUnit());
            item.setProductSpec(product.getSpec());
        });

        productClassifyService.attributeAssign(records, SalesRecordVo::getClassifyId, (item, classify) -> {
            item.setClassifyName(classify.getName());
        });

        return page;
    }

    @DSTransactional
    @Override
    public void excelImport(MultipartFile file, Long warehouseId) {

        // 读取excel数据
        List<ExcelImportBo> excelImportBoList = ExcelUtil.read(file, ExcelImportBo.class);

        // 产品code列表
        List<String> productCodeList = excelImportBoList.stream()
                .map(ExcelImportBo::getProductCode)
                .filter(Objects::nonNull).distinct()
                .collect(Collectors.toList());

        // 产品信息
        List<ProductInfo> productInfoList = productInfoService.list(q -> q.in(ProductInfo::getCode, productCodeList));

        // 判断产品编码
        if (productCodeList.size() != productInfoList.size()) {

            Set<String> productCodeSet = productInfoList.stream().map(ProductInfo::getCode).collect(Collectors.toSet());

            String nonexistenceCodeStr = productCodeList.stream()
                    .filter(item -> !productCodeSet.contains(item))
                    .collect(Collectors.joining(","));

            throw new ServiceException("未知产品编码：" + nonexistenceCodeStr);
        }

        // 产品code id map
        Map<String, Long> codeIdMap = productInfoList.stream()
                .collect(Collectors.toMap(ProductInfo::getCode, BaseIdPo::getId));

        List<SalesRecord> salesRecordList = excelImportBoList.stream().map(item -> {
            SalesRecord salesRecord = new SalesRecord();
            salesRecord.setId(IdWorker.getId());
            salesRecord.setDateSale(item.getDateSale());
            salesRecord.setQuantity(item.getQuantity());
            salesRecord.setWarehouseId(warehouseId);
            salesRecord.setProductId(codeIdMap.get(item.getProductCode()));

            // 出入库明细
            InOutBo inOutBo = new InOutBo();
            inOutBo.setProductId(salesRecord.getProductId());
            inOutBo.setQuantity(salesRecord.getQuantity());
            stockService.inOut(Collections.singletonList(inOutBo), warehouseId, JournalType.JD_SALES_OUT, salesRecord.getId());

            return salesRecord;
        }).collect(Collectors.toList());

        saveBatch(salesRecordList);
    }

}
