package cn.com.poc.appbuilder.rest.impl;

import cn.com.poc.appbuilder.api.BaiduAppBuilderApi;
import cn.com.poc.appbuilder.api.entity.AppBuilderDescribeListRequest;
import cn.com.poc.appbuilder.api.entity.AppBuilderDescribeRequest;
import cn.com.poc.appbuilder.api.entity.BaiduAppBuilderDescribeAppListResult;
import cn.com.poc.appbuilder.api.entity.BaiduAppBuilderDescribeAppResult;
import cn.com.poc.appbuilder.model.BizAppbuilderInfoModel;
import cn.com.poc.appbuilder.rest.AppBuilderDescribeAppRest;
import cn.com.poc.appbuilder.service.BizAppbuilderInfoService;
import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.yict.framemax.core.utils.BeanUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class AppBuilderDescribeAppRestImpl implements AppBuilderDescribeAppRest {

    @Resource
    private BaiduAppBuilderApi baiduAppBuilderApi;

    @Resource
    private BizAppbuilderInfoService bizAppbuilderInfoService;

    @Override
    public BaiduAppBuilderDescribeAppResult getDescribeApp(String appId) throws Exception {
        Assert.notNull(appId, "参数不能为空");
        BaiduAppBuilderDescribeAppResult baiduAppBuilderDescribeAppResult = new BaiduAppBuilderDescribeAppResult();
        BizAppbuilderInfoModel model = new BizAppbuilderInfoModel();
        model.setId(appId);
        List<BizAppbuilderInfoModel> models = bizAppbuilderInfoService.findByExample(model, null);

        if (CollectionUtils.isEmpty(models)) {
            AppBuilderDescribeRequest appBuilderDescribeRequest = new AppBuilderDescribeRequest(appId);
            String str = baiduAppBuilderApi.getDescribeApp(appBuilderDescribeRequest);
            baiduAppBuilderDescribeAppResult = JSONObject.parseObject(str, BaiduAppBuilderDescribeAppResult.class);
        } else {
            BeanUtils.copy(models.get(0), baiduAppBuilderDescribeAppResult);
            String exampleQueries = models.get(0).getExampleQueries();
            List<String> queriesList = (List<String>) JsonUtils.deSerialize(exampleQueries, new TypeReference<List<String>>() {
            }.getType());
            baiduAppBuilderDescribeAppResult.setExampleQueries(queriesList);
        }
        return baiduAppBuilderDescribeAppResult;
    }

    @Override
    public BaiduAppBuilderDescribeAppListResult getDescribeAppList(String marker, Integer maxKeys) throws Exception {
        Assert.notNull(marker, "参数不能为空");
        Assert.notNull(maxKeys, "参数不能为空");
        AppBuilderDescribeListRequest appBuilderDescribeListRequest = new AppBuilderDescribeListRequest(marker, maxKeys);
        return baiduAppBuilderApi.getDescribeAppList(appBuilderDescribeListRequest);
    }
}
