package com.kingtom.shengtai.app.srm.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.kingtom.kirin.app.system.utils.SystemUtils;
import com.kingtom.kirin.core.common.base.service.impl.BaseServiceImpl;
import com.kingtom.kirin.core.common.exception.AppException;
import com.kingtom.kirin.core.common.utils.CollectionUtils;
import com.kingtom.kirin.core.common.utils.IDUtils;
import com.kingtom.shengtai.app.srm.dao.ISrmCooperateDao;
import com.kingtom.shengtai.app.srm.model.SrmCooperate;
import com.kingtom.shengtai.app.srm.model.SrmCooperateDO;
import com.kingtom.shengtai.app.srm.model.SrmSupplier;
import com.kingtom.shengtai.app.srm.service.ISrmCooperateService;
import com.kingtom.shengtai.app.srm.service.ISrmSupplierService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.kingtom.shengtai.app.srm.model.table.SrmCooperateTableDef.SRM_COOPERATE;

/**
 * 供应商合作记录表 服务层实现。
 *
 * @author wany
 * @since 2023-12-21
 */
@Service
public class SrmCooperateServiceImpl extends BaseServiceImpl<ISrmCooperateDao, SrmCooperate>
        implements ISrmCooperateService{

    @Autowired
    private ISrmSupplierService supplierService;

    @Override
    public SrmCooperateDO create(SrmCooperate entity){
        if(entity.getId() == null){
            entity.setId(IDUtils.newUUID());
        }
        if(StringUtils.isEmpty(entity.getSupplierId())){
            throw new AppException("供应商为空，新建合作记录失败！");
        }
        if(StringUtils.isEmpty(entity.getContent())){
            throw new AppException("合作内容为空，新建合作记录失败！");
        }
        if(entity.getTime() == null){
            throw new AppException("合作时间为空，新建合作记录失败！");
        }
        entity.setGmtCreate(new Date());
        entity.setGmtModified(entity.getGmtCreate());
        entity.setSysId(SystemUtils.getCurrentSystemId());
        boolean f = mapper.insert(entity) > 0;
        if(!f){
            throw new AppException("落库出错，新建合作记录失败！");
        }
        return findById(entity.getId());
    }

    @Override
    public void deleteById(String id){
        if(StringUtils.isEmpty(id)){
            return;
        }
        boolean f = mapper.deleteById(id) > 0;
        if(!f){
            throw new AppException("落库出错，删除合作记录失败！");
        }
    }

    @Override
    public void deleteByIds(List<String> ids){
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        boolean f = mapper.deleteBatchByIds(ids) > 0;
        if(!f){
            throw new AppException("落库出错，删除合作记录失败！");
        }
    }

    @Override
    public SrmCooperateDO update(SrmCooperate entity){
        if(entity == null || entity.getId() == null){
            throw new AppException("参数错误，更新合作记录失败！");
        }
        entity.setGmtModified(new Date());
        boolean f = mapper.update(entity) > 0;
        if(!f){
            throw new AppException("落库出错，更新合作记录失败！");
        }
        return findById(entity.getId());
    }

    @Override
    public SrmCooperateDO findById(String id){
        if(StringUtils.isEmpty(id)){
            return null;
        }
        SrmCooperate srmCooperate = mapper.selectOneById(id);
        if(srmCooperate == null){
            return null;
        }
        SrmCooperateDO build = SrmCooperateDO.builder().cooperate(srmCooperate).build();
        if(srmCooperate.getSupplierId() != null){
            build.setSupplier(supplierService.getById(srmCooperate.getSupplierId()));
        }
        return build;
    }

    @Override
    public Page<SrmCooperateDO> page(String search, String supplierId, Integer pageNum, Integer pageSize){
        QueryCondition condition = QueryCondition.createEmpty()
                .and(SRM_COOPERATE.SUPPLIER_ID.eq(supplierId).when(StringUtils.isNotEmpty(supplierId)))
                .and(SRM_COOPERATE.CONTENT.like(search).when(StringUtils.isNotEmpty(search)));
        Page<SrmCooperate> paginate = mapper.paginate(pageNum, pageSize, condition);
        if(CollectionUtils.isEmpty(paginate.getRecords())){
            return new Page<>(new ArrayList<>(), pageNum, pageSize, paginate.getTotalRow());
        }
        List<String> supplierIds =
                paginate.getRecords().stream().map(SrmCooperate::getSupplierId).collect(Collectors.toList());
        List<SrmSupplier> suppliers = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(supplierIds)){
            suppliers = supplierService.listByIds(supplierIds);
        }
        Map<String, SrmSupplier> supplierMap = suppliers.stream().collect(Collectors.toMap(SrmSupplier::getId, e -> e));
        List<SrmCooperateDO> collect = paginate.getRecords().stream()
                .map(e -> SrmCooperateDO.builder().cooperate(e).supplier(supplierMap.get(e.getSupplierId())).build())
                .collect(Collectors.toList());
        return new Page<>(collect, pageNum, pageSize, paginate.getTotalRow());

    }

}
