package com.kingdee.eas.custom.dataconfig.utils.service;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.dataconfig.utils.SqlUtils;
import com.kingdee.eas.custom.entryconfig.DataConfigFactory;
import com.kingdee.eas.custom.entryconfig.DataConfigInfo;
import com.kingdee.eas.custom.entryconfig.DataConfigSelectFieldEntryCollection;
import com.kingdee.shr.base.syssetting.MSFServiceFacadeFactory;

import java.util.HashMap;
import java.util.Map;

public class GetCompleteSqlService implements IHRMsfService {
    @Override
    public Object process(Context context, Map map) throws EASBizException, BOSException {
        // 从输入参数中获取"number"键对应的值，该值为数据配置的编号
        Object o = map.get("number");

        Object t = map.get("top");
        // 检查number参数是否为空
        if (o == null) {
            // 若为空则抛出运行时异常，提示number参数不可为空
            throw new RuntimeException("number参数不能为空！");
        }
        // 将number参数转换为字符串类型
        String number = o.toString();
        // 实例化SQL工具类，用于处理SQL构建相关的工具方法
        SqlUtils sqlUtils = new SqlUtils();

        // 根据number编号查询对应的数据配置信息
        // 此处SQL查询条件为number字段等于输入的编号，查询数据配置主信息及关联的条目信息
        DataConfigInfo dataConfigInfo = DataConfigFactory.getLocalInstance(context)
                .getDataConfigInfo("select *,SelectFieldEntry.* where number  = '" + number + "' order by entrys.seq ");
        DataConfigSelectFieldEntryCollection selectFieldEntry = dataConfigInfo.getSelectFieldEntry();
        StringBuilder field = new StringBuilder();
        if (t!=null){
            field.append("top 1").append("\n");
        }
        StringBuilder selectField = sqlUtils.getSelectField(selectFieldEntry, field);

        Map<String,Object> getSqlServiceMap = new HashMap<String,Object>();
        getSqlServiceMap.put("number",number);
        Object o1 = MSFServiceFacadeFactory.getLocalInstance(context).processService("getSqlService", getSqlServiceMap);
        String sql = o1.toString();
        sql = sql.replace("{{filed}}",selectField.toString());
        return sql.toString();
    }
}
