package org.jeecg.modules.adweb.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.shiro.IgnoreAuth;
import org.jeecg.modules.adweb.api.vo.APIRequestVO;
import org.jeecg.modules.adweb.api.vo.EnquiryInfoVO;
import org.jeecg.modules.adweb.api.vo.EnquiryPageVO;
import org.jeecg.modules.adweb.api.vo.ProductInfoVO;
import org.jeecg.modules.adweb.common.mapper.CommonMapper;
import org.jeecg.modules.adweb.enquiry.entity.AdwebEnquiry;
import org.jeecg.modules.adweb.enquiry.service.IAdwebEnquiryService;
import org.jeecg.modules.adweb.product.entity.AdwebProduct;
import org.jeecg.modules.adweb.product.service.IAdwebProductService;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/openapi")
@Slf4j
public class OpenAPIController {

    private static final String BEARER_TOKEN_HEADER = "AdWeb-Authorization";
    private static final String STATIC_BEARER_TOKEN = "Bearer uxl9Wpzh65vXNUyDvynJDjBo";

    @Resource private CommonMapper commonMapper;

    @Resource private IAdwebSiteService adwebSiteService;

    @Resource private IAdwebProductService adwebProductService;

    @Resource private IAdwebEnquiryService adwebEnquiryService;

    /** 外部api请求获取产品列表 */
    @IgnoreAuth
    @PostMapping("/product/list")
    @ResponseBody
    public Result<List<ProductInfoVO>> listProducts(
            @RequestHeader(value = BEARER_TOKEN_HEADER, required = true) String authToken,
            @RequestBody APIRequestVO apiRequest) {
        this.validateAuthToken(authToken);

        log.info("苏豪通请求产品列表 parameter: {}", apiRequest);

        LambdaQueryWrapper<AdwebSite> adwebSiteQueryWrapper = new LambdaQueryWrapper<>();
        adwebSiteQueryWrapper.like(AdwebSite::getDomain, apiRequest.getDomain());
        List<AdwebSite> adwebSites =
                adwebSiteService.getBaseMapper().selectList(adwebSiteQueryWrapper);

        if (CollectionUtils.isNotEmpty(adwebSites)) {
            LambdaQueryWrapper<AdwebProduct> adwebProductQueryWrapper = new LambdaQueryWrapper<>();
            adwebProductQueryWrapper.eq(AdwebProduct::getSiteCode, adwebSites.get(0).getCode());
            adwebProductQueryWrapper.ne(AdwebProduct::getActionType, "delete");
            List<AdwebProduct> adwebProducts = adwebProductService.list(adwebProductQueryWrapper);

            return Result.ok(adwebProducts.stream().map(ProductInfoVO::fromAdwebProduct).toList());
        } else {
            return Result.error("未找到该站点！");
        }
    }

    /** 外部api请求获取询盘列表 */
    @IgnoreAuth
    @PostMapping("/enquiry/list")
    @ResponseBody
    public Result<EnquiryPageVO> listEnquires(
            @RequestHeader(value = BEARER_TOKEN_HEADER, required = true) String authToken,
            @RequestBody APIRequestVO apiRequest) {
        this.validateAuthToken(authToken);

        log.info("苏豪通请求询盘列表 parameter: {}", apiRequest);

        LambdaQueryWrapper<AdwebSite> adwebSiteQueryWrapper = new LambdaQueryWrapper<>();
        adwebSiteQueryWrapper.like(AdwebSite::getDomain, apiRequest.getDomain());
        List<AdwebSite> adwebSites =
                adwebSiteService.getBaseMapper().selectList(adwebSiteQueryWrapper);

        EnquiryPageVO enquiryPage = new EnquiryPageVO();
        if (CollectionUtils.isNotEmpty(adwebSites)) {
            Page<AdwebEnquiry> page = new Page<>(apiRequest.getPageNo(), apiRequest.getPageSize());

            LambdaQueryWrapper<AdwebEnquiry> enquiryQueryWrapper = new LambdaQueryWrapper<>();
            enquiryQueryWrapper.eq(AdwebEnquiry::getSiteCode, adwebSites.get(0).getCode());
            enquiryQueryWrapper.in(AdwebEnquiry::getUserEffective, "1", "2"); // 获取所有有效询盘
            IPage<AdwebEnquiry> pageList = adwebEnquiryService.page(page, enquiryQueryWrapper);

            if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
                // 复制属性到需要返回的新对象
                List<EnquiryInfoVO> enquiryInfoVOS =
                        pageList.getRecords().stream()
                                .map(EnquiryInfoVO::fromAdwebEnquiry)
                                .toList();

                enquiryPage.setPages(pageList.getPages());
                enquiryPage.setSize(pageList.getSize());
                enquiryPage.setCurrent(pageList.getCurrent());
                enquiryPage.setTotal(pageList.getTotal());
                enquiryPage.setRecords(enquiryInfoVOS);
            }
        } else {
            return Result.error("未找到该站点！");
        }

