package cn.myapps.runtime.chart.service;

import java.util.ArrayList;

import cn.myapps.runtime.dynaform.document.model.IDocument;
import org.springframework.stereotype.Component;

import cn.myapps.common.auth.IUser;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.model.chart.Chart;
import cn.myapps.common.util.StringUtil;
import cn.myapps.designtime.chart.service.ChartDesignTimeServiceImpl;
import cn.myapps.runtime.dynaform.form.ejb.ValidateMessage;
import cn.myapps.runtime.macro.runner.IRunner;
import cn.myapps.runtime.macro.runner.JavaScriptFactory;

@Component
public class ChartServiceImpl extends ChartDesignTimeServiceImpl implements
        ChartService {



    @Override
    public Object buildEChartOption(Chart chart, ParamsTable params, IUser user, IDocument doc) throws Exception {
        Object optionText = "";
        if (!StringUtil.isBlank(chart.getScripttext())) {
            IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), chart.getApplicationid());
            runner.initBSFManager(doc, params, user, new ArrayList<ValidateMessage>());
            try {
                String scriptText = chart.getScripttext();
                scriptText = "JSON.stringify("+scriptText+")";

                Object result = runner.run(chart,"Chart[" + chart.getName() + "]-" + chart.getId(), scriptText);
                optionText =  result;
                 /*if (result instanceof String) {
                 } else {
                     throw new Exception("Chart[" + chart.getName() + "]脚本运算结果不合法，请返回字符串！");
                 }*/
            } catch (Exception e) {
                e.printStackTrace();
                optionText = e.getMessage();
            }
        }
        return optionText;
    }

}
