package com.kiisoo.ic.activity.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kiisoo.ic.activity.bean.PromotionSrcVO;
import com.kiisoo.ic.activity.bean.PushPromotionsVO;
import com.kiisoo.ic.activity.bean.RemoveStaffVO;
import com.kiisoo.ic.activity.entity.PmnPromotionSrc;
import com.kiisoo.ic.activity.service.IPmnPromotionSrcService;
import com.kiisoo.ic.common.BaseController;
import com.kiisoo.ic.store.entity.PoiStoreStaff;
import com.kiisoo.ic.store.mapper.PoiStoreStaffDOMapper;
import com.kiisoo.ic.synchronous.entity.TurnBackDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Api(value = "小程序-我的活动推广", tags = {"小程序-我的活动推广"})
@RestController
@RequestMapping("/webapp/my")
@Slf4j
public class WebAppActivityController extends BaseController {
    @Autowired
    private IPmnPromotionSrcService pmnPromotionSrcService;
    @Autowired
    private PoiStoreStaffDOMapper poiStoreStaffDOMapper;

    @ApiOperation(value = "我的活动推广列表")
    @GetMapping("/get/promotions")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "form"),
    })
    public Map<String, Object> myPromotions(long userId) {
        // TODO 查询当前小程序用户，在活动有效期间的有效活动，包含活动名称，活动二维码
        // TODO 从 promotion_src 获取当前导购的推广关系，并关联 activity_instance等表获取活动详情（注意活动有效性）
        // TODO 需要附加这个活动已经推广的客户列表 promotion_friends_src
        try {
            List<PromotionSrcVO> codes = pmnPromotionSrcService.listUserCodes(userId);
            return data(codes);
        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            return fail();
        }
    }

    @ApiOperation(value = "店长-执行推广")
    @PostMapping("/post/promotions")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "list", value = "选中导购staffId列表", dataType = "array", paramType = "form"),
            @ApiImplicitParam(name = "instanceId", value = "活动ID", dataType = "array", paramType = "form"),
    })
    public Map<String, Object> pushPromotion(@RequestBody PushPromotionsVO vo) {
        // TODO 将活动推广给单个或多个导购 promotion_src
        // TODO 如果已经推广过了，则忽略
        try {
            List<PoiStoreStaff> fails = new ArrayList<>();
            List<PoiStoreStaff> success = new ArrayList<>();
            Long instanceId = vo.getInstanceId();
            Long userId = vo.getUserId();
            List<Long> ids = vo.getList();
            if(ids.size() <= 0) {
                return fail("00004", "请传入list");
            }
            if(instanceId == null) {
                return fail("00004", "请传入实例ID");
            }
            List<PoiStoreStaff> staffs = poiStoreStaffDOMapper.selectBatchIds(ids);
            for (PoiStoreStaff staff : staffs) {
                PmnPromotionSrc create = pmnPromotionSrcService.createCode(staff, instanceId);
                if (create == null) {
                    fails.add(staff);
                } else {
                    success.add(staff);
                }
            }
            /**
             * 传入列表没有的,二维码设为失效
             */
            PmnPromotionSrc up = new PmnPromotionSrc();
            up.setStatus(2L);
            pmnPromotionSrcService.update(up, Wrappers.<PmnPromotionSrc>lambdaQuery().eq(PmnPromotionSrc::getInstanceId, instanceId).notIn(PmnPromotionSrc::getPromoterId, staffs.stream().map(PoiStoreStaff::getUserId).collect(Collectors.toList())).eq(PmnPromotionSrc::getType, 1));
            //
            Map<String, Object> ret = new HashMap<>();
            ret.put("success", success);
            ret.put("fail", fails);
            return data(ret);
        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            return fail();
        }
    }

    @ApiOperation(value = "店长-移除活动导购")
    @PostMapping("/removeStaff")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "当前登录用户ID", dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "user", value = "要移除导购的userId", dataType = "array", paramType = "form"),
            @ApiImplicitParam(name = "instanceId", value = "活动ID", dataType = "array", paramType = "form"),
    })
    public Map<String, Object> removeStaff(@RequestBody RemoveStaffVO removeStaffVO){
        try{
            boolean remove = pmnPromotionSrcService.remove(Wrappers.<PmnPromotionSrc>lambdaQuery().eq(PmnPromotionSrc::getPromoterId, removeStaffVO.getUser()).eq(PmnPromotionSrc::getType, 1).eq(PmnPromotionSrc::getInstanceId, removeStaffVO.getInstanceId()));
            return remove ? success() : fail();
        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            return fail();
        }
    }

    @ApiOperation(value = "好友添加回调通知")
    @PostMapping("/cb")
    public Map<String, Object> turnBack(@RequestBody List<TurnBackDTO> turnBackDTOS) {
        // TODO 待调查
        return data(null);
    }
}
