package com.yiqi.admin.controller.activity;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.app.domain.AppCouponType;
import com.yiqi.common.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.activity.domain.ActivityApplyOrg;
import com.yiqi.activity.domain.ActivityCouponInfo;
import com.yiqi.activity.domain.ActivityInfo;
import com.yiqi.activity.domain.dto.ActivityCouponInfoDTO;
import com.yiqi.activity.domain.vo.ActivityAppCouponItemInfoVO;
import com.yiqi.activity.domain.vo.ActivityCouponInfoVO;
import com.yiqi.activity.domain.dto.ActivityAppCouponItemQueryDTO;
import com.yiqi.activity.service.IActivityApplyOrgService;
import com.yiqi.activity.service.IActivityInfoService;
import com.yiqi.app.domain.dto.weapp.AppCouponItemCountQueryDTO;
import com.yiqi.app.domain.vo.AppCouponItemSendCount2dayVO;
import com.yiqi.app.domain.vo.AppCouponItemVO;
import com.yiqi.app.service.IAppCouponItemService;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.core.domain.vo.SelectItemVO;
import com.yiqi.common.enums.*;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.system.domain.SysStore;
import com.yiqi.system.service.ISysStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.activity.service.IActivityCouponInfoService;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.common.core.page.TableDataInfo;

/**
 * 注册送券活动Controller
 *
 * @author xiaohei
 * @date 2023-09-08
 */
@Api(tags = "管理后台 - 注册送券活动")
@RestController
@RequestMapping(UrlConstants.managerApi + "/activity/couponInfo")
public class ActivityCouponInfoController extends BaseController {
    @Autowired
    private IActivityCouponInfoService activityCouponInfoService;
    @Autowired
    private ISysStoreService sysStoreService;
    @Autowired
    private IActivityInfoService activityInfoService;
    @Autowired
    private IActivityApplyOrgService activityApplyOrgService;
    @Autowired
    private IAppCouponItemService appCouponItemService;
    /**
     * 查询注册送券活动列表
     */
    @PreAuthorize("@ss.hasPermi('activity:couponInfo:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询注册送券活动列表")
    public TableDataInfo list(ActivityCouponInfoDTO activityCouponInfoDTO) {
        startPage();
        List<ActivityCouponInfoVO> list = activityCouponInfoService.selectActivityCouponInfoList(activityCouponInfoDTO);
        return getDataTable(list);
    }

    /**
     * 导出注册送券活动列表
     */
    @PreAuthorize("@ss.hasPermi('activity:couponInfo:export')")
    @Log(title = "注册送券活动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出注册送券活动列表")
    public void export(HttpServletResponse response, ActivityCouponInfoDTO activityCouponInfoDTO) {
        List<ActivityCouponInfoVO> list = activityCouponInfoService.selectActivityCouponInfoList(activityCouponInfoDTO);
        ExcelUtil<ActivityCouponInfoVO> util = new ExcelUtil<ActivityCouponInfoVO>(ActivityCouponInfoVO. class);
        util.exportExcel(response, list, "注册送券活动数据");
    }

    /**
     * 获取注册送券活动详细信息
     */
    @PreAuthorize("@ss.hasPermi('activity:couponInfo:query')")
    @GetMapping(value = "/getInfo")
    @ApiOperation(value = "获取注册送券活动详细信息")
    public AjaxResult getInfo(@RequestParam(value = "id",required = false) Long id) {
        ActivityAppCouponItemInfoVO activityAppCouponItemInfoVO = new ActivityAppCouponItemInfoVO();
        if(id == null){
            activityAppCouponItemInfoVO.setStoreVOS(sysStoreService.list(
                            new QueryWrapper<SysStore>().lambda()
                                    .eq(SysStore::getDelFlag, DeleteStatus.OK.getCode())
                                    .eq(SysStore::getStatus, StatusType.OK.getCode())).stream()
                    .map(SelectItemVO::new).collect(Collectors.toList()));
            return success(activityAppCouponItemInfoVO);
        }
        ActivityInfo activityInfo = activityInfoService.selectActivityInfoById(id);
        if(activityInfo == null || !ActivityType.regist.getCode().equals(activityInfo.getActivityType())){
            throw new ServiceException("未查询到活动");
        }
        BeanUtils.copyProperties(activityInfo,activityAppCouponItemInfoVO);
        ActivityCouponInfo activityCouponInfo = activityCouponInfoService.getOne(new QueryWrapper<ActivityCouponInfo>()
                .lambda().eq(ActivityCouponInfo::getActivityId, activityInfo.getId()));
        BeanUtils.copyProperties(activityCouponInfo,activityAppCouponItemInfoVO);
        activityAppCouponItemInfoVO.setStoreVOS(sysStoreService.list(
                        new QueryWrapper<SysStore>().lambda()
                                .eq(SysStore::getDelFlag, DeleteStatus.OK.getCode())
                                .eq(SysStore::getStatus, StatusType.OK.getCode())).stream()
                .map(SelectItemVO::new).collect(Collectors.toList()));
        activityAppCouponItemInfoVO.setSelectStoreIds(activityApplyOrgService.list(new QueryWrapper<ActivityApplyOrg>()
                        .lambda().eq(ActivityApplyOrg::getActivityId,id))
                .stream().filter(item -> SourceType.STORE.getCode().equals(item.getSourceType()))
                .map(ActivityApplyOrg::getOrgId).collect(Collectors.toList()));
        // 为了编辑的时候，直接按id去更新活动信息
        activityAppCouponItemInfoVO.setId(activityInfo.getId());
        return success(activityAppCouponItemInfoVO);
    }

