package com.fjhx.service.purchase.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.BaseEntity;
import com.fjhx.entity.apply.ApplyPurchase;
import com.fjhx.entity.logistics.LogisticsInfo;
import com.fjhx.entity.purchase.Purchase;
import com.fjhx.entity.supplier.Supplier;
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.service.supplier.SupplierService;
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.HashMap;
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;

    @Autowired
    private SupplierService supplierService;

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

    /**
     * 已采购列表
     *
     * @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(ObjectUtil.isNotEmpty(condition.get("keyword")), "instr(`code`, '" + condition.get("keyword") + "') > 0")
                .orderByDesc(ApplyPurchase::getId);

        Page<Purchase> page = page(condition, wrapper);

        List<Purchase> records = page.getRecords();

        if (records.size() == 0) {
            return page;
        }

        // 采购ID集合
        List<Long> purchaseIds = records.stream().map(Purchase::getId).distinct().collect(Collectors.toList());

        // 查询物流信息
        Map<Long, List<LogisticsInfo>> logisticsInfoMap = logisticsInfoService.getByPurchaseIdsToMap(purchaseIds);

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

        // 供应商
        List<Long> supplierIdList = records.stream().map(Purchase::getSupplierId).filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
        Map<Long, String> supplierIdNameMap;
        if (supplierIdList.size() > 0) {
            supplierIdNameMap = supplierService.getKV(Supplier::getId, Supplier::getName, q -> q.in(BaseEntity::getId, supplierIdList));
        } else {
            supplierIdNameMap = new HashMap<>();
        }

        for (Purchase record : records) {
            // 赋值物流单号
            List<LogisticsInfo> logisticsInfos = logisticsInfoMap.get(record.getId());
            if (ObjectUtil.isNotEmpty(logisticsInfos)) {
                record.setLogisticsCode(logisticsInfos.stream().map(LogisticsInfo::getCode).distinct().collect(Collectors.joining(",")));
            }
            // 赋值采购人名称
            record.setCreateName(userNameMap.get(record.getCreateUser()));
            // 赋值供应商名称
            record.setSupplierName(supplierIdNameMap.get(ObjectUtil.defaultIfNull(record.getSupplierId(), -1L)));
        }

        return page;
    }

    /**
     * 获取审批详情
     *
     * @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
     * @param status 采购状态
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void cancelOrEnd(Long id, Integer status) {
        // 修改采购状态
        lambdaUpdate()
                .set(Purchase::getStatus, status)
                .eq(Purchase::getId, id)
                .update();

        // 修改申购状态
        applyPurchaseService.lambdaUpdate()
                .set(ApplyPurchase::getStatus, ApplyPurchaseStatusEnum.STATUS_70.getKey())
                .eq(ApplyPurchase::getPurchaseId, id).update();
    }

}
