package com.ms.biz.spi.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinritemai.cloud.base.api.BaseRequest;
import com.jinritemai.cloud.base.api.BaseResponse;
import com.jinritemai.cloud.base.api.ExtensionService;
import com.jinritemai.cloud.base.api.ExtensionServiceHandler;
import com.ms.biz.common.SPIBaseService;
import com.ms.biz.service.ShopService;
import com.ms.biz.tool.SecurityTool;
import com.ms.dal.entity.Shop;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.Objects;

/**
 * 抖店授权回调地址
 */
@ExtensionService("shopAuthCallback")
@Slf4j
public class ShopAuthCallbackService extends SPIBaseService implements ExtensionServiceHandler<CallBackRequest, String> {

    @Value("${cloud.app.secret}")
    private String cloudAppSecret;

    @Autowired
    private ShopService shopService;

    @Override
    public BaseResponse<String> handle(BaseRequest<CallBackRequest> req) {
        // ----参数校验----
        log.info("receive callback: " + JSON.toJSONString(req));
        String url = req.getData().getUrl();
        String reqBody = req.getData().getBody();
        String key = cloudAppSecret.replaceAll("-", "");
        reqBody = SecurityTool.decryptDoudianCallback(reqBody, key);
        log.info("receive callback body: " + reqBody);

        JSONObject bodyObj = JSONObject.parseObject(reqBody);
        Integer msgType = bodyObj.getInteger("msg_type");
        String msg = bodyObj.getString("msg");
        JSONObject msgObj = JSONObject.parseObject(msg);
        Long shopId = null;
        String shopName = "";
        Long expireTime = null;
        String appVersion = "";

        if (msgType == 2) { // 授权消息
            shopId = msgObj.getLong("shop_id");

            int actionType = msgObj.getInteger("action_type");
            if (actionType == 1 || actionType == 3) { // 关闭授权或授权超时时，去更新授权过期时间为当期时间
                expireTime = System.currentTimeMillis() / 1000;
            }

        } else if (msgType == 1) { // 支付消息
            JSONObject orderInfoObj = msgObj.getJSONObject("order_info");
            shopId = orderInfoObj.getLong("shop_id");
            expireTime =  orderInfoObj.getLong("service_end_time");
            JSONObject pushSkuInfoObj = orderInfoObj.getJSONObject("push_sku_info");
            appVersion = pushSkuInfoObj.getString("spec_value");
        }

        Shop shop = shopService.getDetailById(shopId);
        boolean isNewShop = Objects.isNull(shop);
        Shop shopData = new Shop();
        shopData.setShopId(shopId);
        shopData.setGmtModified(new Date());
        if (StringUtils.isNotEmpty(shopName)) {
            shopData.setShopName(shopName);
        }
        if (StringUtils.isNotEmpty(appVersion)) {
            shopData.setAppVersion(appVersion);
        }
        if (expireTime != null) {
            shopData.setGmtExpire(new Date(expireTime * 1000L));
        }

        if (isNewShop) {
            shopData.setGmtCreate(new Date());
            shopService.insertSelective(shopData);
        } else {
            shopService.updateByPrimaryKeySelective(shopData);
        }

        // 按照三方平台的规范返回成功或失败的body值
        String respBody = "{\"success\":true,\"code\":0}";
        return BaseResponse.<String>builder().success(true).code("0").data(respBody).build();
    }
}

@Data
class CallBackRequest {
    private String url;
    private String body;
}
