package com.kxs.store.biz.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.constant.enums.BrandTypeEnum;
import com.kxs.common.core.constant.enums.ErrorTypeEnum;
import com.kxs.common.core.constant.enums.KindTypeEnum;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.core.util.R;
import com.kxs.common.core.util.RetOps;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.product.api.feign.RemoteKxsProductService;
import com.kxs.product.api.model.KxsBrand;
import com.kxs.store.api.dto.kxsapp.storeLimit.WarehouseApplyDTO;
import com.kxs.store.api.dto.kxsapp.storeLimit.WarehouseApplyInfoDTO;
import com.kxs.store.api.model.KxsWarehouseLimit;
import com.kxs.store.api.model.KxsWarehouseMachineApplyDetail;
import com.kxs.store.api.vo.kxsapp.storeLimit.MachineApplyDetailVO;
import com.kxs.store.api.vo.kxsapp.storeLimit.WarehouseMachineApplyListVO;
import com.kxs.store.biz.constant.enums.StoreErrorTypeEnum;
import com.kxs.store.biz.constant.enums.WarehouseLimitTypeEnum;
import com.kxs.store.biz.mapper.KxsWarehouseLimitMapper;
import com.kxs.store.biz.mapper.KxsWarehouseMachineApplyDetailMapper;
import com.kxs.store.biz.mapper.KxsWarehouseMachineApplyMapper;
import com.kxs.store.api.model.KxsWarehouseMachineApply;
import com.kxs.store.biz.service.KxsWarehouseLimitService;
import com.kxs.store.biz.service.KxsWarehouseMachineApplyService;
import com.kxs.user.api.feign.RemoteKxsUserService;
import com.kxs.user.api.model.KxsUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客小爽分仓申请补货订单表(KxsWarehouseMachineApply)表服务实现类
 *
 * @author 系统
 * @since 2024-01-08 09:46:02
 */
@Service("kxsWarehouseMachineApplyService")
@RequiredArgsConstructor
public class KxsWarehouseMachineApplyServiceImpl extends ServiceImpl<KxsWarehouseMachineApplyMapper, KxsWarehouseMachineApply> implements KxsWarehouseMachineApplyService {

    private final RemoteKxsUserService remoteKxsUserService;

    private final RemoteKxsProductService remoteKxsProductService;

    private final KxsWarehouseMachineApplyDetailMapper kxsWarehouseMachineApplyDetailMapper;

    private final KxsWarehouseLimitMapper kxsWarehouseLimitMapper;

    private final KxsWarehouseLimitService kxsWarehouseLimitService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R warehouseApplySubmit(WarehouseApplyDTO param) {

        Long userId = SecurityUtils.getUser().getId();
        R<KxsUser> kxsUserR = remoteKxsUserService.loadUserById(userId.intValue(), SecurityConstants.FROM_IN);
        KxsUser user = RetOps.of(kxsUserR)
                .getData()
                .orElseThrow(() -> new GlobalCustomerException(ErrorTypeEnum.USER_NOT_FOUND.getDescription()));
        List<WarehouseApplyInfoDTO> applyData = param.getApplyData();
        //计算额度
        BigDecimal useAmount = BigDecimal.ZERO;
        for (WarehouseApplyInfoDTO info : applyData) {
            R<KxsBrand> kxsBrandR = remoteKxsProductService.loadByBrand(info.getBrandId(), SecurityConstants.FROM_IN);
            KxsBrand kxsBrand = RetOps.of(kxsBrandR)
                    .getData()
                    .orElseThrow(() -> new GlobalCustomerException(ErrorTypeEnum.REMOTE_DATA_ERROR.getDescription()));

            Integer price = EnumUtil.getFieldBy(BrandTypeEnum::getType, BrandTypeEnum::getDescription, String.valueOf(kxsBrand.getBrandType()));
            BigDecimal brandAmount = NumberUtil.mul(price, info.getNumber());
            useAmount = useAmount.add(brandAmount);
        }
        KxsWarehouseLimit warehouseLimit = kxsWarehouseLimitMapper.selectOne(Wrappers.<KxsWarehouseLimit>lambdaQuery()
                .eq(KxsWarehouseLimit::getWarehouseType, WarehouseLimitTypeEnum.FC.getType())
                .eq(KxsWarehouseLimit::getUserId, userId));
        if(warehouseLimit.getValidAmount().compareTo(useAmount) < 0){
            return R.failed(StoreErrorTypeEnum.INSUFFICIENT_QUOTA.getDescription());
        }

        //订单号
        Snowflake snowflake = IdUtil.getSnowflake(1, userId);
        long orderSn = snowflake.nextId();

        KxsWarehouseMachineApply kxsWarehouseMachineApply = new KxsWarehouseMachineApply();
        kxsWarehouseMachineApply.setUserId(userId.intValue());
        kxsWarehouseMachineApply.setOrderSn("FC" + orderSn);
        kxsWarehouseMachineApply.setApplyNum(param.getApplyNum());
        kxsWarehouseMachineApply.setUsername(user.getUsername());
        kxsWarehouseMachineApply.setUserCode(user.getUserCode());
        kxsWarehouseMachineApply.setApplyData(JSON.toJSONString(param.getApplyData()));
        kxsWarehouseMachineApply.setUseAmount(useAmount);
        baseMapper.insert(kxsWarehouseMachineApply);

        //刷新仓库额度
        kxsWarehouseLimitService.refreshWarehouseAmount(userId.intValue(), useAmount.intValue(), KindTypeEnum.ADD.getType());

        return R.ok();
    }

    @Override
    public IPage<WarehouseMachineApplyListVO> getByPage(Page<WarehouseMachineApplyListVO> page) {

        return baseMapper.getByPage(page, SecurityUtils.getUser().getId());
    }

    @Override
    public MachineApplyDetailVO getMachineApplyDetail(Integer id) {
        MachineApplyDetailVO machineApplyDetailVO = new MachineApplyDetailVO();
        KxsWarehouseMachineApply kxsWarehouseMachineApply = baseMapper.selectById(id);
        BeanUtils.copyProperties(kxsWarehouseMachineApply, machineApplyDetailVO);

        List<KxsWarehouseMachineApplyDetail> kxsWarehouseMachineApplyDetails = kxsWarehouseMachineApplyDetailMapper.selectList(Wrappers.lambdaQuery(KxsWarehouseMachineApplyDetail.class)
                .eq(KxsWarehouseMachineApplyDetail::getOrderId, id));
        //分组后组装数据
        Map<String, List<KxsWarehouseMachineApplyDetail>> brands = kxsWarehouseMachineApplyDetails.stream().collect(Collectors.groupingBy(KxsWarehouseMachineApplyDetail::getBrandName));
        ArrayList<Object> brandList = new ArrayList<>();
        brands.forEach((key, value) -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", value.get(0).getBrandId());
            map.put("brandName", key);
            ArrayList<Object> snList = new ArrayList<>();
            for (KxsWarehouseMachineApplyDetail info : value) {
                HashMap<String, Object> sn = new HashMap<>();
                sn.put("id", info.getId());
                sn.put("posSn", info.getPosSn());
                snList.add(sn);
            }
            map.put("snList", snList);
            brandList.add(map);
        });
        machineApplyDetailVO.setBrandList(brandList);

        return machineApplyDetailVO;
    }
}

