package com.trade.client.trade.purchaseorder.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.trade.client.enterprise.customer.domain.CustomerUser;
import com.trade.client.enterprise.customer.service.CustomerUserService;
import com.trade.client.trade.purchaseorder.service.CPurchaseOrderService;
import com.trade.common.constant.HttpStatus;
import com.trade.common.core.page.GridPage;
import com.trade.common.exception.ValidatorException;
import com.trade.common.utils.LoggerUtil;
import com.trade.common.utils.StringUtils;
import com.trade.service.filestorage.entity.TFileStorage;
import com.trade.service.filestorage.enums.FileModuleEnum;
import com.trade.service.filestorage.service.OSSFileService;
import com.trade.service.filestorage.service.TFileStorageService;
import com.trade.service.filestorage.util.MultipartFileUtil;
import com.trade.service.system.domain.InvoiceTypeMapping;
import com.trade.service.system.service.InvoiceTypeMappingService;
import com.trade.service.trade.filingdoc.service.FilingDocService;
import com.trade.service.trade.purchaseorder.dto.PurchaseOrderInvoiceSearchDto;
import com.trade.service.trade.purchaseorder.domain.PurchaseOrder;
import com.trade.service.trade.purchaseorder.dto.PurchaseOrderLogisticsDto;
import com.trade.service.trade.purchaseorder.dto.PurchaseOrderLogisticsSearchDto;
import com.trade.service.trade.purchaseorder.dto.PurchaseSearchDto;
import com.trade.service.trade.purchaseorder.service.PurchaseOrderInvoiceService;
import com.trade.service.trade.purchaseorder.service.PurchaseOrderLogisticsService;
import com.trade.service.trade.purchaseorder.service.PurchaseOrderService;
import com.trade.service.trade.purchaseorder.vo.*;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 采购订单服务实现类
 * @Author: wanglang
 * @Date: 2024/9/11 9:50
 * @Version: 1.0
 */
