package cn.iocoder.yudao.module.system.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.system.api.kingdee.KingdeeApi;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.YearMonth;

@Component
@Slf4j
public class KingdeeOrderAbleSyncIdJob implements JobHandler {

    private final static Logger logger = LoggerFactory.getLogger(KingdeeOrderAbleSyncIdJob.class);

    @Resource
    private KingdeeApi kingdeeApi;

    @Override
    @TenantIgnore
    public String execute(String jsonParam) {
        logger.info("KingdeeOrderAbleSyncIdJob execute param:{}", jsonParam);
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(jsonParam, JsonObject.class);
        JsonArray tenantIds = jsonObject.getAsJsonArray("tenantIds");
        if (tenantIds == null) {
            return "参数错误，tenantIds为空！";
        }
        JsonElement billingMonthElement = jsonObject.get("billingMonth");
        String billingMonth = billingMonthElement == null || StringUtils.isBlank(billingMonthElement.getAsString()) ? YearMonth.now().toString() : billingMonthElement.getAsString();
        StringBuilder msg = new StringBuilder();
        for (JsonElement tenantId : tenantIds) {
            // 应收单
            Integer syncCount = kingdeeApi.syncArReceivable(tenantId.getAsLong(), billingMonth);
            msg.append(String.format("租户{}同步金蝶用户账单数量{}", tenantId.getAsLong(), syncCount)).append("\n");
        }
        return msg.toString();
    }

}
