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.yiqi.activity.domain.ActivityClothItem;
import com.yiqi.activity.domain.vo.ActivityClothItemVO;
import com.yiqi.activity.service.IActivityClothItemService;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.activity.domain.ActivityApplyOrg;
import com.yiqi.activity.domain.dto.ActivityDiscountInfoDTO;
import com.yiqi.activity.domain.vo.ActivityDiscountInfoQueryVO;
import com.yiqi.activity.domain.vo.ActivityDiscountInfoVO;
import com.yiqi.activity.service.IActivityApplyOrgService;
import com.yiqi.activity.service.IActivityDiscountInfoService;
import com.yiqi.common.constant.UrlConstants;
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.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.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-11
 */
@Api(tags = "管理后台 - 全场折扣活动")
@RestController
@RequestMapping(UrlConstants.managerApi + "/activity/discountInfo")
public class ActivityDiscountInfoController extends BaseController {
    @Autowired
    private IActivityInfoService activityInfoService;
    @Autowired
    private IActivityDiscountInfoService activityDiscountInfoService;
    @Autowired
    private ISysStoreService sysStoreService;
    @Autowired
    private IActivityClothItemService activityClothItemService;
    @Autowired
    private IActivityApplyOrgService activityApplyOrgService;
    @Autowired
    private IAppUserService appUserService;

    /**
     * 查询全场折扣活动列表
     */
    @PreAuthorize("@ss.hasPermi('activity:discountInfo:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询全场折扣活动列表")
    public TableDataInfo list(ActivityInfo activityInfo) {
        startPage();
        activityInfo.setActivityType(ActivityType.all_discount.getCode());
        List<ActivityDiscountInfoQueryVO> list = activityDiscountInfoService.selectActivityDiscountInfoList(activityInfo);
        return getDataTable(list);
    }

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

    /**
     * 获取全场折扣活动详细信息
     */
    @PreAuthorize("@ss.hasPermi('activity:discountInfo:query')")
    @GetMapping(value = "getInfo")
    @ApiOperation(value = "获取全场折扣活动详细信息")
    public AjaxResult getInfo(@RequestParam(value = "id", required = false) Long id) {
        if (id == null) {
            ActivityDiscountInfoVO activityDiscountInfoVO = new ActivityDiscountInfoVO();
            activityDiscountInfoVO.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(activityDiscountInfoVO);
        }
        ActivityInfo activityInfo = activityInfoService.selectActivityInfoById(id);
        if (activityInfo == null || !ActivityType.all_discount.getCode().equals(activityInfo.getActivityType())) {
            throw new ServiceException("未查询到活动");
        }
        ActivityDiscountInfoVO activityDiscountInfoVO = new ActivityDiscountInfoVO();
        BeanUtils.copyProperties(activityInfo, activityDiscountInfoVO);
        activityDiscountInfoVO.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()));
        activityDiscountInfoVO.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去更新活动信息
        activityDiscountInfoVO.setId(activityInfo.getId());
        return success(activityDiscountInfoVO);
    }

    /**
     * 获取门店折扣活动列表
     */
    @GetMapping(value = "getDiscountByStoreId")
    @ApiOperation(value = "获取门店折扣活动列表")
    public R getDiscountListByStoreId(Long appUserId) {
        if (getLoginUser().getStoreId() == null) {
            return R.ok();
        }
        List<ActivityDiscountInfoQueryVO> list = activityDiscountInfoService.getDiscountListByStoreId(getLoginUser().getStoreId());
        for (ActivityDiscountInfoQueryVO activityDiscountInfoQueryVO : list) {
            if (activityDiscountInfoQueryVO.getUserScope().equals(UserScopeType.NEW.getCode())) {
                if (!appUserService.checkUserIsNewUser(appUserId)) {
                    continue;
                }
            }
            if (activityDiscountInfoQueryVO.getUserScope().equals(UserScopeType.MEMBER.getCode())) {
                if (!appUserService.checkUserIsMember(appUserId)) {
                    continue;
                }
            }
            //指定衣服
            if (activityDiscountInfoQueryVO.getClothScope().equals("1")) {
                ActivityClothItem activityClothItem = new ActivityClothItem();
                activityClothItem.setActivityId(activityDiscountInfoQueryVO.getId());
                List<ActivityClothItemVO> activityClothItemVOList = activityClothItemService.selectActivityClothItemList(activityClothItem);
                activityDiscountInfoQueryVO.setActivityClothItemVOList(activityClothItemVOList);
            }
        }
        return R.ok(list);
    }

    /**
     * 新增全场折扣活动
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('activity:discountInfo:add')")
    @Log(title = "全场折扣活动", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增全场折扣活动")
    public AjaxResult add(@RequestBody ActivityDiscountInfoDTO activityDiscountInfoDTO) {
        ActivityInfo activityInfo = new ActivityInfo();
        BeanUtils.copyProperties(activityDiscountInfoDTO, activityInfo);
        activityInfo.setActivityType(ActivityType.all_discount.getCode());
        activityInfo.setCreateById(getUserId());
        activityInfo.setCreateBy(getUsername());
        int row = activityInfoService.insertActivityInfo(activityInfo);
        List<ActivityApplyOrg> activityApplyOrgs = new ArrayList<>();
        for (Long selectStoreId : activityDiscountInfoDTO.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:discountInfo:edit')")
    @Log(title = "全场折扣活动", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改全场折扣活动")
    public AjaxResult edit(@RequestBody ActivityDiscountInfoDTO activityDiscountInfoDTO) {
        ActivityInfo activityInfo = new ActivityInfo();
        BeanUtils.copyProperties(activityDiscountInfoDTO, activityInfo);
        activityInfo.setUpdateById(getUserId());
        activityInfo.setUpdateBy(getUsername());
        int row = activityInfoService.updateActivityInfo(activityInfo);

        activityApplyOrgService.remove(new QueryWrapper<ActivityApplyOrg>().lambda()
                .eq(ActivityApplyOrg::getActivityId, activityDiscountInfoDTO.getId()));
        List<ActivityApplyOrg> activityApplyOrgs = new ArrayList<>();
        for (Long selectStoreId : activityDiscountInfoDTO.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:discountInfo:remove')")
    @Log(title = "全场折扣活动", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除全场折扣活动")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(activityInfoService.deleteActivityInfoByIds(ids, ActivityType.all_discount.getCode()));
    }

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