package com.yiqi.api.controller.order;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.common.annotation.Log;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.PageVO;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.enums.*;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.order.domain.OrderRecharge;
import com.yiqi.order.domain.dto.OrderRechargeCreateDTO;
import com.yiqi.order.domain.vo.OrderPayResultVO;
import com.yiqi.order.domain.vo.weapp.AppOrderRechargeResultVO;
import com.yiqi.order.domain.vo.weapp.WeAppOrderRechargeVO;
import com.yiqi.order.service.IOrderRechargeService;
import com.yiqi.recharge.domain.dto.weapp.WeAppCardRechargeDTO;
import com.yiqi.recharge.domain.dto.weapp.WeAppCardRecordByCardDTO;
import com.yiqi.recharge.domain.dto.weapp.WeAppCardRecordByUserDTO;
import com.yiqi.recharge.domain.dto.weapp.WeAppRechargeDTO;
import com.yiqi.recharge.domain.vo.weapp.WeAppCardsInfoVO;
import com.yiqi.recharge.domain.vo.weapp.WeAppCardsUseRecordsVO;
import com.yiqi.recharge.service.IRechargePasswordCardService;
import com.yiqi.system.domain.SysOrg;
import com.yiqi.system.service.ISysOrgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zjw
 * @date 2023/11/15
 */
@Api(tags = "订单充值")
@RestController
@RequestMapping(value = UrlConstants.wxappApi + "/order/recharge")
@Slf4j
public class WeAppOrderRechargeController {
    @Autowired
    private IOrderRechargeService orderRechargeService;
    @Autowired
    private IRechargePasswordCardService rechargePasswordCardService;
    @Autowired
    private ISysOrgService sysOrgService;

    /**
     * app卡密充值
     */
    @Log(title = "app卡密充值", businessType = BusinessType.INSERT)
    @PostMapping(value = "/cardRechargeOrder")
    @ApiOperation(value = "app卡密充值")
    public R<AppOrderRechargeResultVO> cardRechargeOrder(@RequestBody WeAppCardRechargeDTO weAppCardRechargeDTO) {
        OrderRechargeCreateDTO orderRechargeCreateDTO = new OrderRechargeCreateDTO();
        orderRechargeCreateDTO.setOrderSource(OrderSourceType.APP.getCode());
        orderRechargeCreateDTO.setCardNo(weAppCardRechargeDTO.getCardNo());
        orderRechargeCreateDTO.setPassword(weAppCardRechargeDTO.getPassword());
        orderRechargeCreateDTO.setRechargeType(RechargeTypeEnum.CARD.getCode());
        orderRechargeCreateDTO.setAppUserId(AuthHolder.userId());
        AppOrderRechargeResultVO appOrderRechargeResultVO = new AppOrderRechargeResultVO();
        BeanUtils.copyProperties(orderRechargeService.insertOrderRechargeByPasscard(orderRechargeCreateDTO), appOrderRechargeResultVO);
        return R.ok(appOrderRechargeResultVO);
    }

