package com.yiqi.admin.controller.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.common.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.app.domain.*;
import com.yiqi.app.domain.dto.*;
import com.yiqi.app.domain.vo.AppCouponItemVO;
import com.yiqi.app.domain.vo.AppCouponTypeApplyClothVO;
import com.yiqi.app.service.IAppCouponTypeApplyClothService;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.domain.BaseEntity;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.enums.*;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.core.domain.ClothItem;
import com.yiqi.core.service.IClothItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.yiqi.common.annotation.Log;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.app.service.IAppCouponItemService;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.common.core.page.TableDataInfo;

/**
 * 优惠券发放记录Controller
 *
 * @author xiaohei
 * @date 2023-09-19
 */
@Api(tags = "管理后台 - 优惠券发放记录")
@RestController
@RequestMapping(UrlConstants.managerApi + "/app/couponItem")
public class AppCouponItemController extends BaseController {
    @Autowired
    private IAppCouponItemService appCouponItemService;
    @Autowired
    private IAppCouponTypeApplyClothService appCouponTypeApplyClothService;
    @Autowired
    private IClothItemService clothItemService;


    @PostMapping(value = "getlistByAppUserId")
    @ApiOperation("选择客户可使用的优惠券")
    public R<List<AppCouponItemVO>> getlistByAppUserId(@RequestBody @Valid AppCouponItemQueryByAppUserIdDTO appCouponItemQueryByAppUserIdDTO) throws Exception {
        if (appCouponItemQueryByAppUserIdDTO.getClothIds() == null || appCouponItemQueryByAppUserIdDTO.getClothIds().size() == 0) {
            throw new ServiceException("未选择衣服");
        }
        Map<Long, ClothItem> clothItemMap = clothItemService.list(new QueryWrapper<ClothItem>().lambda()
                        .in(ClothItem::getId, appCouponItemQueryByAppUserIdDTO.getClothIds())).stream()
                .collect(Collectors.toMap(ClothItem::getId, ClothItem -> ClothItem));
        appCouponItemQueryByAppUserIdDTO.setDiscountWay(null);
        appCouponItemQueryByAppUserIdDTO.setStoreId(getStoreId());
        List<AppCouponItemVO> appCouponItemVOS = appCouponItemService.getlistByAppUserId(appCouponItemQueryByAppUserIdDTO);
        if (appCouponItemVOS == null || appCouponItemVOS.size() == 0) {
            return R.ok(appCouponItemVOS);
        }
        List<AppCouponTypeApplyCloth> appCouponTypeApplyCloths = appCouponTypeApplyClothService.list(
                new QueryWrapper<AppCouponTypeApplyCloth>().lambda()
                        .in(AppCouponTypeApplyCloth::getCouponTypeId
                                , appCouponItemVOS.stream().map(AppCouponItemVO::getCouponTypeId).collect(Collectors.toSet()))
                        .in(AppCouponTypeApplyCloth::getClothItemId, appCouponItemQueryByAppUserIdDTO.getClothIds()));
        List<AppCouponTypeApplyClothVO> appCouponTypeApplyClothVOS = new ArrayList<>();
        for (AppCouponTypeApplyCloth appCouponTypeApplyCloth : appCouponTypeApplyCloths) {
            AppCouponTypeApplyClothVO appCouponTypeApplyClothVO = new AppCouponTypeApplyClothVO();
            BeanUtils.copyProperties(appCouponTypeApplyCloth, appCouponTypeApplyClothVO);
            appCouponTypeApplyClothVO.setClothItemName(clothItemMap.get(appCouponTypeApplyCloth.getClothItemId()).getName());
            appCouponTypeApplyClothVOS.add(appCouponTypeApplyClothVO);
        }
        Map<Long, List<AppCouponTypeApplyClothVO>> appCouponTypeApplyClothMap = appCouponTypeApplyClothVOS.stream()
                .collect(Collectors.groupingBy(AppCouponTypeApplyClothVO::getCouponTypeId));

        for (AppCouponItemVO appCouponItemVO : appCouponItemVOS) {
            if (appCouponItemVO.getUseScope().equals(2)) {
                appCouponItemVO.setAppCouponTypeApplyClothVOS(appCouponTypeApplyClothMap.get(appCouponItemVO.getCouponTypeId()));
            }
        }
        return R.ok(appCouponItemVOS);
    }

