package com.yiqi.admin.controller.activity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.activity.domain.ActivityApplyOrg;
import com.yiqi.activity.domain.ActivityGroupInfo;
import com.yiqi.activity.domain.ActivityInfo;
import com.yiqi.activity.domain.dto.ActivityGroupInfoDTO;
import com.yiqi.activity.domain.vo.ActivityGroupInfoQueryVO;
import com.yiqi.activity.domain.vo.ActivityGroupInfoVO;
import com.yiqi.activity.service.IActivityApplyOrgService;
import com.yiqi.activity.service.IActivityGroupInfoService;
import com.yiqi.activity.service.IActivityInfoService;
import com.yiqi.common.annotation.Log;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.common.core.domain.vo.SelectItemVO;
import com.yiqi.common.core.page.TableDataInfo;
import com.yiqi.common.enums.*;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.system.domain.ManageFactory;
import com.yiqi.system.domain.SysStore;
import com.yiqi.system.service.IManageFactoryService;
import com.yiqi.system.service.ISysStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * 活动明细Controller
 *
 * @author xiaohei
 * @date 2023-09-11
 */
@Api(tags = "管理后台 - 拼团送券活动")
@RestController
@RequestMapping(UrlConstants.managerApi + "/activity/groupInfo")
public class ActivityGroupInfoController extends BaseController {
    @Autowired
    private IActivityInfoService activityInfoService;
    @Autowired
    private IActivityGroupInfoService activityGroupInfoService;
    @Autowired
    private ISysStoreService sysStoreService;
    @Autowired
    private IManageFactoryService manageFactoryService;
    @Autowired
    private IActivityApplyOrgService activityApplyOrgService;

    /**
     * 查询拼团送券活动列表
     */
    @PreAuthorize("@ss.hasPermi('activity:groupInfo:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询拼团送券活动列表")
    public TableDataInfo list(ActivityInfo activityInfo) {
        startPage();
        activityInfo.setActivityType(ActivityType.group.getCode());
        List<ActivityGroupInfoQueryVO> list = activityGroupInfoService.selectActivityGroupInfoList(activityInfo);
        return getDataTable(list);
    }

    /**
     * 导出拼团送券活动列表
     */
    @PreAuthorize("@ss.hasPermi('activity:groupInfo:export')")
    @Log(title = "拼团送券活动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出拼团送券活动列表")
    public void export(HttpServletResponse response, ActivityInfo activityInfo) {
        activityInfo.setActivityType(ActivityType.group.getCode());
        List<ActivityInfo> list = activityInfoService.selectActivityInfoList(activityInfo);
        ExcelUtil<ActivityInfo> util = new ExcelUtil<ActivityInfo>(ActivityInfo. class);
        util.exportExcel(response, list, "全场折扣活动数据");
    }

