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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
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.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.*;

@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;

    @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);

        // TODO
        return Result.ok(Arrays.asList(new ProductInfoVO(), new ProductInfoVO()));
    }

    @IgnoreAuth
    @PostMapping("/enquiry/list")
    @ResponseBody
    public Result<EnquiryPageVO> listEnquires(
            @RequestHeader(value = BEARER_TOKEN_HEADER, required = true) String authToken,
            @RequestBody APIRequestVO apiRequest) {
        this.validateAuthToken(authToken);

        // TODO
        EnquiryPageVO enquiryPage = new EnquiryPageVO();
        enquiryPage.setRecords(Arrays.asList(new EnquiryInfoVO(), new EnquiryInfoVO()));
        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);
        // 获取站点
        QueryWrapper<AdwebSite> adwebSiteQueryWrapper = new QueryWrapper<>();
        adwebSiteQueryWrapper.like("domain", 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);
    }

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