    /**
     * 新增注册送券活动
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('activity:couponInfo:add')")
    @Log(title = "注册送券活动", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增注册送券活动")
    public AjaxResult add(@RequestBody ActivityCouponInfoDTO activityCouponInfoDTO) {
        activityCouponInfoDTO.setCreateById(getUserId());
        activityCouponInfoDTO.setCreateBy(getUsername());
        return toAjax(activityCouponInfoService.insertActivityCouponInfo(activityCouponInfoDTO));
    }

    /**
     * 修改注册送券活动
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('activity:couponInfo:edit')")
    @Log(title = "注册送券活动", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改注册送券活动")
    public AjaxResult edit(@RequestBody ActivityCouponInfoDTO activityCouponInfoDTO) {
        activityCouponInfoDTO.setUpdateById(getUserId());
        activityCouponInfoDTO.setUpdateBy(getUsername());
        return toAjax(activityCouponInfoService.updateActivityCouponInfo(activityCouponInfoDTO));
    }

    /**
     * 删除注册送券活动
     */
    @PreAuthorize("@ss.hasPermi('activity:couponInfo:remove')")
    @Log(title = "注册送券活动", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除注册送券活动")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(activityCouponInfoService.deleteActivityCouponInfoByIds(ids, ActivityType.regist.getCode()));
    }

    /**
     * 查询门店适用的注册活动和优惠券列表
     */
    @PreAuthorize("@ss.hasPermi('activity:couponInfo:list')")
    @GetMapping("/listByStore")
    @ApiOperation(value = "查询门店适用的活动和优惠券列表")
    public TableDataInfo listByStore(ActivityAppCouponItemQueryDTO activityAppCouponItemQueryDTO) {
        startPage();
        List<AppCouponType> list = activityCouponInfoService.selectActivityCouponItemList(activityAppCouponItemQueryDTO);
        return getDataTable(list);
    }

    /**
     * 查询门店发券统计-今日统计数量
     */
    @PreAuthorize("@ss.hasPermi('activity:couponInfo:count')")
    @GetMapping("/todayCouponSendCountByStore")
    @ApiOperation(value = "查询门店发券统计-今日统计数量")
    public R<AppCouponItemSendCount2dayVO> todayCouponSendCountByStore() {
        String dateTimeNow = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD);
        AppCouponItemSendCount2dayVO vo = new AppCouponItemSendCount2dayVO();
        vo.setSendTotal(appCouponItemService.countTodaySendNumber(dateTimeNow));
        vo.setHXTotal(appCouponItemService.countTodayHxNumber(dateTimeNow));
        return R.ok(vo);
    }

    /**
     * 查询门店发券统计-列表统计
     */
    @PreAuthorize("@ss.hasPermi('activity:couponInfo:count')")
    @PostMapping("/listCouponSendCount")
    @ApiOperation(value = "查询门店发券统计-列表统计")
    public R<Page<AppCouponItemVO>> listCouponSendCount(AppCouponItemCountQueryDTO appCouponItemCountQueryDTO) {
        appCouponItemCountQueryDTO.setOrgId(SecurityUtils.getLoginUser().getOrgId());
        appCouponItemCountQueryDTO.setSourceType(SecurityUtils.getLoginUser().getSourceType());
        List<AppCouponItemVO> list = appCouponItemService.couponSendListByStore(appCouponItemCountQueryDTO);
        int count = appCouponItemService.countCouponSendListByStore(appCouponItemCountQueryDTO);
        Page<AppCouponItemVO> page = new Page<>();
        page.setRecords(list);
        page.setTotal(count);
        return R.ok(page);
    }
}
