package com.cyksj.web.controller.channel;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.channel.ChannelPopularizeMapper;
import com.cyksj.mapper.channel.ChannelPopularizeVisitMapper;
import com.cyksj.mapper.channel.MoviesVisitRecordMapper;
import com.cyksj.mapper.manage.coupon.CouponSkuMapper;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.model.entity.ChannelPopularizeVisit;
import com.cyksj.model.entity.MoviesVisitRecord;
import com.cyksj.model.entity.SysConfig;
import com.cyksj.model.manage.dto.ChannelBaiDuDiscountDto;
import com.cyksj.model.views.ChannelPopularizeFrontView;
import com.cyksj.model.views.CouponTfPopularizeView;
import com.cyksj.service.corp.CorpCustomerAcquistionService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author chan
 * @date 2022/12/13 2:36 PM
 */
@RequestMapping("/applets/channel")
@RestController
@RequiredArgsConstructor
@Slf4j
public class ChannelController {

    private final HttpServletResponse response;

    private final ChannelPopularizeVisitMapper channelPopularizeVisitMapper;

    private final ChannelPopularizeMapper popularizeMapper;

    private final MoviesVisitRecordMapper moviesVisitRecordMapper;

    private final BeanSearcher beanSearcher;

    private final CouponSkuMapper couponSkuMapper;

    private final CorpCustomerAcquistionService corpCustomerAcquistionService;

    private final SysConfigMapper sysConfigMapper;



    @GetMapping("/get/{id}")
    public Result<ChannelPopularizeFrontView> getById(@PathVariable Long id) {
        ChannelPopularizeFrontView channelPopularize = beanSearcher.searchFirst(ChannelPopularizeFrontView.class, MapUtils.builder()
                .put("id", String.format("id = %s", id))
                .build());

        if (channelPopularize == null) {
            throw BusinessRuntimeException.getInstance("该链接不存在！");
        }
        if (StrUtil.isNotBlank(channelPopularize.getCouponIds())) {
            try {
                List<Long> couponIds = Jsons.parseList(channelPopularize.getCouponIds(), Long.class);
                Long userId = StpUserUtil.getUserIdAfterLogin();
                MapBuilder builder = MapUtils.builder().field(CouponTfPopularizeView::getCouponId, couponIds).op(Operator.InList);
                if (userId != null) {
                    builder.put("user_id", String.format("and cu.user_id = %s", userId));
                }
                List<CouponTfPopularizeView> couponTfPopularizeViews = beanSearcher.searchAll(CouponTfPopularizeView.class, builder.build());
                couponTfPopularizeViews.forEach(data -> {
                    String str = couponSkuMapper.selectGoodsSkuStr(data.getCouponId());
                    data.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
                });
                channelPopularize.setCoupons(couponTfPopularizeViews);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        String channelName = channelPopularize.getChannelName();
        if (channelName.contains(Constant.NO_SIGN_CHANNEL_NAMES.get(0)) || channelName.contains(Constant.NO_SIGN_CHANNEL_NAMES.get(1))) {
            String key;
            if (channelName.contains(Constant.NO_SIGN_CHANNEL_NAMES.get(0))) {
                key = Constant.CHANNEL_BAIDU_DISCOUNT_KEY;
            } else {
                key = Constant.CHANNEL_DY_DISCOUNT_KEY;
            }
            SysConfig baiduConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
                    .eq(SysConfig::getSysKey, key).last("limit 1"));
            if (baiduConfig != null) {
                String sysValue = baiduConfig.getSysValue();
                if (StrUtil.isNotBlank(sysValue)) {
                    try {
                        ChannelBaiDuDiscountDto baiDuDiscountDto = Jsons.parseObject(sysValue, ChannelBaiDuDiscountDto.class);
                        if (baiDuDiscountDto != null && CollUtil.isNotEmpty(baiDuDiscountDto.getPopularizeIds()) && baiDuDiscountDto.getPopularizeIds().contains(id)) {
                            channelPopularize.setIsSign(true);
                            channelPopularize.setDiscount(baiDuDiscountDto.getDiscount());
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
        ChannelPopularizeVisit channelPopularizeVisit = new ChannelPopularizeVisit();
        channelPopularizeVisit.setPopularizeId(id);
        channelPopularizeVisitMapper.insert(channelPopularizeVisit);
        return GatewayResponse.SUCCESS.newBuilder().toResult(channelPopularize);
    }

    /**
     * 记录银河电影浏览量
     */
    @PostMapping("/movies/record/")
    public Result<String> moviesVisitRecord() {
        MoviesVisitRecord moviesVisitRecord = new MoviesVisitRecord();
        moviesVisitRecord.setType(MoviesVisitRecord.Type.movies);
        moviesVisitRecordMapper.insert(moviesVisitRecord);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 橙子建站带参跳转获客链接
     */
    @GetMapping("/customerAcquistion")
    public void customerAcquistion(String projectid, String clickid, String callback, Long linkId) throws Exception {
        log.info("橙子建站带参跳转获客链接 projectid:{} clickid:{},callback:{}", projectid, clickid, callback);
        if (StrUtil.equals(projectid, "__PROJECT_ID__") && StrUtil.equals(clickid, "__CLICKID__") && linkId != null && linkId == 5) {
            response.sendRedirect("https://www.chengzijianzhan.com/tetris/page/7321557902601240626/");
            return;
        }
        String key = corpCustomerAcquistionService.saveClickid(projectid, clickid, callback, linkId);
        String url = corpCustomerAcquistionService.getUrlByLinkId(linkId);

        String redirect = url + "?customer_channel=" + "customer_" + key;
        log.info("橙子建站带参跳转获客链接 跳转路径:{}", redirect);
        response.sendRedirect(redirect);
    }

    /**
     * 动态客服 链接
     * acLinkId 获客链接id
     */
    @GetMapping("/customerAcquistion/{acLinkId}")
    public void getCustomerAcquistionById(@PathVariable Long acLinkId) throws Exception {
        log.info("动态客服获客链接跳转 acLinkId:{}", acLinkId);

        String url = corpCustomerAcquistionService.getActiveCustomerAcquistionById(acLinkId);

        String redirect = url + "?customer_channel=" + "customer_" + acLinkId;
        log.info("动态客服获客链接 跳转路径:{}", redirect);
        response.sendRedirect(redirect);
    }
}
