package com.yiqi.admin.controller.activity;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.activity.domain.ActivityApplyOrg;
import com.yiqi.activity.domain.dto.ActivityRechargeDTO;
import com.yiqi.activity.domain.vo.ActivityRechargeVO;
import com.yiqi.activity.service.IActivityApplyOrgService;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.domain.BaseEntity;
import com.yiqi.common.core.domain.vo.SelectItemVO;
import com.yiqi.common.enums.*;
import com.yiqi.common.utils.DateUtils;
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.domain.ActivityInfo;
import com.yiqi.activity.service.IActivityInfoService;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.common.core.page.TableDataInfo;

/**
 * 充值多送活动Controller
 *
 * @author xiaohei
 * @date 2023-09-09
 */
@Api(tags = "管理后台 - 充值多送活动")
@RestController
@RequestMapping(UrlConstants.managerApi + "/activity/recharge")
public class ActivityRechargeInfoController extends BaseController {

    @Autowired
    private IActivityInfoService activityInfoService;
    @Autowired
    private IActivityApplyOrgService activityApplyOrgService;
    @Autowired
    private ISysStoreService sysStoreService;

    /**
     * 查询充值多送活动
     */
    @PreAuthorize("@ss.hasPermi('activity:recharge:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询充值多送活动列表")
    public TableDataInfo list(ActivityInfo activityInfo) {
        startPage();
        activityInfo.setActivityType(ActivityType.recharge.getCode());
        List<ActivityInfo> list = activityInfoService.selectActivityInfoList(activityInfo);
        return getDataTable(list);
    }

    /**
     * 导出充值多送活动列表
     */
    @PreAuthorize("@ss.hasPermi('activity:recharge:export')")
    @Log(title = "活动明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出充值多送活动列表")
    public void export(HttpServletResponse response, ActivityInfo activityInfo) {
        List<ActivityInfo> list = activityInfoService.selectActivityInfoList(activityInfo);
        ExcelUtil<ActivityInfo> util = new ExcelUtil<ActivityInfo>(ActivityInfo. class);
        util.exportExcel(response, list, "活动明细数据");
    }

    /**
     * 获取充值多送活动详细信息
     */
    @PreAuthorize("@ss.hasPermi('activity:recharge:query')")
    @GetMapping(value = "/getInfo")
    @ApiOperation(value = "获取充值多送活动详细信息")
    public AjaxResult getInfo(@RequestParam(required = false) Long id) {
        if(id == null || id == 0){
            ActivityRechargeVO activityRechargeVO = new ActivityRechargeVO();
            activityRechargeVO.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(activityRechargeVO);
        }
        ActivityInfo activityInfo = activityInfoService.selectActivityInfoById(id);
        if(activityInfo == null){
            throw new ServiceException("未查询到活动");
        }
        ActivityRechargeVO activityRechargeVO = new ActivityRechargeVO();
        BeanUtils.copyProperties(activityInfo,activityRechargeVO);
        activityRechargeVO.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()));
        activityRechargeVO.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()));
        return success(activityRechargeVO);
    }

    /**
     * 新增充值多送活动
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('activity:recharge:add')")
    @Log(title = "充值多送活动", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增充值多送活动")
    public AjaxResult add(@RequestBody ActivityRechargeDTO activityRechargeDTO) {
        ActivityInfo activityInfo = new ActivityInfo();
        BeanUtils.copyProperties(activityRechargeDTO,activityInfo);
        activityInfo.setActivityType(ActivityType.recharge.getCode());
        activityInfo.setCreateBy(getUsername());
        activityInfo.setCreateById(getUserId());
        int row = activityInfoService.insertActivityInfo(activityInfo);

        List<ActivityApplyOrg> activityApplyOrgs = new ArrayList<>();
        for (Long selectStoreId : activityRechargeDTO.getSelectStoreIds()) {
            ActivityApplyOrg activityApplyOrg = new ActivityApplyOrg();
            activityApplyOrg.setActivityId(activityInfo.getId());
            activityApplyOrg.setOrgId(selectStoreId);
            activityApplyOrg.setSourceType(SourceType.STORE.getCode());
            activityApplyOrg.setCreateBy(getUsername());
            activityApplyOrg.setCreateById(getUserId());
            activityApplyOrg.setCreateTime(DateUtils.getNowDate());
            activityApplyOrgs.add(activityApplyOrg);
        }
        activityApplyOrgService.saveBatch(activityApplyOrgs);
        return toAjax(row);
    }

    /**
     * 修改充值多送活动
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('activity:recharge:edit')")
    @Log(title = "充值多送活动", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改充值多送活动")
    public AjaxResult edit(@RequestBody ActivityRechargeDTO activityRechargeDTO) {
        if(activityRechargeDTO.getId() == null){
            throw new ServiceException("活动ID不能为空");
        }
        ActivityInfo activityInfo = new ActivityInfo();
        BeanUtils.copyProperties(activityRechargeDTO,activityInfo);
        activityInfo.setUpdateById(getUserId());
        activityInfo.setUpdateBy(getUsername());
        int row = activityInfoService.updateActivityInfo(activityInfo);

        activityApplyOrgService.remove(new QueryWrapper<ActivityApplyOrg>().lambda()
                .eq(ActivityApplyOrg::getActivityId,activityRechargeDTO.getId()));

        List<ActivityApplyOrg> activityApplyOrgs = new ArrayList<>();
        for (Long selectStoreId : activityRechargeDTO.getSelectStoreIds()) {
            ActivityApplyOrg activityApplyOrg = new ActivityApplyOrg();
            activityApplyOrg.setActivityId(activityInfo.getId());
            activityApplyOrg.setOrgId(selectStoreId);
            activityApplyOrg.setSourceType(SourceType.STORE.getCode());
            activityApplyOrg.setCreateBy(getUsername());
            activityApplyOrg.setCreateById(getUserId());
            activityApplyOrg.setCreateTime(DateUtils.getNowDate());
            activityApplyOrgs.add(activityApplyOrg);
        }
        activityApplyOrgService.saveBatch(activityApplyOrgs);
        return toAjax(row);
    }

    /**
     * 删除充值多送活动
     */
    @PreAuthorize("@ss.hasPermi('activity:recharge:remove')")
    @Log(title = "充值多送活动", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除充值多送活动")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(activityInfoService.deleteActivityInfoByIds(ids,ActivityType.recharge.getCode()));
    }

    /**
     * 修改充值多送活动状态
     */
    @PreAuthorize("@ss.hasPermi('activity:recharge:edit')")
    @Log(title = "充值多送活动", businessType = BusinessType.UPDATE)
    @PostMapping(value = "updateStatus")
    @ApiOperation(value = "修改充值多送活动状态")
    public AjaxResult updateActivityInfoStatus(@RequestBody ActivityInfo activityInfo) {
        return toAjax(activityInfoService.update(new UpdateWrapper<ActivityInfo>().lambda()
                .set(ActivityInfo::getStatus,activityInfo.getStatus())
                .set(BaseEntity::getUpdateById,getUserId())
                .set(BaseEntity::getUpdateBy,getUsername())
                .set(BaseEntity::getUpdateTime, DateUtils.getNowDate())
                .eq(ActivityInfo::getId,activityInfo.getId())
                .eq(ActivityInfo::getActivityType,ActivityType.recharge.getCode())));
    }



}
