package com.hzs.activity.pick.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzs.activity.pick.param.RetailPickConfirmOrderParam;
import com.hzs.activity.pick.param.RetailPickProductParam;
import com.hzs.activity.pick.service.IAcRetailPickProductService;
import com.hzs.activity.pick.service.IAcRetailPickService;
import com.hzs.activity.pick.vo.RetailPickInfoVO;
import com.hzs.activity.pick.vo.RetailPickProductVO;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.enums.EOrderPrefix;
import com.hzs.common.core.enums.EOrderStatus;
import com.hzs.common.core.enums.EOrderType;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.activity.pick.AcRetailPick;
import com.hzs.common.domain.activity.pick.AcRetailPickProduct;
import com.hzs.common.domain.activity.pick.ext.AcRetailPickProductExt;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.sale.order.SaOrderItems;
import com.hzs.common.domain.system.base.BdStorehouse;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.order.service.impl.SaOrderHandle;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 新零售提货控制器
 * @Author: jiang chao
 * @Time: 2025/1/9 16:23
 * @Classname: ApiRetailPickController
 * @PackageName: com.hzs.activity.pick.controller.api
 */
@RestController
@RequestMapping("/api/retail-pick")
public class ApiRetailPickController extends BaseController {

    @Autowired
    private IAcRetailPickService iAcRetailPickService;
    @Autowired
    private IAcRetailPickProductService iAcRetailPickProductService;
    @Autowired
    private SaOrderHandle saOrderHandle;


    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;

    /**
     * 会员提货信息
     *
     * @return
     */
    @GetMapping("/info")
    public AjaxResult info() {
        AcRetailPick acRetailPick = iAcRetailPickService.getOne(Wrappers.<AcRetailPick>lambdaQuery()
                .eq(AcRetailPick::getPkMember, SecurityUtils.getUserId())
        );
        if (null == acRetailPick) {
            // 没有提货数据
            return AjaxResult.success(RetailPickInfoVO.builder()
                    .usableQuantity(0)
                    .build());
        }

        return AjaxResult.success(RetailPickInfoVO.builder()
                .usableQuantity(acRetailPick.getUsableQuantity())
                .build());
    }

    /**
     * 提货产品列表
     *
     * @return
     */
    @GetMapping("/product-list")
    public TableDataInfo productList() {
        List<RetailPickProductVO> pickProductVOList = new ArrayList<>();

        startPage();
        List<AcRetailPickProductExt> productList = iAcRetailPickProductService.listPickProduct(null, SecurityUtils.getPkCountry(), SecurityUtils.getSystemType());
        if (CollectionUtil.isNotEmpty(productList)) {
            for (AcRetailPickProductExt acRetailPickProduct : productList) {
                pickProductVOList.add(BeanUtil.copyProperties(acRetailPickProduct, RetailPickProductVO.class));
            }
        }

        TableDataInfo tableDataInfo = getDataTable(productList);
        tableDataInfo.setRows(pickProductVOList);
        return tableDataInfo;
    }

    /**
     * 提货产品信息
     *
     * @param param
     * @return
     */
    @PostMapping("/product-info")
    public AjaxResult productInfo(@Valid @RequestBody List<RetailPickProductParam> param) {
        List<Long> pkIdList = param.stream().map(RetailPickProductParam::getPkId).collect(Collectors.toList());

        // 产品数据
        List<AcRetailPickProductExt> productList = iAcRetailPickProductService.listPickProduct(pkIdList, SecurityUtils.getPkCountry(), SecurityUtils.getSystemType());
        Map<Long, AcRetailPickProductExt> productMap = productList.stream().collect(Collectors.toMap(AcRetailPickProductExt::getPkId, value -> value));

        // 返回数据列表
        List<RetailPickProductVO> resultList = new ArrayList<>(param.size());
        for (RetailPickProductParam tmpParam : param) {
            AcRetailPickProductExt product = productMap.get(tmpParam.getPkId());
            resultList.add(RetailPickProductVO.builder()
                    .pkId(tmpParam.getPkId())
                    .quantity(tmpParam.getQuantity())
                    .productName(product.getProductName())
                    .cover(product.getCover())
                    .showPrice(product.getShowPrice())
                    .build());
        }

        return AjaxResult.success(resultList);
    }

