package com.seeyon.apps.esign.job;

import com.seeyon.aicloud.common.JsonUtils;
import com.seeyon.apps.esign.config.EsignConfigProvider;
import com.seeyon.apps.esign.constants.EsignApiUrl;
import com.seeyon.apps.esign.constants.EsignConfigConstants;
import com.seeyon.apps.esign.po.esignapi.EsignApiHeader;
import com.seeyon.apps.esign.po.esignapi.EsignBaseResp;
import com.seeyon.apps.esign.po.seal.SealInfoVo;
import com.seeyon.apps.esign.service.SealService;
import com.seeyon.apps.esign.service.TokenCacheManager;
import com.seeyon.apps.esign.utils.HttpClient;
import com.seeyon.apps.ext.quartz.AbstractQuartzTask;
import com.seeyon.ctp.common.AppContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import java.util.List;
import java.util.Map;


public class SealDocSyncJob extends AbstractQuartzTask {

    private static final Log log = LogFactory.getLog(SealDocSyncJob.class);

    private EsignConfigProvider configProvider = EsignConfigProvider.getInstance();
    private TokenCacheManager tokenCacheManager = (TokenCacheManager) AppContext.getBean("tokenCacheManager");
    private SealService sealService = (SealService) AppContext.getBean("sealService");

    @Override
    public String taskRun(String s) throws Exception {
        log.info("开始执行印章同步任务");
        List<String> appIds = tokenCacheManager.getAppIds();
        for (String appId : appIds) {
            syncSeals(appId);
        }
        log.info("印章同步任务完成");
        return "";
    }

    private void syncSeals(String appId) {
        String host = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST);
        Integer pageNum = 1;
        Integer pageSize = 20;
        EsignApiHeader esignApiHeader = EsignApiHeader.build().appId(appId);
        esignApiHeader.token(tokenCacheManager.getToken(appId));
        EsignBaseResp esignBaseResp = null;
        Map<String,Object> dataMap = null;
        do {
            String url = host + EsignApiUrl.SEAL_QUERY_URL + "?" + "orgId=" + tokenCacheManager.getOrgNameByAppId(appId) + "&pageNum=" + (pageNum++) + "&pageSize=" + pageSize;
            String respStr = HttpClient.httpGet(url, esignApiHeader.convert2Headers(),"UTF-8");
            esignBaseResp = JsonUtils.parseObject(respStr, EsignBaseResp.class);
            if(esignBaseResp.getCode() != 0) {
                break;
            }
            dataMap = (Map<String,Object>)esignBaseResp.getData();
            Object[] sealArray = (Object[]) dataMap.get("seals");
            if(sealArray == null || sealArray.length == 0) {
                break;
            }
            for (Object o : sealArray) {
                SealInfoVo sealInfoVo = JsonUtils.parseObject(JsonUtils.toJSONString(o), SealInfoVo.class);
                sealService.upsertOaSealDoc(sealInfoVo);
            }
        }while (true);

    }

    @Override
    public String getName() {
        return "E签宝印章信息同步任务";
    }
}