        return Result.ok(enquiryPage);
    }

    @IgnoreAuth
    @PostMapping("/product/getMaxDate")
    @ResponseBody
    public Result<?> getMaxDate(
            @RequestHeader(value = BEARER_TOKEN_HEADER, required = true) String authToken,
            HttpServletRequest request) {
        this.validateAuthToken(authToken);

        String domain = request.getParameter("siteHost");
        if (domain == null) {
            return Result.error("未传递合法的参数！");
        }

        log.info("request from domain: {}", domain);
        // 获取站点
        LambdaQueryWrapper<AdwebSite> adwebSiteQueryWrapper = new LambdaQueryWrapper<>();
        adwebSiteQueryWrapper.like(AdwebSite::getDomain, domain);
        AdwebSite adwebsite = adwebSiteService.getOne(adwebSiteQueryWrapper);
        if (adwebsite == null) {
            return Result.error("该站点未绑定adweb3系统！");
        }

        String filterSiteCode = "site_code='%s'".formatted(adwebsite.getCode());

        Date maxDate = commonMapper.getMaxDate("adweb_product", "request_time", filterSiteCode);
        Long maxTime = null;
        if (maxDate != null) {
            maxTime = maxDate.getTime();
        }

        Map<String, Object> result = new HashMap<>();

        result.put("maxTime", maxTime);
        result.put(
                "wordpress_setting",
                adwebsite.getWordpressSetting()); // 指定wordpress 传输的产品类型是来自adwebpro还是woocommerce
        return Result.ok(result);
    }

    @IgnoreAuth
    @PostMapping("/enquiry/getMaxDate")
    @ResponseBody
    public Result<?> getEnquiryMaxDate(
            @RequestHeader(value = BEARER_TOKEN_HEADER, required = true) String authToken,
            HttpServletRequest request) {
        this.validateAuthToken(authToken);

        String domain = request.getParameter("siteHost");
        if (domain == null) {
            return Result.error("未传递合法的参数！");
        }

        log.info("EnquiryMaxDate request from domain: {}", domain);
        // 获取站点
        LambdaQueryWrapper<AdwebSite> adwebSiteQueryWrapper = new LambdaQueryWrapper<>();
        adwebSiteQueryWrapper.like(AdwebSite::getDomain, domain);
        AdwebSite adwebsite = adwebSiteService.getOne(adwebSiteQueryWrapper);
        if (adwebsite == null) {
            return Result.error("该站点未绑定adweb3系统！");
        }

        String filterSiteCode = "site_code='%s'".formatted(adwebsite.getCode());

        Date maxDate = commonMapper.getMaxDate("adweb_enquiry", "record_ctime", filterSiteCode);
        Long maxTime = null;
        if (maxDate != null) {
            maxTime = maxDate.getTime();
        }

        Map<String, Object> result = new HashMap<>();

        result.put("maxTime", maxTime);

        return Result.ok(result);
    }

    private boolean validateAuthToken(String authToken) {
        if (!StringUtils.equals(STATIC_BEARER_TOKEN, authToken)) {
            throw new InvalidBearerTokenException("Bearer toke is invalid: " + authToken);
        }
        return true;
    }
}