    /**
     * 支付订单
     *
     * @param param
     * @return
     */
    @RepeatSubmitSimple
    @PostMapping("/pay-order")
    public AjaxResult payOrder(@Valid @RequestBody RetailPickConfirmOrderParam param) {
        // 会员ID
        Long userId = SecurityUtils.getUserId();
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 系统类型
        Integer systemType = SecurityUtils.getSystemType();

        // 提货ID列表
        List<Long> pickProductPkList = new ArrayList<>(param.getProductList().size());
        // 提货数量
        Integer pickCount = 0;
        for (RetailPickProductParam retailPickProductParam : param.getProductList()) {
            pickProductPkList.add(retailPickProductParam.getPkId());
            pickCount += retailPickProductParam.getQuantity();
        }
        // 查询提货商品列表
        List<AcRetailPickProductExt> pickProductList = iAcRetailPickProductService.listPickProduct(pickProductPkList, pkCountry, systemType);
        if (CollectionUtil.isEmpty(pickProductList) || pickProductList.size() != pickProductPkList.size()) {
            // 提货商品列表为空，或者提货商品列表和前台传入数量不一致，则为商品不足，不能进行提货
            return AjaxResult.error("提货商品不存在或已下架，请重新选择商品");
        }

        // 校验会员可提次数
        AcRetailPick acRetailPick = iAcRetailPickService.getOne(Wrappers.<AcRetailPick>lambdaQuery()
                .eq(AcRetailPick::getPkMember, userId)
        );
        if (null == acRetailPick) {
            return AjaxResult.error("没有可提货数量");
        }
        if (acRetailPick.getUsableQuantity() < pickCount) {
            // 可提数量小于本次提货数量
            return AjaxResult.error("剩余可提货数量不足");
        }

        // 验证密码
        CuMember cuMember = iMemberServiceApi.getRetailMember(userId, null).getData();
        if (!SecurityUtils.matchesPassword(param.getPayPwd(), cuMember.getPayPwd())) {
            return AjaxResult.error("支付密码输入错误，请重新输入");
        }

        // 获取汇率
        CurrencyDTO currency = iCurrencyServiceApi.getCurrency(pkCountry).getData();

        // 当前时间
        Date nowDate = new Date();

        // 生成订单
        SaOrder saOrder = SaOrder.builder()
                .orderCode(saOrderHandle.createOrderCode(EOrderPrefix.ORDER_CODE.getValue()))
                .orderType(EOrderType.RETAIL_PICK.getValue())
                .pkRate(currency.getPkId())
                .orderAmount(BigDecimal.ZERO)
                .orderAchieve(BigDecimal.ZERO)
                .uploadAchieve(BigDecimal.ZERO)
                .orderAssAchieve(BigDecimal.ZERO)
                .postage(BigDecimal.ZERO)
                .recName(param.getRecName())
                .recPhone(param.getRecPhone())
                .recProvince(param.getRecProvince())
                .recCity(param.getRecCity())
                .recCounty(param.getRecCounty())
                .recAddress(param.getRecAddress())
                .remark(param.getRemark())
                .payTime(nowDate)
                .orderStatus(EOrderStatus.PAY.getValue())
                .deliveryWay(param.getDeliveryWay())
                .pkMember(userId)
                .pkReference(cuMember.getPkParent())
                .tranType(param.getTranType())
                .pkVertex(cuMember.getPkVertex())
                .systemType(systemType)
                .build();
        if (param.getRecProvince() != null) {
            // 根据收货省获取仓库
            BdStorehouse bdStorehouse = iCurrencyServiceApi.queryBdStorehouseByProvince(param.getRecProvince()).getData();
            if (bdStorehouse != null) {
                saOrder.setPkStorehouse(bdStorehouse.getPkId());
            }
        }
        saOrder.setPkCreator(userId);
        saOrder.setCreationTime(nowDate);
        saOrder.setPkCountry(pkCountry);

        // 订单明细
        List<SaOrderItems> saOrderItemsList = new ArrayList<>(pickProductList.size());
        // 产品对应map
        Map<Long, AcRetailPickProductExt> pickProductMap = pickProductList.stream().collect(Collectors.toMap(AcRetailPickProduct::getPkId, val -> val));
        for (RetailPickProductParam productParam : param.getProductList()) {
            // 产品信息
            AcRetailPickProductExt product = pickProductMap.get(productParam.getPkId());
            SaOrderItems saOrderItems = SaOrderItems.builder()
                    .pkProduct(product.getPkProduct())
                    .pkWares(0)
                    .pkWaresDetail(0)
                    .pkWaresSpecsSku(0)
                    .price(BigDecimal.ZERO)
                    .achievement(BigDecimal.ZERO)
                    .assAchievement(BigDecimal.ZERO)
                    .quantity(productParam.getQuantity())
                    .waresQuantity(productParam.getQuantity())
                    .pkRate(currency.getPkId())
                    .isGift(EYesNo.NO.getIntValue())
                    .specsName(product.getSpecsName())
                    .specsNameId(product.getSpecsNameId())
                    .skuCode(CommonUtil.createSkuCode(product.getProductCode(), product.getSpecsNameId()))
                    .build();
            if (saOrderItems.getIsGift() != null && EYesNo.YES.getIntValue() == saOrderItems.getIsGift()) {
                // 赠品不计算金额、业绩等
                saOrderItems.setPrice(BigDecimal.ZERO);
                saOrderItems.setAchievement(BigDecimal.ZERO);
                saOrderItems.setAssAchievement(BigDecimal.ZERO);
            }
            saOrderItems.setPkGrade(cuMember.getPkSettleGrade());
            saOrderItems.setPkAwards(cuMember.getPkAwards());
            saOrderItems.setPkStorehouse(saOrder.getPkStorehouse());
            saOrderItems.setOrderStatus(saOrder.getOrderStatus());
            saOrderItems.setPkCreator(saOrder.getPkCreator());
            saOrderItems.setCreationTime(saOrderItems.getCreationTime());
            saOrderItems.setPkCountry(saOrder.getPkCountry());
            saOrderItemsList.add(saOrderItems);
        }

        // 提货数量
        acRetailPick.setUsedQuantity(pickCount);
        iAcRetailPickService.payOrder(acRetailPick, saOrder, saOrderItemsList);

        return AjaxResult.success();
    }

}
