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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.activity.pick.param.PickOrderParam;
import com.hzs.activity.pick.param.PickPostageParam;
import com.hzs.activity.pick.service.IAcPickMemberLogService;
import com.hzs.activity.pick.service.IAcPickService;
import com.hzs.activity.pick.vo.ApiPickDetailVO;
import com.hzs.activity.pick.vo.ApiPickVO;
import com.hzs.activity.wares.service.IAcGiftConfigService;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.ActivityMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.StringUtils;
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.base.ext.AcGiftConfigExt;
import com.hzs.common.domain.activity.pick.AcPick;
import com.hzs.common.domain.activity.pick.AcPickMemberLog;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.ext.SaOrderExt;
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.common.util.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.product.IProductServiceApi;
import com.hzs.sale.product.dto.ProductDTO;
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 java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 会员端提货处理控制器
 * @Author: jiang chao
 * @Time: 2023/4/24 13:55
 * @Classname: ApiPickController
 * @PackageName: com.hzs.activity.pick.controller.api
 */
@RequestMapping("/api/pick")
@RestController
public class ApiPickController extends BaseController {

    @Autowired
    private IAcPickService iAcPickService;
    @Autowired
    private IAcPickMemberLogService iAcPickMemberLogService;
    @Autowired
    private IAcGiftConfigService iAcGiftConfigService;

    @Autowired
    private RedisService redisService;

    @DubboReference
    IProductServiceApi iProductServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;