    /**
     * app套餐充值
     */
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "app套餐充值", businessType = BusinessType.INSERT)
    @PostMapping(value = "/payRechargeOrder")
    @ApiOperation(value = "app套餐充值")
    public R<OrderPayResultVO> payRechargeOrder(@RequestBody @Valid WeAppRechargeDTO weAppRechargeDTO) {
        try {
            // 1. 构建充值订单参数
            OrderRechargeCreateDTO orderRechargeCreateDTO = new OrderRechargeCreateDTO();
            orderRechargeCreateDTO.setOrderSource(OrderSourceType.APP.getCode());
            orderRechargeCreateDTO.setRechargeType(RechargeTypeEnum.PACKAGE.getCode());
            orderRechargeCreateDTO.setAppUserId(AuthHolder.userId());
            orderRechargeCreateDTO.setRechargeTypeId(weAppRechargeDTO.getRechargeTypeId());
            orderRechargeCreateDTO.setPayType(weAppRechargeDTO.getPayType());
            orderRechargeCreateDTO.setOrgId(weAppRechargeDTO.getOrgId());
            orderRechargeCreateDTO.setPlatform(weAppRechargeDTO.getPlatform());
            // 2. 创建并处理充值订单
            OrderPayResultVO resultVO = orderRechargeService.createRechargeOrder(orderRechargeCreateDTO);
            return R.ok(resultVO);

        } catch (ServiceException e) {
            log.error("套餐充值失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("套餐充值异常", e);
            return R.fail("充值失败,请稍后重试");
        }

    }

    /**
     * 按客户获取充值卡信息
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/getPasswordCardsInfoByAppUserId")
    @ApiOperation(value = "按客户获取会员卡明细")
    public R<List<WeAppCardsInfoVO>> getPasswordCardsInfoByAppUserId(@RequestBody WeAppCardRecordByUserDTO weAppCardRecordByUserDTO) {
        return R.ok(rechargePasswordCardService.getPasswordCardsInfoByAppUserId(weAppCardRecordByUserDTO));
    }

    /**
     * 按充值卡查消费记录
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/getUseRecordsByCardId")
    @ApiOperation(value = "按充值卡获取消费记录明细")
    public R<WeAppCardsUseRecordsVO> getUseRecordsByCardId(@RequestBody WeAppCardRecordByCardDTO weAppCardRecordByCardDTO) {
        weAppCardRecordByCardDTO.setAppUserId(AuthHolder.userId());
        return R.ok(rechargePasswordCardService.getUseRecordsByCardId(weAppCardRecordByCardDTO));
    }

    @PostMapping(value = "findPage")
    @ApiOperation("分页查询充值订单")
    public R<List<WeAppOrderRechargeVO>> findPage(@RequestBody PageVO pageVO) throws Exception {
        List<OrderRecharge> orderRecharges = orderRechargeService.page(new Page<>(pageVO.getPageNum(), pageVO.getPageSize(), false)
                , new QueryWrapper<OrderRecharge>().lambda()
                        .eq(OrderRecharge::getAppUserId, AuthHolder.userId())
                        .eq(OrderRecharge::getOrderStatus, OrderRechargeStatus.YES_PAY.getCode())
                        .orderByDesc(OrderRecharge::getCreateTime)).getRecords();
        if (orderRecharges.size() == 0) {
            return R.ok(new ArrayList<>());
        }
        Map<Long, SysOrg> sysOrgMap = new HashMap<>();
        if (orderRecharges.stream()
                .map(OrderRecharge::getStoreId).collect(Collectors.toSet()).size() > 0) {
            sysOrgMap = sysOrgService.list(new QueryWrapper<SysOrg>().lambda()
                            .eq(SysOrg::getSourceType, SourceType.STORE.getCode())
                            .in(SysOrg::getId, orderRecharges.stream()
                                    .map(OrderRecharge::getStoreId).collect(Collectors.toSet())))
                    .stream().collect(Collectors.toMap(SysOrg::getId, SysOrg -> SysOrg));
        }
        List<WeAppOrderRechargeVO> weAppOrderRechargeVOS = new ArrayList<>();

        for (OrderRecharge orderRecharge : orderRecharges) {
            WeAppOrderRechargeVO weAppOrderRechargeVO = new WeAppOrderRechargeVO();
            BeanUtils.copyProperties(orderRecharge, weAppOrderRechargeVO);
            if (sysOrgMap.containsKey(weAppOrderRechargeVO.getOrgId())) {
                weAppOrderRechargeVO.setSysOrg(sysOrgMap.get(weAppOrderRechargeVO.getOrgId()));
            }
            weAppOrderRechargeVOS.add(weAppOrderRechargeVO);
        }
        return R.ok(weAppOrderRechargeVOS);
    }
}