    @ApiOperation("根据核销码查询优惠券")
    @GetMapping(value = "getInfoByDeductNo")
    public R<AppCouponItem> getInfoByDeductNo(@ApiParam("核销码") String deductNo, @RequestParam @ApiParam("客户ID") long appUserId
            , @RequestParam @ApiParam("优惠方式（0=抵扣,1=满减,2=折扣）") String discountWay) throws Exception {
        AppCouponItem appCouponItem = appCouponItemService.getOne(new QueryWrapper<AppCouponItem>().lambda()
                .eq(AppCouponItem::getAppUserId, appUserId).eq(AppCouponItem::getDeductNo, deductNo)
                .eq(AppCouponItem::getDiscountWay, discountWay)
                .eq(AppCouponItem::getIsUsed, SysBoolType.NO.getCode())
                .le(AppCouponItem::getStartDate, DateUtils.getNowDate())
                .ge(AppCouponItem::getEndDate, DateUtils.getNowDate(DateUtils.YYYY_MM_DD)), false);
        if (appCouponItem == null) {
            throw new ServiceException("未查询到优惠券");
        }
        return R.ok(appCouponItem);
    }

    @PostMapping(value = "/getMemberCouponInfo")
    @ApiOperation(value = "获取会员优惠券列表")
    public TableDataInfo getMemberCouponInfo(@RequestBody MemberCouponItemQueryDTO memberCouponItemQueryDTO) {
        startPage();
        AppCouponItemQueryDTO appCouponItemQueryDTO = new AppCouponItemQueryDTO();
        appCouponItemQueryDTO.setAppUserId(memberCouponItemQueryDTO.getAppUserId());
        List<AppCouponItemVO> list = appCouponItemService.selectAppCouponItemList(appCouponItemQueryDTO);
        return getDataTable(list);
    }

    @PostMapping(value = "/getMemberCouponInfoByRecharge")
    @ApiOperation(value = "获取会员可抵用充值优惠券列表")
    public R<Page<AppCouponItem>> getMemberCouponInfoByRecharge(@RequestBody @Valid MemberCouponItemQueryDTO memberCouponItemQueryDTO) {
        List<AppCouponItem> appCouponItems = appCouponItemService.getMemberCouponInfoByRecharge(memberCouponItemQueryDTO);
        Page<AppCouponItem> page = new Page<>();
        page.setRecords(appCouponItems);
        return R.ok(page);
    }

    /**
     * 查询优惠券发放记录列表
     */
    @PreAuthorize("@ss.hasPermi('app:couponItem:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询优惠券发放记录列表")
    public TableDataInfo list(AppCouponItemQueryDTO appCouponItemQueryDTO) {
        startPage();
        List<AppCouponItemVO> list = appCouponItemService.selectAppCouponItemList(appCouponItemQueryDTO);
        return getDataTable(list);
    }

    /**
     * 导出优惠券发放记录列表
     */
    @PreAuthorize("@ss.hasPermi('app:couponItem:export')")
    @Log(title = "优惠券发放记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出优惠券发放记录列表")
    public void export(HttpServletResponse response, AppCouponItemQueryDTO appCouponItemQueryDTO) {
        List<AppCouponItemVO> list = appCouponItemService.selectAppCouponItemList(appCouponItemQueryDTO);
        ExcelUtil<AppCouponItemVO> util = new ExcelUtil<AppCouponItemVO>(AppCouponItemVO.class);
        util.exportExcel(response, list, "优惠券发放记录数据");
    }

    /**
     * 获取优惠券发放记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('app:couponItem:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取优惠券发放记录详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(appCouponItemService.selectAppCouponItemById(id));
    }

    /**
     * 发放优惠券
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('app:couponItem:add')")
    @PostMapping("/sendCoupon")
    @ApiOperation(value = "发放优惠券")
    public R sendCoupon(@RequestBody @Valid AppCouponItemSendDTO appCouponItemSendDTO) {
        // 总部发放关注的是 优惠券本身属性
        String key = appCouponItemSendDTO.getCouponTypeId() + "";
        synchronized (key.intern()) {
            return R.ok(appCouponItemService.insertAppCouponItemByHQ(appCouponItemSendDTO));
        }

        // 门店发放关注的是 活动属性


//        if (SourceType.STORE.getCode().equals(SecurityUtils.getLoginUser().getSourceType())){
//            return R.ok(appCouponItemService.insertAppCouponItemByStore(appCouponItemSendDTO));
//        }
//        return R.ok("发放优惠劵失败");
    }


    /**
     * 修改优惠券发放记录
     */
    @PreAuthorize("@ss.hasPermi('app:couponItem:edit')")
    @Log(title = "优惠券发放记录", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改优惠券发放记录")
    public AjaxResult edit(@RequestBody AppCouponItem appCouponItem) {
        appCouponItem.setUpdateById(getUserId());
        appCouponItem.setUpdateBy(getUsername());
        return toAjax(appCouponItemService.updateAppCouponItem(appCouponItem));
    }

    /**
     * 删除优惠券发放记录
     */
    @PreAuthorize("@ss.hasPermi('app:couponItem:remove')")
    @Log(title = "优惠券发放记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除优惠券发放记录")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(appCouponItemService.deleteAppCouponItemByIds(ids));
    }

}
