package com.ruoyi.web.controller.clock;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.clock.domain.bo.*;
import com.ruoyi.clock.domain.vo.*;
import com.ruoyi.clock.service.IActivityService;
import com.ruoyi.clock.service.IClockRecordService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 活动信息Controller
 *
 * @author pengc
 * @date 2026-03-04
 */
@Validated
@Api(value = "活动信息控制器", tags = {"活动信息管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/clock/activity")
public class ActivityController extends BaseController {

    private final IActivityService iActivityService;
    private final IClockRecordService iClockRecordService;

    /**
     * 分页查询活动信息列表
     */
    @ApiOperation("查询活动信息列表")
    @SaCheckPermission("clock:activity:list")
    @GetMapping("/page")
    public TableDataInfo<ActivityVo> page(@Validated(QueryGroup.class) ActivityBo bo, PageQuery pageQuery) {
        TableDataInfo<ActivityVo> activityVoTableDataInfo = iActivityService.queryPageList(bo, pageQuery);
        if (CollUtil.isNotEmpty(activityVoTableDataInfo.getRows())){
            activityVoTableDataInfo.getRows().forEach(item -> {
                item.loadAgentList();
                item.loadProductList();
            });
        }
        return activityVoTableDataInfo;
    }

    /**
     * 获取活动信息详细信息
     */
    @ApiOperation("获取活动信息详细信息")
    @SaCheckPermission("clock:activity:query")
    @GetMapping("/info/{activityId}")
    public R<ActivityVo> getInfo(@ApiParam("主键")
                                  @NotNull(message = "主键不能为空")
                                  @PathVariable("activityId") Long activityId) {
        ActivityVo activityVo = iActivityService.queryById(activityId);
        if(ObjectUtil.isNotNull(activityVo)){
            activityVo.loadAgentList();
            activityVo.loadProductList();
        }
        return R.ok(activityVo);
    }

    /**
     * 新增活动信息
     */
    @ApiOperation("新增活动信息")
    @SaCheckPermission("clock:activity:add")
    @Log(title = "活动信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ActivityBo bo) {
        return toAjax(iActivityService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改活动信息
     */
    @ApiOperation("修改活动信息")
    @SaCheckPermission("clock:activity:edit")
    @Log(title = "活动信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/edit")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ActivityBo bo) {
        return toAjax(iActivityService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除活动信息
     */
    @ApiOperation("删除活动信息")
    @SaCheckPermission("clock:activity:remove")
    @Log(title = "活动信息", businessType = BusinessType.DELETE)
    @PostMapping("/del/{activityIds}")
    public R<Void> remove(@ApiParam("主键串")
                                       @NotEmpty(message = "主键不能为空")
                                       @PathVariable Long[] activityIds) {
        return toAjax(iActivityService.deleteWithValidByIds(Arrays.asList(activityIds), true) ? 1 : 0);
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @Log(title = "活动状态修改", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    public R<Void> changeStatus(@RequestBody ActivityStatusBo bo) {
        return toAjax(iActivityService.updateStatus(bo));
    }


    /**
     * 导出活动信息列表
     */
    @ApiOperation("导出活动信息列表")
    @SaCheckPermission("clock:activity:export")
    @Log(title = "活动信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated ActivityBo bo, HttpServletResponse response) {
        List<ActivityVo> list = iActivityService.queryList(bo);
        list.forEach(item -> {
            item.loadAgentList();
            item.loadProductList();
            item.loadImage();
        });
        ExcelUtil.exportExcel(list, "活动信息", ActivityVo.class, response);
    }

    /**
     * 分页查询活动打卡记录列表
     * 查询条件：店员姓名、所属代理商、所属门店、打卡状态
     */
    @ApiOperation("查询活动打卡记录列表（分页）")
    @SaCheckPermission("clock:activity:clockRecord:list")
    @GetMapping("/clockRecord/page")
    public TableDataInfo<ActivityClockRecordVo> clockRecordPage(
            @Validated(QueryGroup.class) ActivityClockRecordBo bo, PageQuery pageQuery) {
        return iClockRecordService.queryActivityClockRecordPage(bo, pageQuery);
    }

    /**
     * 查询活动打卡统计
     * 当前筛选条件下打卡店员人数与销售数量合计
     */
    @ApiOperation("查询活动打卡统计（打卡人数 + 销售数量）")
    @SaCheckPermission("clock:activity:clockRecord:list")
    @GetMapping("/clockRecord/statistic")
    public R<ActivityClockStatisticVo> clockRecordStatistic(
            @Validated(QueryGroup.class) ActivityClockRecordBo bo) {
        return R.ok(iClockRecordService.queryActivityClockStatistic(bo));
    }

    /**
     * 查询活动销量打卡排行
     */
    @ApiOperation("查询活动销量打卡排行")
    @PostMapping("/saleRankList")
    public R<List<SaleStatisticRecordVo>> saleRankList(@Validated(QueryGroup.class) @RequestBody SaleStatisticBo bo) {
        return R.ok(iClockRecordService.querySaleStatisticRecordList(bo));
    }

    /**
     * 将员工在指定活动下的所有打卡设为失效
     */
    @ApiOperation("设为无效打卡")
    @SaCheckPermission("clock:activity:clockRecord:invalidate")
    @Log(title = "活动打卡记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/clockRecord/invalidate/{activityId}/{employeeId}")
    public R<Void> invalidateClockRecord(
            @ApiParam("活动id") @NotNull @PathVariable("activityId") Long activityId,
            @ApiParam("员工id") @NotNull @PathVariable("employeeId") Long employeeId) {
        Boolean result = iClockRecordService.invalidateEmployeeClock(activityId, employeeId);
        return toAjax(result ? 1 : 0);
    }

    /**
     * 分页查询活动店铺销量列表（销量活动）
     * 活动类型为1（销量PK），过滤掉失效的打卡记录
     */
    @ApiOperation("查询活动店铺销量列表")
    @SaCheckPermission("clock:activity:shopSale:list")
    @GetMapping("/shopSale/page")
    public TableDataInfo<ActivityShopSaleVo> shopSalePage(
            @Validated(QueryGroup.class) ActivityShopSaleBo bo, PageQuery pageQuery) {
        return iClockRecordService.queryActivityShopSalePage(bo, pageQuery);
    }

}