@Service
public class CPurchaseOrderServiceImpl implements CPurchaseOrderService {

    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SERVICES_LOG);
    @Resource
    private PurchaseOrderService purchaseOrderService;
    @Resource
    private OSSFileService ossFileService;
    @Resource
    private CustomerUserService customerUserService;
    @Resource
    private PurchaseOrderLogisticsService purchaseOrderLogisticsService;
    @Resource
    private TFileStorageService tFileStorageService;
    @Resource
    private PurchaseOrderInvoiceService purchaseOrderInvoiceService;
    @Resource
    private FilingDocService filingDocService;
    @Resource
    private InvoiceTypeMappingService invoiceTypeMappingService;

    @Override
    public Boolean saveOrderLogistics(PurchaseOrderLogisticsDto purchaseOrderLogisticsDto, HttpServletRequest request) {
        MultipartFile transferFile = null;
        if (request instanceof MultipartHttpServletRequest) {
            transferFile = ((MultipartHttpServletRequest) request).getFile("file");
        }
        if (transferFile == null) {
            throw new ValidatorException(HttpStatus.ERROR, "请您运输证明！");
        }
        boolean meetLimit = MultipartFileUtil.checkFileSize(transferFile, 20, "M");
        if (!meetLimit) {
            throw new ValidatorException(HttpStatus.ERROR, "合同文件大小请控制在20M以内");
        }
        TFileStorage fileStorage = null;
        try {
            fileStorage = ossFileService.addStorage(transferFile, FileModuleEnum.PURCHASE_ORDER);
        } catch (IOException e) {
            log.error("purchaseOrderId={}文件上传失败={}", purchaseOrderLogisticsDto.getPurchaseOrderId(), e);
            throw new ValidatorException(HttpStatus.ERROR, "文件上传失败");
        }
        purchaseOrderLogisticsDto.setTransportCertificateFileId(fileStorage.getId());
        purchaseOrderService.saveOrderLogistics(purchaseOrderLogisticsDto);
        return true;
    }

    @Override
    public Boolean saveOrderLogistics(PurchaseOrderLogisticsDto purchaseOrderLogisticsDto) {
        TFileStorage fileStorage = tFileStorageService
                .getFileStorageById(purchaseOrderLogisticsDto.getTransportCertificateFileId());
        if (fileStorage == null) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST,
                    "文件不存在（文件id：" + purchaseOrderLogisticsDto.getTransportCertificateFileId() + "）");
        }
        purchaseOrderService.saveOrderLogistics(purchaseOrderLogisticsDto);
        try {
            PurchaseOrder purchaseOrder = purchaseOrderService.getById(purchaseOrderLogisticsDto.getPurchaseOrderId());
            filingDocService.newTaskBySalesOrderId(purchaseOrder.getSalesOrderId(), 1);
        } catch (Exception e) {
            log.error("新增备案单证写入任务失败，采购订单id={}", purchaseOrderLogisticsDto.getPurchaseOrderId());
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public GridPage<PurchaseOrderVo> queryListByPage(PurchaseSearchDto purchaseSearch) {
        CustomerUser customerUser = customerUserService.getCustomerUser();
        purchaseSearch.setCustomerUserId(customerUser.getId());
        purchaseSearch.setPoint(true);
        Page<PurchaseOrderVo> page = PageHelper.startPage(purchaseSearch.getPage(), purchaseSearch.getRows());
        List<PurchaseOrderVo> voList = purchaseOrderService.selectByCondition(purchaseSearch);
        return new GridPage<>(purchaseSearch.getPage(), purchaseSearch.getRows(), page.getTotal(), voList);
    }

    @Override
    public PurchaseOrderDetailsVo getDetailsById(Long id) {
        return purchaseOrderService.getDetailsById(id);
    }

    @Override
    public GridPage<PurchaseOrderLogisticsPageVo> queryOrderLogisticsByPage(
            PurchaseOrderLogisticsSearchDto orderLogisticsSearch) {
        CustomerUser customerUser = customerUserService.getCustomerUser();
        orderLogisticsSearch.setCustomerUserId(customerUser.getId());
        orderLogisticsSearch.setPoint(true);
        Page<PurchaseOrderVo> page = PageHelper.startPage(orderLogisticsSearch.getPage(),
                orderLogisticsSearch.getRows());
        return new GridPage<>(orderLogisticsSearch.getPage(), orderLogisticsSearch.getRows(), page.getTotal(),
                purchaseOrderLogisticsService.queryOrderLogisticsByPage(orderLogisticsSearch));
    }

    @Override
    public GridPage<PurchaseOrderInvoiceVo> queryInvoiceListByPage(
            PurchaseOrderInvoiceSearchDto purchaseOrderInvoiceSearchDto) {
        CustomerUser customerUser = customerUserService.getCustomerUser();
        purchaseOrderInvoiceSearchDto.setSource(2);
        purchaseOrderInvoiceSearchDto.setCustomerUserId(customerUser.getId());
        if (StringUtils.isNotEmpty(purchaseOrderInvoiceSearchDto.getInvoiceType())) {
            List<String> types = invoiceTypeMappingService
                    .getInvoiceKjtCode(purchaseOrderInvoiceSearchDto.getInvoiceType()).stream()
                    .map(InvoiceTypeMapping::getCode).collect(Collectors.toList());
            purchaseOrderInvoiceSearchDto.setInvoiceTypeList(types);
        }
        Page<PurchaseOrderVo> page = PageHelper.startPage(purchaseOrderInvoiceSearchDto.getPage(),
                purchaseOrderInvoiceSearchDto.getRows());
        List<PurchaseOrderInvoiceVo> voList = purchaseOrderInvoiceService
                .queryByCondition(purchaseOrderInvoiceSearchDto);
        return new GridPage<>(purchaseOrderInvoiceSearchDto.getPage(), purchaseOrderInvoiceSearchDto.getRows(),
                page.getTotal(), voList);
    }

    @Override
    public PurchaseOrderInvoiceDetailsVo getInvoiceDetails(Long InvoiceId) {
        return purchaseOrderInvoiceService.getDetails(InvoiceId);
    }
}