    /**
     * 获取拼团送券活动详细信息
     */
    @PreAuthorize("@ss.hasPermi('activity:groupInfo:query')")
    @GetMapping(value = "getInfo")
    @ApiOperation(value = "获取拼团送券活动详细信息")
    public AjaxResult getInfo(@RequestParam(value = "id",required = false) Long id) {
        if(id == null){
            ActivityGroupInfoVO activityGroupInfoVO = new ActivityGroupInfoVO();
            activityGroupInfoVO.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()));
            activityGroupInfoVO.setFactoryVOS(manageFactoryService.list(
                            new QueryWrapper<ManageFactory>().lambda()
                                    .eq(ManageFactory::getDelFlag, DeleteStatus.OK.getCode())
                                    .eq(ManageFactory::getStatus, StatusType.OK.getCode())).stream()
                    .map(SelectItemVO::new).collect(Collectors.toList()));
            return success(activityGroupInfoVO);
        }
        ActivityInfo activityInfo = activityInfoService.selectActivityInfoById(id);
        if(activityInfo == null || !ActivityType.group.getCode().equals(activityInfo.getActivityType())){
            throw new ServiceException("未查询到活动");
        }
        ActivityGroupInfoVO activityGroupInfoVO = new ActivityGroupInfoVO();
        BeanUtils.copyProperties(activityInfo,activityGroupInfoVO);

        ActivityGroupInfo activityGroupInfo = activityGroupInfoService
                .getOne(new QueryWrapper<ActivityGroupInfo>().lambda().eq(ActivityGroupInfo::getActivityId,activityInfo.getId()));
        BeanUtils.copyProperties(activityGroupInfo,activityGroupInfoVO,"id");

        activityGroupInfoVO.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()));
        activityGroupInfoVO.setFactoryVOS(manageFactoryService.list(
                        new QueryWrapper<ManageFactory>().lambda()
                                .eq(ManageFactory::getDelFlag, DeleteStatus.OK.getCode())
                                .eq(ManageFactory::getStatus, StatusType.OK.getCode())).stream()
                .map(SelectItemVO::new).collect(Collectors.toList()));
        activityGroupInfoVO.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()));
        activityGroupInfoVO.setSelectFactoryIds(activityApplyOrgService.list(new QueryWrapper<ActivityApplyOrg>()
                        .lambda().eq(ActivityApplyOrg::getActivityId,id))
                .stream().filter(item -> SourceType.FACTORY.getCode().equals(item.getSourceType()))
                .map(ActivityApplyOrg::getOrgId).collect(Collectors.toList()));

        // 为了编辑的时候，直接按id去更新活动信息
        activityGroupInfoVO.setId(activityInfo.getId());
        return success(activityGroupInfoVO);
    }

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

        ActivityGroupInfo activityGroupInfo = new ActivityGroupInfo();
        BeanUtils.copyProperties(activityGroupInfoDTO,activityGroupInfo);
        activityGroupInfo.setActivityId(activityInfo.getId());
        activityGroupInfo.setCreateById(getUserId());
        activityGroupInfo.setCreateBy(getUsername());
        activityGroupInfoService.insertActivityGroupInfo(activityGroupInfo);

        List<ActivityApplyOrg> activityApplyOrgs = new ArrayList<>();
        for (Long selectStoreId : activityGroupInfoDTO.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);
        }
        for (Long selectStoreId : activityGroupInfoDTO.getSelectFactoryIds()) {
            ActivityApplyOrg activityApplyOrg = new ActivityApplyOrg();
            activityApplyOrg.setActivityId(activityInfo.getId());
            activityApplyOrg.setOrgId(selectStoreId);
            activityApplyOrg.setSourceType(SourceType.FACTORY.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:groupInfo:edit')")
    @Log(title = "拼团送券活动", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改拼团送券活动")
    public AjaxResult edit(@RequestBody ActivityGroupInfoDTO activityGroupInfoDTO) {
        ActivityInfo activityInfo = new ActivityInfo();
        BeanUtils.copyProperties(activityGroupInfoDTO,activityInfo);
        activityInfo.setUpdateById(getUserId());
        activityInfo.setUpdateBy(getUsername());
        int row = activityInfoService.updateActivityInfo(activityInfo);

        ActivityGroupInfo activityGroupInfo = new ActivityGroupInfo();
        BeanUtils.copyProperties(activityGroupInfoDTO,activityGroupInfo,"id");
        activityGroupInfo.setActivityId(activityGroupInfoDTO.getId());
        activityInfo.setUpdateById(getUserId());
        activityInfo.setUpdateBy(getUsername());
        activityGroupInfoService.updateActivityGroupInfo(activityGroupInfo);

        activityApplyOrgService.remove(new QueryWrapper<ActivityApplyOrg>().lambda()
                .eq(ActivityApplyOrg::getActivityId,activityGroupInfoDTO.getId()));
        List<ActivityApplyOrg> activityApplyOrgs = new ArrayList<>();
        for (Long selectStoreId : activityGroupInfoDTO.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);
        }
        for (Long selectStoreId : activityGroupInfoDTO.getSelectFactoryIds()) {
            ActivityApplyOrg activityApplyOrg = new ActivityApplyOrg();
            activityApplyOrg.setActivityId(activityInfo.getId());
            activityApplyOrg.setOrgId(selectStoreId);
            activityApplyOrg.setSourceType(SourceType.FACTORY.getCode());
            activityApplyOrg.setCreateBy(getUsername());
            activityApplyOrg.setCreateById(getUserId());
            activityApplyOrg.setCreateTime(DateUtils.getNowDate());
            activityApplyOrgs.add(activityApplyOrg);
        }
        activityApplyOrgService.saveBatch(activityApplyOrgs);
        return toAjax(row);
    }

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

    /**
     * 修改拼团送券活动状态
     */
    @PreAuthorize("@ss.hasPermi('activity:groupInfo:edit')")
    @Log(title = "全场折扣活动", businessType = BusinessType.UPDATE)
    @PostMapping(value = "updateStatus")
    @ApiOperation(value = "修改拼团送券活动状态")
    public AjaxResult updateActivityInfoStatus(@RequestBody ActivityInfo activityInfo) {
        return toAjax(activityInfoService.updateActivityInfoStatus(activityInfo));
    }
}
