package com.xunmei.sync.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xunmei.common.core.http.service.params.HttpParamsGet;
import com.xunmei.sync.config.ThirdPartySystemConfig;
import com.xunmei.sync.dto.fjnxsync.FJNXXmlOrgDto;
import com.xunmei.sync.dto.fjnxsync.SyncResponseDto;
import com.xunmei.sync.service.IFJNXOrgSyncService;
import com.xunmei.sync.service.api.FjnxApi;
import com.xunmei.sync.service.api.FjnxXmlApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhulu
 * @date 2022/5/30 16:02
 */
@Service
@Slf4j
public class FJNXOrgSyncServiceImpl implements IFJNXOrgSyncService {

    @Autowired
    FjnxApi fjnxApi;

    @Autowired
    FjnxXmlApi fjnxXmlApi;

    @Autowired
    private ThirdPartySystemConfig thirdPartySystemConfig;

    @Override
    public SyncResponseDto getOrgSyncFileInfo() {
        final Map<String, Object> params = new HashMap<>();
        // TODO 后期将参数和地址 放在数据库中，放在配置文件中如果不是多套需要修改多个配置文件，可以放在数据库中 获取一次后放入Redis缓存
        params.put("systemCode", thirdPartySystemConfig.getFjnxSystemCode());
        params.put("orgCode", thirdPartySystemConfig.getFjnxSyncOrgTopOrgCode());
//        final JSONObject data = this.fjnxApi.get(HttpParamsGet.get(thirdPartySystemConfig.getFjnxSyncOrgFileInfoUrl(), params));
        JSONObject data = this.fjnxApi.get(HttpParamsGet.get(thirdPartySystemConfig.getFjnxSyncOrgFileInfoUrl(), params));
        if (data == null) {
            return null;
        }
        return  JSONObject.toJavaObject(data,SyncResponseDto.class);
    }

    @Override
    public FJNXXmlOrgDto getOrgInfoByFileInfo() {
        SyncResponseDto syncResponseDto =getOrgSyncFileInfo();
        if(syncResponseDto==null) return null;

        // TODO 后期将参数和地址 放在数据库中，放在配置文件中如果不是多套需要修改多个配置文件，可以放在数据库中 获取一次后放入Redis缓存
        final Map<String, Object> params = new HashMap<>();
        params.put("systemCode",  thirdPartySystemConfig.getFjnxSystemCode());//"61303"
        params.put("fileName", syncResponseDto.getData().getFileName());
        params.put("fileId", syncResponseDto.getData().getFileId());
        params.put("storageType", "localdisk");
//        final String data= fjnxXmlApi.get(HttpParamsGet.get(thirdPartySystemConfig.getFjnxSyncOrgFileDownloadUrl(), params));
        final String data= fjnxXmlApi.get(HttpParamsGet.get(thirdPartySystemConfig.getFjnxSyncOrgFileDownloadUrl(), params)); //"/fjnx/mock/orgxmldata"

        try {
            return FjnxXmlApi.convertXmlToJavaBean(data, FJNXXmlOrgDto.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
