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

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.annotation.Log;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.config.corp.WeChatCorpFactory;
import com.cyksj.dto.Result;
import com.cyksj.enums.BusinessType;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.corp.CorpUserAuthMapper;
import com.cyksj.mapper.corp.CorpUserMapper;
import com.cyksj.mapper.manage.coupon.*;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.CorpCouponSendReq;
import com.cyksj.model.request.corp.CorpXmlMessage;
import com.cyksj.model.views.CouponClassificationView;
import com.cyksj.model.views.CouponView;
import com.cyksj.model.views.GoodsDonSkuView;
import com.cyksj.service.corp.msg.CorpEventActionService;
import com.cyksj.service.coupon.EquipmentActivityReduceService;
import com.cyksj.service.mange.coupon.CouponCommonService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author chan
 * @date 2025/1/22 16:24
 */
@RestController
@RequestMapping("/manage/coupon")
@RequiredArgsConstructor
@Slf4j
public class CouponController {

    private final CouponCommonService couponCommonService;

    private final CouponMapper couponMapper;

    private final BeanSearcher beanSearcher;

    private final CouponRecommendMapper couponRecommendMapper;

    private final CouponDistributePopularizeMapper couponDistributePopularizeMapper;

    private final CouponActiveMapper couponActiveMapper;

    private final CouponUserMapper couponUserMapper;

    private final CouponSkuMapper couponSkuMapper;

    private final CorpUserMapper corpUserMapper;

    private final CorpEventActionService corpEventActionService;

    private final CorpUserAuthMapper corpUserAuthMapper;

    private final CouponClassificationMapper couponClassificationMapper;

    private final OrderDonMapper orderDonMapper;

    private final HttpServletRequest request;

    private final EquipmentActivityReduceService equipmentActivityReduceService;


    /**
     * 优惠券分类列表
     */
    @GetMapping("/get/classification")
    public Result<SearchResult<CouponClassificationView>> classificationView() {
        SearchResult<CouponClassificationView> search = beanSearcher.search(CouponClassificationView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 新增优惠券
     */
    @PostMapping
    @Log(module = "优惠券/新增优惠券", businessType = BusinessType.POST, isSaveRequestData = true)
    public Result<String> couponSave(@RequestBody @Validated Coupon coupon) throws Exception {
        couponCommonService.saveCoupon(coupon);
        return GatewayResponse.SUCCESS.newBuilder().toResult("新增优惠券成功");
    }


    /**
     * 优惠券列表
     */
    @GetMapping
    public Result<SearchResult<CouponView>> couponList(HttpServletRequest request) {
        SearchResult<CouponView> search = beanSearcher.search(CouponView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
        search.getDataList().forEach(data -> {
            data.setRelationNum(couponDistributePopularizeMapper.selectCount(Wrappers.lambdaQuery(CouponDistributePopularize.class).eq(CouponDistributePopularize::getDeleted, 1).eq(CouponDistributePopularize::getCouponId, data.getId())));

            Map<String, Long> couponUserNumData = couponUserMapper.selectCouponUserNumData(data.getId());
            Integer usedNum = Integer.parseInt(couponUserNumData.get("usedNum").toString());
            data.setUsedNum(usedNum);
            Integer receiptNum = Integer.parseInt(couponUserNumData.get("receiptNum").toString());
            data.setReceiptNum(receiptNum);

            List<GoodsDonSkuView> skuViewList = couponSkuMapper.selectGoodsSkuViewList(data.getId());
            data.setSkuViewList(skuViewList);
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 企业微信发放优惠券
     */
    @PostMapping("/corp/send")
    public Result<String> corpSendCoupon(@RequestBody @Validated CorpCouponSendReq corpCouponSendReq) throws Exception {
        String corpId = corpCouponSendReq.getCorpId();
        String externalUserId = corpCouponSendReq.getExternalUserId();
        String unionid = getUnionId(corpId, externalUserId);
        Long couponId = corpCouponSendReq.getCouponId();
        if (StrUtil.isEmpty(unionid)) {
            throw BusinessRuntimeException.getInstance("该用户不是微信用户");
        }
        couponCommonService.corpSendCoupon(unionid, couponId);
        return GatewayResponse.SUCCESS.newBuilder().toResult("发放优惠券成功");
    }

    public String getUnionId(String corpId, String externalUserId) throws Exception {
        WxCorpApp wxCorpApp = WeChatCorpFactory.getCorpConfigStrategy(corpId);
        LambdaQueryWrapper<CorpUserAuth> corpUserAuthWrapper = Wrappers.lambdaQuery(CorpUserAuth.class)
                .eq(CorpUserAuth::getExternalUserid, externalUserId)
                .eq(CorpUserAuth::getWxCorpId, wxCorpApp.getId()).last("limit 1");
        CorpUserAuth corpUserAuth = corpUserAuthMapper.selectOne(corpUserAuthWrapper);
        CorpUser corpUser = null;
        if (corpUserAuth == null) {
            //尝试添加客户
            CorpXmlMessage message = new CorpXmlMessage();
            message.setToUserName(wxCorpApp.getCorpId());
            message.setExternalUserId(externalUserId);
            corpEventActionService.addExternalContact(message, null);
            corpUserAuth = corpUserAuthMapper.selectOne(corpUserAuthWrapper);
            if (corpUserAuth != null) {
                corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class).eq(CorpUser::getId, corpUserAuth.getCorpUserId()).last("limit 1"));
            }
        } else {
            corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class).eq(CorpUser::getId, corpUserAuth.getCorpUserId()).last("limit 1"));
        }
        if (corpUser == null) {
            log.info("该客户{}不存在", externalUserId);
            throw BusinessRuntimeException.getInstance("该企业微信用户不存在..");
        }
        return corpUser.getUnionid();
    }

    /**
     * 可选优惠券 分页列表
     */
    @GetMapping("/get/available/coupons")
    public Result<SearchResult<CouponView>> getAvailableCoupons() {
        SearchResult<CouponView> search = beanSearcher.search(CouponView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }
}
