package com.yiqi.api.controller.order;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.activity.domain.ActivityCouponInfo;
import com.yiqi.activity.domain.ActivityInfo;
import com.yiqi.activity.domain.vo.ActivityCouponInfoVO;
import com.yiqi.activity.domain.vo.ActivityInfoVO;
import com.yiqi.activity.service.IActivityCouponInfoService;
import com.yiqi.activity.service.IActivityInfoService;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.BaseEntity;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.enums.OrderSourceType;
import com.yiqi.common.enums.SourceType;
import com.yiqi.common.utils.StringUtils;
import com.yiqi.order.domain.OrderActivity;
import com.yiqi.order.domain.OrderActivityItem;
import com.yiqi.order.domain.dto.ActivityOrderDTO;
import com.yiqi.order.domain.dto.weapp.AppActivityOrderListQueryDTO;
import com.yiqi.order.domain.dto.weapp.AppGoodsOrderInfoQueryDTO;
import com.yiqi.order.domain.dto.weapp.WeAppActivityOrderDTO;
import com.yiqi.order.domain.vo.OrderActivityPayResultVO;
import com.yiqi.order.domain.vo.weapp.AppActivityOrderInfoQueryVO;
import com.yiqi.order.domain.vo.weapp.AppGoodsOrderInfoQueryVO;
import com.yiqi.order.service.IOrderActivityItemService;
import com.yiqi.order.service.IOrderActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "活动订单")
@RestController
@RequestMapping(UrlConstants.wxappApi + "/order/activity")
public class WeAppOrderActivityController extends BaseController {
    @Autowired
    private IOrderActivityService orderActivityService;
    @Autowired
    private IOrderActivityItemService orderActivityItemService;
    @Autowired
    private IActivityInfoService activityInfoService;
    @Autowired
    private IActivityCouponInfoService activityCouponInfoService;

    @ApiOperation(value = "APP分页获取活动订单列表")
    @PostMapping("/findPage")
    public R<List<AppActivityOrderInfoQueryVO>> getActivityOrderListByApp(@RequestBody AppActivityOrderListQueryDTO appActivityOrderListQueryDTO) {
        LambdaQueryWrapper<OrderActivity> queryWrapper = new QueryWrapper<OrderActivity>().lambda()
                .eq(OrderActivity::getAppUserId, AuthHolder.userId());
        if (StringUtils.isNotEmpty(appActivityOrderListQueryDTO.getOrderStatus())){
            queryWrapper.eq(OrderActivity::getOrderStatus, appActivityOrderListQueryDTO.getOrderStatus());
        }
        queryWrapper.orderByDesc(BaseEntity::getCreateTime);
        Page<OrderActivity> pageOrderActivity = orderActivityService.page(new Page<>(appActivityOrderListQueryDTO.getPageNum(), appActivityOrderListQueryDTO.getPageSize(),false)
                , queryWrapper);
        List<OrderActivity> orderActivityList = pageOrderActivity.getRecords();
        if (CollUtil.isEmpty(orderActivityList)){
            return R.ok(new ArrayList<>());
        }
        Set<String> orderNoList = orderActivityList.stream().map(OrderActivity::getOrderNo).collect(Collectors.toSet());
        List<OrderActivityItem> orderActivityItems = orderActivityItemService.list(new QueryWrapper<OrderActivityItem>().lambda()
                .in(OrderActivityItem::getOrderNo, orderNoList));
        Map<String, List<OrderActivityItem>> map = orderActivityItems.stream().collect(Collectors.groupingBy(OrderActivityItem::getOrderNo));

        Set<Long> activityIds = orderActivityList.stream().map(OrderActivity::getActivityId).collect(Collectors.toSet());
        Map<Long, ActivityInfo> activityInfoMap = activityInfoService.list(new QueryWrapper<ActivityInfo>().lambda()
                .in(ActivityInfo::getId,activityIds)).stream()
                .collect(Collectors.toMap(ActivityInfo::getId,ActivityInfo -> ActivityInfo));
        Map<Long, ActivityCouponInfo> activityCouponInfoMap = activityCouponInfoService
                .list(new QueryWrapper<ActivityCouponInfo>().lambda()
                        .in(ActivityCouponInfo::getActivityId,activityIds))
                .stream().collect(Collectors.toMap(ActivityCouponInfo::getActivityId,ActivityCouponInfo -> ActivityCouponInfo));

        List<AppActivityOrderInfoQueryVO> voList = new ArrayList<>();
        for (OrderActivity orderActivity : orderActivityList) {
            AppActivityOrderInfoQueryVO appActivityOrderInfoQueryVO = new AppActivityOrderInfoQueryVO();
            BeanUtils.copyProperties(orderActivity, appActivityOrderInfoQueryVO);
            appActivityOrderInfoQueryVO.setOrderActivityItemList(map.get(orderActivity.getOrderNo()));

            if(activityCouponInfoMap.containsKey(orderActivity.getActivityId())){
                ActivityCouponInfoVO activityCouponInfoVO = new ActivityCouponInfoVO();
                BeanUtils.copyProperties(activityCouponInfoMap.get(orderActivity.getActivityId()),activityCouponInfoVO);
                if(activityInfoMap.containsKey(orderActivity.getActivityId())){
                    BeanUtils.copyProperties(activityInfoMap.get(orderActivity.getActivityId()),activityCouponInfoVO);
                }
                appActivityOrderInfoQueryVO.setActivityCouponInfoVO(activityCouponInfoVO);
            }
            voList.add(appActivityOrderInfoQueryVO);
        }
        return R.ok(voList);
    }

    /**
     * 获取活动订单详细信息
     */
    @GetMapping(value = "/getInfo")
    @ApiOperation(value = "获取活动订单详细信息")
    public R<OrderActivity> getInfo(@RequestParam("id") Long id) {
        return R.ok(orderActivityService.selectOrderActivityById(id));
    }

    /**
     * 新增活动订单
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/add")
    @ApiOperation(value = "新增活动订单")
    public R<OrderActivityPayResultVO> add(@RequestBody @Valid WeAppActivityOrderDTO weAppActivityOrderDTO) {
        ActivityOrderDTO activityOrderDTO = new ActivityOrderDTO();
        BeanUtils.copyProperties(weAppActivityOrderDTO, activityOrderDTO);
        activityOrderDTO.setOrderSource(OrderSourceType.APP.getCode());
        activityOrderDTO.setAppUserId(AuthHolder.userId());
        activityOrderDTO.setSourceType(SourceType.STORE.getCode());
        activityOrderDTO.setOrgId(weAppActivityOrderDTO.getStoreId());
        return R.ok(orderActivityService.insertOrderActivity(activityOrderDTO));
    }

}