    /**
     * 查询提货列表
     *
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list() {
        return AjaxResult.success(iAcPickService.pickList(SecurityUtils.getUserId(), SecurityUtils.getPkCountry()));
    }

    /**
     * 查询提货详情
     *
     * @param pkId     提货ID
     * @param quantity 提货数量
     * @return
     */
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam("pkId") Long pkId, @RequestParam("quantity") Integer quantity) {
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();

        QueryWrapper<AcPick> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_ID, pkId);
        queryWrapper.eq("PK_MEMBER", SecurityUtils.getUserId());
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        AcPick acPick = iAcPickService.getOne(queryWrapper);
        if (null == acPick) {
            // 会员提货商品不存在
            return AjaxResult.error(TransactionUtils.getContent(ActivityMsgConstants.PICK_PRODUCT_NOT_EXIST));
        }
        if (quantity > acPick.getUsableQuantity()) {
            // 会员提货商品数量不足
            return AjaxResult.error(TransactionUtils.getContent(ActivityMsgConstants.PICK_QUANTITY_NOT_ENOUGH));
        }

        // 提货详情VO
        ApiPickVO apiPickVO = new ApiPickVO();
        // 提货产品明细列表
        List<ApiPickDetailVO> detailList = new ArrayList<>();

        // 根据各种提货不同进行处理
        switch (EPickType.getEnumByValue(acPick.getPickType())) {
            case PICK_PRODUCT:
            case PRIZE:
                // 提货产品处理、迁移抽奖处理
                // 查询产品
                ProductDTO productDTO = iProductServiceApi.getProduct(acPick.getPkDataId().intValue()).getData();
                // 处理提货产品明细
                detailList.add(ApiPickDetailVO.builder()
                        .productName(productDTO.getProductName())
                        .specsName(acPick.getSpecsName())
                        .cover(StringUtils.isNotEmpty(acPick.getPickCover()) ? acPick.getPickCover() : productDTO.getCover())
                        .quantity(quantity)
                        .build());
                break;
//            case MAKER_SEA_BUCKTHORN:
//            case REPURCHASE_PICK:
//                // 迁移创客沙棘提货、迁移复购提货处理
//                if (quantity % acPick.getBaseQuantity() != 0) {
//                    // 提货数量只能为%s的倍数
//                    return AjaxResult.error(TransactionUtils.getContent(ActivityMsgConstants.PICK_QUANTITY_BASE, acPick.getBaseQuantity()));
//                }
//                // 查询产品
//                ProductDTO seaProductDTO = iProductServiceApi.getProduct(acPick.getPkDataId().intValue()).getData();
//                // 处理提货产品明细
//                detailList.add(ApiPickDetailVO.builder()
//                        .productName(seaProductDTO.getProductName())
//                        .specsName(acPick.getSpecsName())
//                        .cover(StringUtils.isNotEmpty(acPick.getPickCover()) ? acPick.getPickCover() : seaProductDTO.getCover())
//                        .quantity(quantity)
//                        .build());
//                break;
            case LOTTERY_DRAW:
            case CONSUMPTION_GIFT:
            case DIRECT_PUSH_GIFT:
                // 抽奖活动、消费赠送活动、直推赠送活动
                // 处理提货产品明细
                List<AcGiftConfigExt> giftConfigList = iAcGiftConfigService.queryListByRuleIdList(acPick.getPkDataId(), pkCountry);
                for (AcGiftConfigExt acGiftConfigExt : giftConfigList) {
                    // 处理提货产品明细
                    detailList.add(ApiPickDetailVO.builder()
                            .productName(acGiftConfigExt.getProductName())
                            .specsName(acGiftConfigExt.getSpecsName())
                            .cover(acGiftConfigExt.getCover())
                            .quantity(acGiftConfigExt.getQuantity())
                            .build());
                }
                break;
        }

        apiPickVO.setIsFreeMail(acPick.getIsFreeMail());
        apiPickVO.setDetailList(detailList);

        return AjaxResult.success(apiPickVO);
    }

    /**
     * 查询提货邮费
     *
     * @param param 提货邮费参数
     * @return
     */
    @GetMapping("/postage")
    public AjaxResult postage(PickPostageParam param) {
        if (null == param.getPkId() || null == param.getQuantity() || null == param.getRecProvince() || null == param.getRecCity()) {
            // 缺少参数
            return AjaxResult.error("缺少参数");
        }
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();

        QueryWrapper<AcPick> pickQueryWrapper = new QueryWrapper<>();
        pickQueryWrapper.eq(SystemFieldConstants.PK_ID, param.getPkId());
        pickQueryWrapper.eq("PK_MEMBER", SecurityUtils.getUserId());
        pickQueryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        AcPick acPick = iAcPickService.getOne(pickQueryWrapper);
        if (null == acPick) {
            // 会员提货商品不存在
            return AjaxResult.error(TransactionUtils.getContent(ActivityMsgConstants.PICK_PRODUCT_NOT_EXIST));
        }

        // 邮费
        BigDecimal postage = iAcPickService.postageHandle(acPick, param.getQuantity(), param.getRecProvince(), param.getRecCity(), pkCountry);
        if (null == postage) {
            // 提货邮费计算错误
            return AjaxResult.error(TransactionUtils.getContent(ActivityMsgConstants.PICK_POSTAGE_ERROR));
        }
        return AjaxResult.success(postage);
    }

    /**
     * 提货下单
     *
     * @param param 提货下单参数
     * @return
     */
    @RepeatSubmitSimple
    @PostMapping("/order")
    public AjaxResult order(@RequestBody PickOrderParam param) {
        if (null == param.getPkId() || null == param.getQuantity() || null == param.getRecProvince() || null == param.getRecCity()
                || StringUtils.isAnyEmpty(param.getRecName(), param.getRecPhone(), param.getRecAddress())) {
            // 缺少参数
            return AjaxResult.error("缺少参数");
        }

        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 当前用户
        Long userId = SecurityUtils.getUserId();
        // 当前时间
        Date nowDate = new Date();

        QueryWrapper<AcPick> pickQueryWrapper = new QueryWrapper<>();
        pickQueryWrapper.eq(SystemFieldConstants.PK_ID, param.getPkId());
        pickQueryWrapper.eq("PK_MEMBER", userId);
        pickQueryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        AcPick acPick = iAcPickService.getOne(pickQueryWrapper);
        if (null == acPick) {
            // 会员提货商品不存在
            return AjaxResult.error(TransactionUtils.getContent(ActivityMsgConstants.PICK_PRODUCT_NOT_EXIST));
        }
        if (!acPick.getUsableQuantity().equals(param.getQuantity()) && param.getQuantity() % acPick.getBaseQuantity() != 0) {
            // 提货数量等于可提数量 或 提货数量是提货基数的倍数才能进行处理
            return AjaxResult.error(TransactionUtils.getContent(ActivityMsgConstants.PICK_QUANTITY_BASE, acPick.getBaseQuantity()));
        }

        // 邮费
        BigDecimal postage = iAcPickService.postageHandle(acPick, param.getQuantity(), param.getRecProvince(), param.getRecCity(), pkCountry);
        if (null == postage) {
            // 提货邮费计算错误
            return AjaxResult.error(TransactionUtils.getContent(ActivityMsgConstants.PICK_POSTAGE_ERROR));
        }

        // 查询会员信息
        CuMember cuMember = iMemberServiceApi.getMember(userId).getData();
        // 查询汇率
        CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(pkCountry).getData();
        // 生成订单编号
        String orderCode = CommonUtil.createSerialNumber(EOrderPrefix.ORDER_CODE);

        // 根据收货省获取仓库
        BdStorehouse storehouse = iCurrencyServiceApi.queryBdStorehouseByProvince(param.getRecProvince()).getData();

        // 生成订单信息
        SaOrderExt saOrder = new SaOrderExt();
        saOrder.setOrderCode(orderCode);
        saOrder.setOrderType(EOrderType.PICK_ORDER.getValue());
        saOrder.setPkRate(currencyDTO.getPkId());
        saOrder.setOrderAmount(BigDecimal.ZERO);
        saOrder.setPostage(postage);
        saOrder.setRecName(param.getRecName());
        saOrder.setRecPhone(param.getRecPhone());
        saOrder.setRecProvince(param.getRecProvince());
        saOrder.setRecCity(param.getRecCity());
        saOrder.setRecCounty(param.getRecCounty());
        saOrder.setRecAddress(param.getRecAddress());
        saOrder.setRemark(param.getRemark());
        saOrder.setPkMember(userId);
        saOrder.setPkReference(cuMember.getPkParent());
        saOrder.setTranType(ETransportType.LAND.getValue());
        saOrder.setPkVertex(cuMember.getPkVertex());
        if (null != storehouse) {
            saOrder.setPkStorehouse(storehouse.getPkId());
        }
        saOrder.setPkCreator(userId);
        saOrder.setCreationTime(nowDate);
        saOrder.setPkCountry(pkCountry);

        // 生成订单明细信息
        List<SaOrderItems> orderItemsList = new ArrayList<>();

        // 根据各种提货不同进行处理
        switch (EPickType.getEnumByValue(acPick.getPickType())) {
            case PICK_PRODUCT:
            case PRIZE:
                // 提货产品处理、迁移抽奖处理
                // 查询产品信息
                ProductDTO productDTO = iProductServiceApi.getProduct(acPick.getPkDataId().intValue()).getData();

                // 处理提货产品明细
                SaOrderItems productOrderItems = new SaOrderItems();
                productOrderItems.setPkProduct(acPick.getPkDataId().intValue());
                productOrderItems.setPkRate(currencyDTO.getPkId());
                productOrderItems.setQuantity(param.getQuantity());
                productOrderItems.setPkGrade(cuMember.getPkSettleGrade());
                productOrderItems.setPkAwards(cuMember.getPkAwards());
                productOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
                productOrderItems.setPkCreator(userId);
                productOrderItems.setCreationTime(nowDate);
                productOrderItems.setSpecsName(acPick.getSpecsName());
                productOrderItems.setSpecsNameId(acPick.getSpecsNameId());
                productOrderItems.setPkCountry(pkCountry);
                productOrderItems.setWaresQuantity(param.getQuantity());
                productOrderItems.setSkuCode(CommonUtil.createSkuCode(productDTO.getProductCode(), acPick.getSpecsNameId()));
                productOrderItems.setPkStorehouse(saOrder.getPkStorehouse());
                orderItemsList.add(productOrderItems);
                break;
//            case MAKER_SEA_BUCKTHORN:
//            case REPURCHASE_PICK:
//                // 迁移创客沙棘提货、迁移复购提货处理
//                if (param.getQuantity() % acPick.getBaseQuantity() != 0) {
//                    // 提货数量只能为%s的倍数
//                    return AjaxResult.error(TransactionUtils.getContent(ActivityMsgConstants.PICK_QUANTITY_BASE, acPick.getBaseQuantity()));
//                }
//                // 查询产品信息
//                ProductDTO msbProductDTO = iProductServiceApi.getProduct(acPick.getPkDataId().intValue()).getData();
//
//                // 处理提货产品明细
//                SaOrderItems msbOrderItems = new SaOrderItems();
//                msbOrderItems.setPkProduct(acPick.getPkDataId().intValue());
//                msbOrderItems.setPkRate(currencyDTO.getPkId());
//                msbOrderItems.setQuantity(param.getQuantity());
//                msbOrderItems.setPkGrade(cuMember.getPkSettleGrade());
//                msbOrderItems.setPkAwards(cuMember.getPkAwards());
//                msbOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
//                msbOrderItems.setPkCreator(userId);
//                msbOrderItems.setCreationTime(nowDate);
//                msbOrderItems.setSpecsName(acPick.getSpecsName());
//                msbOrderItems.setSpecsNameId(acPick.getSpecsNameId());
//                msbOrderItems.setPkCountry(pkCountry);
//                msbOrderItems.setWaresQuantity(param.getQuantity());
//                msbOrderItems.setSkuCode(CommonUtil.createSkuCode(msbProductDTO.getProductCode(), acPick.getSpecsNameId()));
//                orderItemsList.add(msbOrderItems);
//                break;
            case LOTTERY_DRAW:
            case CONSUMPTION_GIFT:
            case DIRECT_PUSH_GIFT:
                // 抽奖活动、商品赠品活动、消费赠送活动、直推赠送活动

                // 处理提货产品明细
                List<AcGiftConfigExt> giftConfigList = iAcGiftConfigService.queryListByRuleIdList(acPick.getPkDataId(), pkCountry);
                for (AcGiftConfigExt acGiftConfigExt : giftConfigList) {
                    // 查询产品信息
                    ProductDTO giftProductDTO = iProductServiceApi.getProduct(acGiftConfigExt.getPkProduct()).getData();
                    if (null == giftProductDTO) {
                        return AjaxResult.error("提货产品不存在，请联系客服处理");
                    }

                    SaOrderItems giftOrderItems = new SaOrderItems();
                    giftOrderItems.setPkProduct(acGiftConfigExt.getPkProduct());
                    giftOrderItems.setPkRate(currencyDTO.getPkId());
                    giftOrderItems.setQuantity(param.getQuantity() * acGiftConfigExt.getQuantity());
                    giftOrderItems.setPkGrade(cuMember.getPkSettleGrade());
                    giftOrderItems.setPkAwards(cuMember.getPkAwards());
                    giftOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
                    giftOrderItems.setPkCreator(userId);
                    giftOrderItems.setCreationTime(nowDate);
                    giftOrderItems.setSpecsName(acPick.getSpecsName());
                    giftOrderItems.setSpecsNameId(acPick.getSpecsNameId());
                    giftOrderItems.setPkCountry(pkCountry);
                    giftOrderItems.setWaresQuantity(param.getQuantity());
                    giftOrderItems.setSkuCode(CommonUtil.createSkuCode(giftProductDTO.getProductCode(), acPick.getSpecsNameId()));
                    orderItemsList.add(giftOrderItems);
                }
                break;
            default:
        }
        saOrder.setOrderItemsList(orderItemsList);

        // 添加提货日志
        AcPickMemberLog acPickMemberLog = new AcPickMemberLog();
        acPickMemberLog.setPkMember(userId);
        acPickMemberLog.setPkPick(acPick.getPkId());
        acPickMemberLog.setPickQuantity(param.getQuantity());
        acPickMemberLog.setPickTime(nowDate);
        acPickMemberLog.setPickOrder(orderCode);
        acPickMemberLog.setPkCountry(pkCountry);
        iAcPickMemberLogService.save(acPickMemberLog);

        // 临时订单直接放入缓存
        redisService.setCacheObject(CacheConstants.TEMP_ORDER + userId + orderCode, saOrder, CacheConstants.MEMBER_REFRESH_TIME, TimeUnit.MINUTES);

        return AjaxResult.success("", orderCode);
    }

    /**
     * 提货日志
     *
     * @return
     */
    @GetMapping("/pick-log")
    public TableDataInfo pickLog() {
        startPage();
        return getDataTable(iAcPickMemberLogService.queryMemberLog(SecurityUtils.getUserId()));
    }

}
