package com.yc.ship.module.marketing.controller.admin.coupon;


import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.pojo.PageParam;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.collection.CollectionUtils;
import com.yc.ship.framework.common.util.collection.MapUtils;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.excel.core.util.ExcelUtils;
import com.yc.ship.framework.operatelog.core.annotations.OperateLog;
import com.yc.ship.module.marketing.controller.admin.coupon.vo.CouponPageReqVO;
import com.yc.ship.module.marketing.controller.admin.coupon.vo.CouponRespVO;
import com.yc.ship.module.marketing.controller.admin.coupon.vo.CouponSaveReqVO;
import com.yc.ship.module.marketing.dal.dataobject.coupon.CouponDO;
import com.yc.ship.module.marketing.dal.dataobject.couponCode.CouponCodeDO;
import com.yc.ship.module.marketing.service.coupon.CouponService;
import com.yc.ship.module.marketing.service.couponCode.CouponCodeService;
import com.yc.ship.module.system.api.user.AdminUserApi;
import com.yc.ship.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yc.ship.framework.common.pojo.CommonResult.success;
import static com.yc.ship.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;


@Tag(name = "管理后台 - 优惠券")
@RestController
@RequestMapping("/marketing/coupon")
@Validated
public class CouponController {

    @Resource
    private CouponService couponService;

    @Resource
    private CouponCodeService couponCodeService;
    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建优惠券")
    @PreAuthorize("@ss.hasPermission('marketing:coupon:create')")
    public CommonResult<Long> createCoupon(@Valid @RequestBody CouponSaveReqVO createReqVO) {
        return success(couponService.createCoupon(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新优惠券")
    @PreAuthorize("@ss.hasPermission('marketing:coupon:update')")
    public CommonResult<Boolean> updateCoupon(@Valid @RequestBody CouponSaveReqVO updateReqVO) {
        couponService.updateCoupon(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除优惠券")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('marketing:coupon:delete')")
    public CommonResult<Boolean> deleteCoupon(@RequestParam("id") Long id) {
        couponService.deleteCoupon(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得优惠券")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('marketing:coupon:query')")
    public CommonResult<CouponRespVO> getCoupon(@RequestParam("id") Long id) {
        CouponDO coupon = couponService.getCoupon(id);
        CouponRespVO couponRespVO = BeanUtils.toBean(coupon, CouponRespVO.class);
        return success(couponRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得优惠券分页")
    @PreAuthorize("@ss.hasPermission('marketing:coupon:query')")
    public CommonResult<PageResult<CouponRespVO>> getCouponPage(@Valid CouponPageReqVO pageReqVO) {
        PageResult<CouponDO> pageResult = couponService.getCouponPage(pageReqVO);
        PageResult<CouponRespVO> result = BeanUtils.toBean(pageResult, CouponRespVO.class);
        List<CouponRespVO> list = result.getList();
        List<String> creatorIds = CollectionUtils.convertList(list, CouponRespVO::getCreator);
        List<AdminUserRespDTO> userList = adminUserApi.getUserList(creatorIds.stream().distinct().map(Long::parseLong).collect(Collectors.toList()));
        Map<Long, AdminUserRespDTO> userMap = CollectionUtils.convertMap(userList, AdminUserRespDTO::getId);

        List<Long> couponIds = CollectionUtils.convertList(list, CouponRespVO::getId);
        List<CouponCodeDO> couponCodeList = couponCodeService.getGetNumAndUsedNumList(couponIds);
        Map<Long, CouponCodeDO> couponCodeMap = CollectionUtils.convertMap(couponCodeList, CouponCodeDO::getCouponId);
        list.stream().forEach(item -> {
            MapUtils.findAndThen(userMap, Long.parseLong(item.getCreator()), adminUserRespDTO -> item.setCreator(adminUserRespDTO.getNickname()));
            MapUtils.findAndThen(couponCodeMap, item.getId(), couponCodeDO -> item.setGetAndUseNum(couponCodeDO.getGetNum() + "/" + couponCodeDO.getUsedNum()));
        });
        return success(result);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出优惠券 Excel")
    @PreAuthorize("@ss.hasPermission('marketing:coupon:export')")
    @OperateLog(type = EXPORT,enable = false)
    public void exportCouponExcel(@Valid CouponPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CouponDO> list = couponService.getCouponPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "优惠券.xls", "数据", CouponRespVO.class,
                        BeanUtils.toBean(list, CouponRespVO.class));
    }

}