package com.yiqi.admin.controller.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.app.domain.AppCouponTypeApplyOrg;
import com.yiqi.app.domain.dto.AppCouponTypeDTO;
import com.yiqi.app.service.IAppCouponTypeApplyOrgService;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.enums.DeleteStatus;
import com.yiqi.common.enums.SourceType;
import com.yiqi.common.enums.StatusType;
import com.yiqi.common.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.common.enums.BusinessType;
import com.yiqi.app.domain.AppCouponType;
import com.yiqi.app.service.IAppCouponTypeService;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.common.core.page.TableDataInfo;

import static com.yiqi.common.utils.DateUtils.YYYY_MM_DD;

/**
 * 优惠券类型Controller
 *
 * @author xiaohei
 * @date 2023-09-06
 */
@Api(tags = "管理后台 - 优惠券类型")
@RestController
@RequestMapping(UrlConstants.managerApi + "/coupon/type")
public class AppCouponTypeController extends BaseController {
    @Autowired
    private IAppCouponTypeService appCouponTypeService;
    @Autowired
    private IAppCouponTypeApplyOrgService appCouponTypeApplyOrgService;
    /**
     * 查询优惠券类型列表
     */
    @PreAuthorize("@ss.hasPermi('coupon:type:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询优惠券类型列表")
    public TableDataInfo list(AppCouponType appCouponType) {
        startPage();
        List<AppCouponType> list = appCouponTypeService.selectAppCouponTypeList(appCouponType);
        return getDataTable(list);
    }

    

    /**
     * 1=手动券,2=活动券,9=新用户赠送券
     * @param sendWay
     * @return
     */
    @GetMapping("/all")
    @ApiOperation(value = "查询所有优惠券类型")
    public R<List<AppCouponType>> all(@RequestParam Integer sendWay) {
        List<AppCouponType> list = appCouponTypeService.list(new QueryWrapper<AppCouponType>().lambda()
                .eq(AppCouponType::getStatus, StatusType.OK.getCode())
                        .eq(AppCouponType::getSendWay, sendWay)
                .eq(AppCouponType::getDelFlag, DeleteStatus.OK.getCode()));
        return R.ok(list);
    }

    @GetMapping("/allValidByStoreId")
    @ApiOperation(value = "查询适用门店的，所有有效优惠券类型")
    public R<List<AppCouponType>> allValidByStoreId(@RequestParam Long orgId) {
        List<AppCouponType> list = appCouponTypeService.list(new QueryWrapper<AppCouponType>().lambda()
                .eq(AppCouponType::getStatus, StatusType.OK.getCode())
                        .eq(AppCouponType::getSendWay, 1)
                .eq(AppCouponType::getDelFlag, DeleteStatus.OK.getCode())
                .ge(AppCouponType::getEndDate, DateUtils.getNowDate(YYYY_MM_DD)));
        if (CollUtil.isEmpty(list)){
            return R.ok(list);
        }
        Set<Long> collect = list.stream().map(AppCouponType::getId).collect(Collectors.toSet());
        List<AppCouponTypeApplyOrg> applyOrgList = appCouponTypeApplyOrgService.list(new QueryWrapper<AppCouponTypeApplyOrg>().lambda()
                .in(AppCouponTypeApplyOrg::getCouponTypeId, collect)
                .eq(AppCouponTypeApplyOrg::getSourceType, SourceType.STORE.getCode())
                .eq(AppCouponTypeApplyOrg::getOrgId, orgId));
        if (CollUtil.isEmpty(applyOrgList)){
            return R.ok(new ArrayList<>());
        }
        Set<Long> set = applyOrgList.stream().map(AppCouponTypeApplyOrg::getCouponTypeId).collect(Collectors.toSet());

        List<AppCouponType> appCouponTypeList = list.stream().filter(vo -> set.contains(vo.getId())).collect(Collectors.toList());
        return R.ok(appCouponTypeList);
    }

    /**
     * 导出优惠券类型列表
     */
    @PreAuthorize("@ss.hasPermi('coupon:type:export')")
    @Log(title = "优惠券类型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出优惠券类型列表")
    public void export(HttpServletResponse response, AppCouponType appCouponType) {
        List<AppCouponType> list = appCouponTypeService.selectAppCouponTypeList(appCouponType);
        ExcelUtil<AppCouponType> util = new ExcelUtil<AppCouponType>(AppCouponType. class);
        util.exportExcel(response, list, "优惠券类型数据");
    }

    /**
     * 获取优惠券类型详细信息
     */
    @PreAuthorize("@ss.hasPermi('coupon:type:query')")
    @GetMapping(value = "/getInfo")
    @ApiOperation(value = "获取优惠券类型详细信息")
    public AjaxResult getInfo(@RequestParam(value = "id",required = false) Long id) {
        return success(appCouponTypeService.selectAppCouponTypeById(id));
    }

    /**
     * 新增优惠券类型
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('coupon:type:add')")
    @Log(title = "优惠券类型", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增优惠券类型")
    public AjaxResult add(@RequestBody AppCouponTypeDTO appCouponTypeDTO) {
        return toAjax(appCouponTypeService.insertAppCouponType(appCouponTypeDTO));
    }

    /**
     * 修改优惠券类型
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('coupon:type:edit')")
    @Log(title = "优惠券类型", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改优惠券类型")
    public AjaxResult edit(@RequestBody AppCouponTypeDTO appCouponTypeDTO) {
        return toAjax(appCouponTypeService.updateAppCouponType(appCouponTypeDTO));
    }

    /**
     * 删除优惠券类型
     */
    @PreAuthorize("@ss.hasPermi('coupon:type:remove')")
    @Log(title = "优惠券类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除优惠券类型")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(appCouponTypeService.deleteAppCouponTypeByIds(ids));
    }

    /**
     * 修改优惠券类型状态
     */
    @PreAuthorize("@ss.hasPermi('coupon:type:edit')")
    @Log(title = "优惠券类型", businessType = BusinessType.UPDATE)
    @PostMapping(value = "updateStatus")
    @ApiOperation(value = "修改优惠券类型状态")
    public AjaxResult updateAppCouponTypeStatus(@RequestBody AppCouponType appCouponType) {
        return toAjax(appCouponTypeService.updateAppCouponTypeStatus(appCouponType));
    }
}
