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

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.channel.ChannelPopularizeVisitMapper;
import com.cyksj.mapper.corp.CorpCustomerAcquisitionLinkPopularizeMapper;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.mapper.vip.VipOrderDonMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.ChannelPopularizeDetailView;
import com.cyksj.model.views.ChannelPopularizeView;
import com.cyksj.model.views.VipOrderDonPopularizeView;
import com.cyksj.service.mange.channel.ChannelPopularizeService;
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/popularize")
@Slf4j
@RestController
@RequiredArgsConstructor
public class CmsChannelPopularizeController {

    private final ChannelPopularizeService channelPopularizeService;

    private final BeanSearcher beanSearcher;

    private final HttpServletRequest request;

    private final UserMapper userMapper;

    private final OrderDonMapper orderDonMapper;

    private final VipOrderDonMapper vipOrderDonMapper;

    private final ChannelPopularizeVisitMapper visitMapper;

    private final CorpCustomerAcquisitionLinkPopularizeMapper acquisitionLinkPopularizeMapper;

    private final CmsUserService cmsUserService;

    private final SysConfigMapper sysConfigMapper;
    @GetMapping
    @SaCheckPermission("promotion:view")
    public Result<SearchResult<ChannelPopularizeView>> get(String startTime, String endTime, Long goodsId) throws Exception {
        long adminId = StpUtil.getLoginIdAsLong();
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        Boolean isRootRole = cmsUserService.isRootRole(adminId);
        if (!isRootRole) {
            String condition = String.format("FIND_IN_SET(%s,c.creator) > 0", adminId);
            //渠道单独给管理员展示
            SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
                    .eq(SysConfig::getSysKey, Constant.POPULARIZE_USER_VIEWS)
                    .last("limit 1"));
            if (sysConfig != null && StrUtil.isNotBlank(sysConfig.getSysValue())) {
                List<Long> userList = Jsons.parseList(sysConfig.getSysValue(), Long.class);
                if (userList.contains(adminId)) {
                    condition += String.format(" or FIND_IN_SET(%s,cp.creator) > 0", adminId);
                }
            }
            builder.put("condition", "(" + condition + ")");
        }
        SearchResult<ChannelPopularizeView> searchResult = beanSearcher.search(ChannelPopularizeView.class, builder.build());
        searchResult.getDataList().forEach(data -> {
            Integer emailCount = userMapper.selectCount(Wrappers.lambdaQuery(User.class)
                    .eq(User::getPopularizeId, data.getId())
                    .ne(User::getEmail, ""));
            data.setEmailCount(emailCount);
            Integer phoneCount = userMapper.selectCount(Wrappers.lambdaQuery(User.class)
                    .eq(User::getPopularizeId, data.getId())
                    .ne(User::getLoginPhone, ""));
            data.setPhoneCount(phoneCount);

            Integer wechatCount = userMapper.selectCount(Wrappers.lambdaQuery(User.class)
                    .eq(User::getPopularizeId, data.getId())
                    .ne(User::getOpenId, ""));
            data.setWechatCount(wechatCount);

            Integer numOfOrderWebPay = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
                    .eq(OrderDon::getPopularizeId, data.getId())
                    .eq(OrderDon::getIsWebPay, true)
                    .notIn(OrderDon::getStatus, Constant.noOrderStatus));
            data.setNumOfOrderWebPay(numOfOrderWebPay);
            ChannelPopularizeView channelPopularizeView = orderDonMapper.countPopularizeOrderDetail(data.getId(), goodsId, startTime, endTime);
            data.setOrderCount(channelPopularizeView.getOrderCount());
            data.setOrderMoney(channelPopularizeView.getOrderMoney());
            data.setRefundCount(channelPopularizeView.getRefundCount());
            data.setRefundMoney(channelPopularizeView.getRefundMoney());

            //AI会员订单数据
            ChannelPopularizeView vipView = vipOrderDonMapper.countPopularizeOrderDetail(data.getId(), goodsId, startTime, endTime);
            data.setOrderCount(data.getOrderCount() + vipView.getOrderCount());
            data.setOrderMoney(data.getOrderMoney().add(vipView.getOrderMoney()));
            data.setRefundCount(data.getRefundCount() + vipView.getRefundCount());
            data.setRefundMoney(data.getRefundMoney().add(vipView.getRefundMoney()));

            Integer visitCount = visitMapper.selectCount(Wrappers.lambdaQuery(ChannelPopularizeVisit.class)
                    .eq(ChannelPopularizeVisit::getPopularizeId, data.getId())
                    .ge(StrUtil.isNotEmpty(startTime), ChannelPopularizeVisit::getCreatedTime, startTime)
                    .lt(StrUtil.isNotEmpty(endTime), ChannelPopularizeVisit::getCreatedTime, endTime));
            data.setVisit(visitCount);

            CorpCustomerAcquisitionLinkPopularize acquisitionLinkPopularize = acquisitionLinkPopularizeMapper.selectOne(Wrappers.lambdaQuery(CorpCustomerAcquisitionLinkPopularize.class)
                    .eq(CorpCustomerAcquisitionLinkPopularize::getPopularizeId, data.getId())
                    .last("limit 1"));
            if (acquisitionLinkPopularize != null) {
                data.setCorpCustomerLinkId(acquisitionLinkPopularize.getId());
            }
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(searchResult);
    }

    @GetMapping("/{id}")
    public Result<List<ChannelPopularizeDetailView>> getById(@PathVariable Long id, String startTime, String endTime){
        String timeSql = StringUtils.EMPTY;
        if(StringUtils.isNotBlank(startTime)){
            timeSql += " and o.created_time >= '" + startTime + "'";
        }
        if(StringUtils.isNotBlank(endTime)){
            timeSql += " and o.created_time <= '" + endTime + "'";
        }
        List<ChannelPopularizeDetailView> result = beanSearcher.searchAll(ChannelPopularizeDetailView.class,
                MapUtils.flatBuilder(request.getParameterMap())
                        .field(ChannelPopularizeDetailView::getPopularizeId, id)
                        .put("time", timeSql)
                        .orderBy(ChannelPopularizeDetailView::getGoodsId).asc()
                        .build());
        //银河AI会员订单 单独查询
        VipOrderDonPopularizeView view = beanSearcher.searchFirst(VipOrderDonPopularizeView.class, MapUtils.builder().field(VipOrderDonPopularizeView::getPopularizeId, id).put("time", timeSql).build());
        ChannelPopularizeDetailView vipOrderDonPopularizeView = new ChannelPopularizeDetailView();
        BeanUtil.copyProperties(view, vipOrderDonPopularizeView);
        result.add(vipOrderDonPopularizeView);
        return GatewayResponse.SUCCESS.newBuilder().toResult(result);
    }

    @PostMapping
    public Result<ChannelPopularize> post(@RequestBody ChannelPopularize popularize){
        channelPopularizeService.save(popularize);
        return GatewayResponse.SUCCESS.newBuilder().toResult(channelPopularizeService.getById(popularize.getId()));
    }

    @PutMapping
    public Result<String> put(@RequestBody ChannelPopularize popularize){
        channelPopularizeService.updateById(popularize);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    @DeleteMapping("/{id}")
    public Result<String> del(@PathVariable Long id){
        channelPopularizeService.removeById(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    @GetMapping("/get")
    public Result<List<ChannelPopularize>> getAllPopularizeList() {
        List<ChannelPopularize> list = beanSearcher.searchAll(ChannelPopularize.class, MapUtils.flatBuilder(request.getParameterMap()).onlySelect(ChannelPopularize::getId, ChannelPopularize::getName).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(list);
    }
}
