package com.cyksj.web.controller.manage.channel;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.vip.VipOrderDonMapper;
import com.cyksj.model.entity.Channel;
import com.cyksj.model.entity.ChannelPopularize;
import com.cyksj.model.views.ChannelView;
import com.cyksj.service.mange.channel.ChannelPopularizeService;
import com.cyksj.service.mange.channel.ChannelService;
import com.cyksj.service.mange.cms.service.CmsUserService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author chan
 * @date 2022/12/13 2:29 PM
 */
@RequestMapping("/manage/channel")
@Slf4j
@RestController
@RequiredArgsConstructor
public class CmsChannelController {

    private final ChannelService channelService;

    private final ChannelPopularizeService channelPopularizeService;

    private final BeanSearcher beanSearcher;

    private final CmsUserService cmsUserService;

    private final HttpServletRequest request;

    private final VipOrderDonMapper vipOrderDonMapper;

    @GetMapping
    public Result<SearchResult<ChannelView>> get(String startTime, String endTime) {
        String timeSql = StringUtils.EMPTY;
        long adminId = StpUtil.getLoginIdAsLong();
        Boolean isRootRole = cmsUserService.isRootRole(adminId);
        if (StringUtils.isNotBlank(startTime)) {
            timeSql += String.format(" and o.created_time >= '%s'", startTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            timeSql += String.format(" and o.created_time <= '%s'", endTime);
        }
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        if (!isRootRole) {
            builder.put("condition", String.format("FIND_IN_SET(%s,c.creator) > 0", adminId));
        }
        SearchResult<ChannelView> searchResult = beanSearcher.search(ChannelView.class,
                builder.put("time", timeSql).build());
        searchResult.getDataList().forEach(data->{
            //AI会员订单数据
            Long channelId = data.getId();
            ChannelView vipView = vipOrderDonMapper.getOrderDataByCid(channelId, startTime, endTime);
            data.setOrderCount(data.getOrderCount() + vipView.getOrderCount());
            data.setOrderMoney(data.getOrderMoney().add(vipView.getOrderMoney()));
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(searchResult);
    }

    /**
     * 所有渠道列表
     */
    @GetMapping("/get/channelList")
    public Result<List<Channel>> getChannels() {
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        long adminId = StpUtil.getLoginIdAsLong();
        Boolean isRootRole = cmsUserService.isRootRole(adminId);
        if (!isRootRole) {
            builder.put("condition", String.format("FIND_IN_SET(%s,c.creator) > 0", adminId));
        }
        List<Channel> list = beanSearcher.searchAll(Channel.class, builder
                .onlySelect(Channel::getId, Channel::getName)
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(list);
    }

    @PostMapping
    public Result<String> post(@RequestBody Channel channel){
        Long adminId = StpUtil.getLoginIdAsLong();
        channel.setCreator(adminId.toString());
        channelService.save(channel);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    @PutMapping
    public Result<String> put(@RequestBody Channel channel){
        channelService.updateById(channel);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    @DeleteMapping("/{id}")
    public Result<String> del(@PathVariable Long id){
        channelService.removeById(id);
        channelPopularizeService.remove(Wrappers.lambdaQuery(ChannelPopularize.class).eq(ChannelPopularize::getChannelId,id));
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

}
