package com.jwipc.supplier.logic.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.jwipc.exception.DaoException;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.convert.SupRelationBidConvert;
import com.jwipc.supplier.convert.SupplierConvert;
import com.jwipc.supplier.dto.RelationBidDTO;
import com.jwipc.supplier.dto.RelationBidExportDTO;
import com.jwipc.supplier.dto.SupplierBaseDTO;
import com.jwipc.supplier.entity.RelationBid;
import com.jwipc.supplier.entity.Supplier;
import com.jwipc.supplier.logic.SupRelationBidLogic;
import com.jwipc.supplier.model.po.RelationBidPO;
import com.jwipc.supplier.model.query.SupRelationBidQuery;
import com.jwipc.supplier.service.IRelationBidService;
import com.jwipc.supplier.service.ISupplierService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class SupRelationBidLogicImpl implements SupRelationBidLogic {
    private final IRelationBidService relationBidService;
    private final SupRelationBidConvert supRelationBidConvert;
    private final ISupplierService supplierService;
    private final SupplierConvert supplierConvert;

    @Override
    public PageView findByPage(SupRelationBidQuery query) {
        final Page<RelationBid> dbPage = PageUtil.toPage(query);

        List<RelationBidPO> supRelationBidPOS = relationBidService.findPageByQuery(dbPage, query);

        return PageUtil.getPV(supRelationBidConvert.po2PageListDTO(supRelationBidPOS), dbPage.getTotal());
    }

    @Override
    public RelationBidDTO getById(Long id) {
        if (id != null) {
            RelationBidPO relationBidPO = relationBidService.getDataById(id);
            return supRelationBidConvert.po2DTO(relationBidPO);
        } else {
            return new RelationBidDTO();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(RelationBidDTO param) {
        //保存
        if (Objects.isNull(param.getId())) {
        }

//            final LambdaQueryWrapper<RelationBid> resourcesLambdaQueryWrapper = new LambdaQueryWrapper<PurchaseOrg>
//            ().eq(
//                    PurchaseOrg::getPurchaseOrgCode, param.getPurchaseOrgCode()).last(" limit 1");
//            if (ObjectUtil.isNotNull(purchaseOrgService.getOne(resourcesLambdaQueryWrapper))){
//                throw new DaoException("采购组织编码重复");
//            }

//            param.setCreateTime(LocalDateTime.now());

//
//        }else {
//            final LambdaQueryWrapper<PurchaseOrg> resourcesLambdaQueryWrapper = new LambdaQueryWrapper<PurchaseOrg>
//            ().eq(
//                    PurchaseOrg::getPurchaseOrgCode, param.getPurchaseOrgCode()).ne(PurchaseOrg::getId,param.getId
//                    ()).last(" limit 1");
//            if (ObjectUtil.isNotNull(purchaseOrgService.getOne(resourcesLambdaQueryWrapper))){
//                throw new DaoException("采购组织编码重复");
//            }
//            param.setLastUpdateTime(LocalDateTime.now());
//
//
//        }
//        String sapClient = ObjectUtil.isNull(param.getSapClient()) ? "" : param.getSapClient();
//        String companyCode = ObjectUtil.isNull(param.getCompanyCode()) ? "" : param.getCompanyCode();
//        String purchaseOrgCode = ObjectUtil.isNull(param.getPurchaseOrgCode()) ? "" : param.getPurchaseOrgCode();

//        String dataPrimary = sapClient + companyCode + purchaseOrgCode;
//        param.setDataPrimary(dataPrimary);
        relationBidService.saveOrUpdate(supRelationBidConvert.param2Entity(param));
    }

    @Override
    public void remove(Long id) {
        relationBidService.remove(new LambdaQueryWrapper<RelationBid>().eq(RelationBid::getId, id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void itemImportData(MultipartFile fileId) {
        //这个地方需要通过文件id获取文件，然后获取导入的数据
        //查询当前的所有稽核整改明细;
        List<RelationBidExportDTO> cachedDataList = ListUtils.newArrayList();

        try {

            EasyExcel.read(fileId.getInputStream(), RelationBidExportDTO.class,
                    new ReadListener<RelationBidExportDTO>() {
                        @Override
                        public void invoke(RelationBidExportDTO data, AnalysisContext context) {

//                    final String supplierCode = data.getSupplierCode();
//
//
//                    if (Strings.isNullOrEmpty(supplierCode)) {
//                        throw new DaoException("供应商编码不能为空!");
//                    }
                            if (Strings.isNullOrEmpty(data.getSupplierName())) {
                                throw new DaoException("供应商名称不能为空!");
                            }
                            if (Strings.isNullOrEmpty(data.getSupplierCode())) {
                                throw new DaoException("供应商代码不能为空!");
                            }
                            //字典
                            if (Strings.isNullOrEmpty(data.getFaSupplierName())) {
                                throw new DaoException("父供应商名称不能为空!");
                            }
                            if (Strings.isNullOrEmpty(data.getFaSupplier())) {
                                throw new DaoException("父供应商编码不能为空!");
                            }

                            cachedDataList.add(data);
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        }
                    }).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<RelationBid> qmAuditManages = supRelationBidConvert.importDTOs2Entites(cachedDataList);
        for (RelationBid qmAuditManage : qmAuditManages) {

//            qmAuditManage.setUpdateUserId(LoginUtil.getUserId());
//            qmAuditManage.setUpdateUserName(LoginUtil.getName());
//            qmAuditManage.setUpdateTime(LocalDateTime.now());
            //qmAuditManage.setAuditReason(codeValue);
            //qmAuditManage.setAuditResult(codeValue);
        }
        relationBidService.saveBatch(qmAuditManages);
    }

    @Override
    public List<SupplierBaseDTO> getAgentList() {
        if (LoginUtil.isSupplier()) {
            final List<RelationBid> list = relationBidService.list(
                    new LambdaQueryWrapper<RelationBid>().eq(RelationBid::getFaSupplier, LoginUtil.getSupplierCode()));
            if (CollUtil.isEmpty(list)) {
                final List<Supplier> suppliers = supplierService.list(
                        new LambdaQueryWrapper<Supplier>().eq(Supplier::getSupplierCode, LoginUtil.getSupplierCode()));
                return supplierConvert.entities2BaseDtos(suppliers);
            } else {
                final Set<String> supplierCodes = list.stream().map(RelationBid::getSupplierCode)
                        .collect(Collectors.toSet());
                final List<Supplier> suppliers = supplierService.list(
                        new LambdaQueryWrapper<Supplier>().in(Supplier::getSupplierCode, supplierCodes));
                return supplierConvert.entities2BaseDtos(suppliers);
            }
        }
        return List.of();
    }

    @Override
    public RelationBidDTO getBySupplierCode(String supplierCode) {
        RelationBid relationBid = relationBidService.getOne(Wrappers.lambdaQuery(RelationBid.class).eq(RelationBid::getSupplierCode, supplierCode).last(" limit 1"));
        return supRelationBidConvert.entity2DTO(relationBid);
    }

}