package com.fjhx.service.purchase.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.entity.apply.ApplyPurchase;
import com.fjhx.entity.logistics.LogisticsInfo;
import com.fjhx.entity.purchase.Purchase;
import com.fjhx.enums.apply.ApplyPurchaseStatusEnum;
import com.fjhx.enums.purchase.PurchaseStatusEnum;
import com.fjhx.mapper.purchase.PurchaseMapper;
import com.fjhx.service.apply.ApplyPurchaseService;
import com.fjhx.service.logistics.LogisticsInfoService;
import com.fjhx.service.purchase.PurchaseService;
import com.fjhx.utils.UserClientUtil;
import com.fjhx.utils.wrapperUtil.IWrapper;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 采购 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-12-01
 */
@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase> implements PurchaseService {

    @Autowired
    private ApplyPurchaseService applyPurchaseService;

    @Autowired
    private LogisticsInfoService logisticsInfoService;

    /**
     * 待发货列表
     *
     * @param condition 查询条件
     * @return
     */
    @Override
    public Page<Purchase> getPage(Map<String, Object> condition) {

        IWrapper<Purchase> wrapper = IWrapper.getWrapper(condition);

        wrapper.ge(Purchase::getStatus, PurchaseStatusEnum.STATUS_30.getKey())
                .eq(Purchase::getStatus)
                .apply("instr(`code`, '" + condition.get("keyword") + "') > 0")
                .orderByDesc(ApplyPurchase::getId);

        Page<Purchase> page = page(condition, wrapper);
        if (Func.isNotEmpty(page.getRecords())) {
            //采购ID集合
            List<Long> purchaseIds = page.getRecords().stream().map(Purchase::getId).distinct().collect(Collectors.toList());
            //查询物流信息
            Map<Long, List<LogisticsInfo>> logisticsInfoMap = logisticsInfoService.getByPurchaseIdsToMap(purchaseIds);

            //采购人名称map
            Map<Long, String> userNameMap = UserClientUtil.getUserNameMap(page.getRecords(), Purchase::getCreateUser);

            for (Purchase record : page.getRecords()) {
                if (Func.isNotEmpty(logisticsInfoMap) && Func.isNotEmpty(logisticsInfoMap.get(record.getId()))) {
                    List<LogisticsInfo> infos = logisticsInfoMap.get(record.getId());
                    record.setLogisticsCode(infos.stream().map(LogisticsInfo::getCode).distinct().collect(Collectors.joining(",")));
                }

                if (Func.isNotEmpty(userNameMap) && Func.isNotEmpty(userNameMap.get(record.getCreateUser()))) {
                    record.setCreateName(userNameMap.get(record.getCreateUser()));
                }
            }
        }

        return page;
    }

    /**
     * 待采购列表
     *
     * @param condition 查询条件
     * @return
     */
    @Override
    public Page<ApplyPurchase> stayPurchasePage(Map<String, Object> condition) {
        return applyPurchaseService.stayPurchasePage(condition);
    }

    /**
     * 获取审批详情
     *
     * @param id 采购ID
     * @return
     */
    @Override
    public Purchase getFlowDetailsById(Long id) {
        Purchase purchase = getById(id);
        if (Func.isEmpty(purchase)) {
            throw new ServiceException("操作异常，业务数据不存在！");
        }

        //获取物品详情
        List<ApplyPurchase> applyPurchases = applyPurchaseService.getByPurchaseId(id);
        purchase.setGoodsList(applyPurchases);
        return purchase;
    }

    /**
     * 完成采购
     *
     * @param id 采购ID
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void complete(Long id) {
        //修改采购状态
        lambdaUpdate().set(Purchase::getStatus, PurchaseStatusEnum.STATUS_50.getKey()).eq(Purchase::getId, id).update();
        //修改申购状态
        applyPurchaseService.lambdaUpdate().set(ApplyPurchase::getStatus, ApplyPurchaseStatusEnum.STATUS_50.getKey()).eq(ApplyPurchase::getPurchaseId, id).update();
    }
}
