package cn.ibizlab.api.rest.extensions;

import cn.ibizlab.core.dict.extensions.service.DictDstService;
import cn.ibizlab.core.extensions.dto.FetchParam;
import cn.ibizlab.core.extensions.dto.FetchResult;
import cn.ibizlab.core.extensions.dto.LookupResult;
import cn.ibizlab.core.extensions.service.BuildResultService;
import cn.ibizlab.core.lite.domain.DstSystem;
import cn.ibizlab.core.lite.domain.MetaEntity;
import cn.ibizlab.core.lite.domain.MetaField;
import cn.ibizlab.core.lite.extensions.domain.*;
import cn.ibizlab.core.lite.extensions.model.DataModel;
import cn.ibizlab.core.lite.extensions.model.Property;
import cn.ibizlab.core.lite.extensions.service.LiteCoreService;
import cn.ibizlab.core.lite.extensions.service.LiteDataService;
import cn.ibizlab.core.lite.extensions.service.LiteModelService;
import cn.ibizlab.core.lite.filter.MetaFieldSearchContext;
import cn.ibizlab.core.lite.service.IMetaEntityService;
import cn.ibizlab.core.lite.service.IMetaFieldService;
import cn.ibizlab.core.rule.domain.RuleItem;
import cn.ibizlab.core.rule.service.IRuleItemService;
import cn.ibizlab.util.annotation.RunLock;
import cn.ibizlab.util.dict.CodeItem;
import cn.ibizlab.util.dict.CodeList;
import cn.ibizlab.util.dict.Option;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.filter.QueryFilter;
import cn.ibizlab.util.helper.DataObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = {"接口" })
@RestController("api-litecore")
@RequestMapping("")
public class DstCoreResource
{

    @Autowired
    private LiteModelService liteModelService;

    @Autowired
    private LiteDataService liteDataService;

    @Autowired
    private IRuleItemService ruleItemService;



    @RequestMapping(method = RequestMethod.GET, value = {
            "/dst/lock/{rulecode}/{key}" })
    public ResponseEntity<Boolean> testLock(@PathVariable("rulecode") String rulecode,@PathVariable("key") String key)
    {
        System.out.println("start");
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end");
        return ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @RequestMapping(method = RequestMethod.GET, value = {
            "/dst/test/{rulecode}/{key}" })
    public ResponseEntity<Boolean> testRule(@PathVariable("rulecode") String rulecode,@PathVariable("key") String key)
    {
        RuleItem ruleItem=new RuleItem();
        ruleItem.setRuleCode(rulecode);
        ruleItem.set("debugkey",key);
        ruleItemService.testRule(ruleItem);
        return ResponseEntity.status(HttpStatus.OK).body(true);
    }



    @RequestMapping(method = RequestMethod.GET, value = {"/dst/datamodels/{modelid}/data/{key}","/lite/datamodels/{modelid}/data/{key}"})
    public ResponseEntity<ModelObj> getModelObj(@PathVariable(name="modelid",required = false) String modelid,@PathVariable(name="key",required = false) String key)
    {

        if(StringUtils.isEmpty(modelid))
            modelid="dataModelff8080816a8b510c016a8c2f18b10001";
        return ResponseEntity.ok(liteDataService.getModelObjs(modelid, null,key));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/datamodels/{modelid}","/dst/datamodels/{modelid}/name/{modelname}",
            "/lite/datamodels/{modelid}","/lite/datamodels/{modelid}/name/{modelname}"})
    public ResponseEntity<DataModel> getDataModel(@PathVariable(name="modelid",required = false) String modelid,
                                                  @PathVariable(name="modelname",required = false) String modelname)
    {
        return ResponseEntity.ok(liteModelService.getDataModel(modelid,modelname));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/datamodels/{modelid}/submodels","/dst/datamodels/{modelid}/name/{modelname}/submodels",
            "/lite/datamodels/{modelid}/submodels","/lite/datamodels/{modelid}/name/{modelname}/submodels"})
    public ResponseEntity<List<Option>> getDataModelSubModels(@PathVariable(name="modelid",required = false) String modelid,
                                                              @PathVariable(name="modelname",required = false) String modelname)
    {
        List<Option> list =  new ArrayList<>();
        liteModelService.getDataModel(modelid,modelname).getSubDataModel().forEach(dataModel -> list.add(new Option().setId(dataModel.getDataModelName()).setLabel(dataModel.getFactPorperty().getEntityModel().getLogicName()+"["+dataModel.getDataModelName()+"]")));
        return ResponseEntity.ok(list);
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/datamodels/{modelid}/allmodels","/lite/datamodels/{modelid}/allmodels"})
    public ResponseEntity<List<Option>> getDataModelAllModels(@PathVariable(name="modelid",required = false) String modelid)
    {
        List<Option> list =  new ArrayList<>();
        DataModel rootModel=liteModelService.getDataModel(modelid);
        list.add(new Option().setId(rootModel.getDataModelName()).setLabel(rootModel.getFactPorperty().getEntityModel().getLogicName()+"["+rootModel.getDataModelName()+"]"));
        rootModel.getSubDataModel().forEach(dataModel -> list.add(new Option().setId(dataModel.getDataModelName()).setLabel(dataModel.getFactPorperty().getEntityModel().getLogicName()+"["+dataModel.getDataModelName()+"]")));
        return ResponseEntity.ok(list);
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/datamodels/{modelid}/propertys","/dst/datamodels/{modelid}/name/{modelname}/propertys",
            "/lite/datamodels/{modelid}/propertys","/lite/datamodels/{modelid}/name/{modelname}/propertys"})
    public ResponseEntity<List<Option>> getDataModelParentProperty(@PathVariable(name="modelid",required = false) String modelid,
                                                              @PathVariable(name="modelname",required = false) String modelname)
    {
        List<Option> list =  new ArrayList<>();
        liteModelService.getDataModel(modelid,modelname).getParentProperty().forEach(property -> {
            Option option = new Option().setId(property.getPropertyName()).setLabel(property.getEntityModel().getLogicName()+"["+property.getPropertyName()+"]");
            list.add(option);
        });
        return ResponseEntity.ok(list);
    }



    @RequestMapping(method = RequestMethod.GET, value = {"/dst/datamodels/{modelid}/propertys/{propertyname}/fields","/dst/datamodels/{modelid}/name/{modelname}/propertys/{propertyname}/fields",
            "/lite/datamodels/{modelid}/propertys/{propertyname}/fields","/lite/datamodels/{modelid}/name/{modelname}/propertys/{propertyname}/fields"})
    public ResponseEntity<List<Option>> getDataModelParentField(@PathVariable(name="modelid",required = false) String modelid,
                                                                   @PathVariable(name="modelname",required = false) String modelname,
                                                                @PathVariable(name="propertyname",required = false) String propertyname)
    {
        List<Option> list =  new ArrayList<>();
        Property property=liteModelService.getDataModel(modelid,modelname).findObjectProperty(propertyname,"UP");
        property.getEntityModel().getFields().forEach(field -> {
            Option option = new Option().setId(property.getPropertyName()+"."+field.getColumnName()).setLabel(field.getComment()+"["+field.getColumnName()+"]");
            list.add(option);
        });
        return ResponseEntity.ok(list);
    }


    @RequestMapping(method = RequestMethod.GET, value = {"/dst/datamodels/{modelid}/allpropertys"})
    public ResponseEntity<List<Option>> getDataModelParentProperty(@PathVariable(name="modelid",required = false) String modelid)
    {
        List<Option> list =  new ArrayList<>();
        liteModelService.getDataModel(modelid).getAllProperty().forEach(property -> {
            Option option = new Option().setId(property.getPropertyName()).setLabel(property.getEntityModel().getLogicName()+"["+property.getPropertyName()+"]");
            list.add(option);
        });
        return ResponseEntity.ok(list);
    }
    @RequestMapping(method = RequestMethod.GET, value = {"/dst/datamodels/{modelid}/allpropertys/{propertyname}/fields","/lite/datamodels/{modelid}/allpropertys/{propertyname}/fields"})
    public ResponseEntity<List<Option>> getDataModelField(@PathVariable(name="modelid",required = false) String modelid,
                                                                @PathVariable(name="propertyname",required = false) String propertyname,
                                                                @PathVariable(name="fieldname",required = false) String fieldname)
    {
        List<Option> list =  new ArrayList<>();
        Property property=liteModelService.getDataModel(modelid).findObjectProperty(propertyname,"ALL");
        property.getEntityModel().getFields().forEach(field -> {
            Option option = new Option().setId(property.getPropertyName()+"."+field.getColumnName()).setLabel(field.getComment()+"["+field.getColumnName()+"]");
            list.add(option);
        });
        return ResponseEntity.ok(list);
    }

    @Autowired
    private DictDstService dictDstService;

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/datamodels/{modelid}/{propertyname}.{fieldname}/dict","/lite/datamodels/{modelid}/{propertyname}.{fieldname}/dict"})
    public ResponseEntity<List<CodeItem>> getDataModelFieldDict(@PathVariable(name="modelid",required = false) String modelid,
                                                                @PathVariable(name="propertyname",required = false) String propertyname,
                                                                @PathVariable(name="fieldname",required = false) String fieldname)
    {
        List<CodeItem> list =  new ArrayList<>();
        Property property=liteModelService.getDataModel(modelid).findObjectProperty(propertyname,"ALL");
        if(property!=null)
        {
            MetaFieldModel field=property.getEntityModel().getField(fieldname).getField();
            if(field!=null)
            {
                String dict = field.getDict();
                if(!StringUtils.isEmpty(dict))
                {
                    CodeList codeList= dictDstService.getCodeListCatalog(dict);
                    if(codeList!=null)
                        list=codeList.getOptions();

                }
            }

        }

        return ResponseEntity.ok(list);
    }

    @Autowired
    IMetaEntityService metaEntityService;


    @Autowired
    @Lazy
    private IMetaFieldService fieldService;

    @RequestMapping(method = RequestMethod.GET, value = {
            "/dst/{system}/entities","/lite/{system}/entities",
            "/dst/{system}/entitys","/lite/{system}/entitys"})
    public ResponseEntity<List<EntityModel>> getEntityModel(@PathVariable("system") String system) {
        return ResponseEntity.status(HttpStatus.OK).body(liteModelService.getEntityModel(system));
    }

    @RequestMapping(method = RequestMethod.GET, value = {
            "/dst/{system}/metaentities","/lite/{system}/metaentities",
            "/dst/{system}/metaentitys","/lite/{system}/metaentitys"})
    public ResponseEntity<List<MetaEntity>> getMetaEntities(@PathVariable("system") String system) {
        return ResponseEntity.status(HttpStatus.OK).body(metaEntityService.list(Wrappers.<MetaEntity>lambdaQuery().eq(MetaEntity::getSystemId,system)));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/{system}/metafields","/lite/{system}/metafields"})
    public ResponseEntity<List<MetaField>> getFields(@PathVariable("system") String system) {
        MetaFieldSearchContext context=new MetaFieldSearchContext();
        context.setSize(Integer.MAX_VALUE);
        context.setN_systemid_eq(system);
        return ResponseEntity.status(HttpStatus.OK).body(fieldService.searchDefault(context).getContent());
    }

    @RequestMapping(method = RequestMethod.GET, value = {
            "/dst/{system}/entities/{entity}","/lite/{system}/entities/{entity}",
            "/dst/{system}/entitys/{entity}","/lite/{system}/entitys/{entity}"})
    public ResponseEntity<EntityModel> getEntityModel(@PathVariable("system") String system, @PathVariable("entity") String entity) {
        return ResponseEntity.status(HttpStatus.OK).body(liteModelService.getEntityModel(system,entity));
    }

    @RequestMapping(method = RequestMethod.GET, value = {
            "/dst/{system}/entities/{entity}/fields","/lite/{system}/entities/{entity}/fields",
            "/dst/{system}/entitys/{entity}/fields","/lite/{system}/entitys/{entity}/fields"})
    public ResponseEntity<List<FieldModel>> getEntityModelFields(@PathVariable("system") String system, @PathVariable("entity") String entity) {
        return ResponseEntity.status(HttpStatus.OK).body(liteModelService.getEntityModel(system,entity).getFields());
    }

    @RequestMapping(method = RequestMethod.GET, value = {
            "/dst/{system}/entities/{entity}/references","/lite/{system}/entities/{entity}/references",
            "/dst/{system}/entitys/{entity}/references","/lite/{system}/entitys/{entity}/references"})
    public ResponseEntity<List<RelationshipModel>> getEntityModelReferences(@PathVariable("system") String system, @PathVariable("entity") String entity) {
        return ResponseEntity.status(HttpStatus.OK).body(liteModelService.getEntityModel(system,entity).getReferences());
    }

    @RequestMapping(method = RequestMethod.GET, value = {
            "/dst/{system}/entities/{entity}/nesteds","/lite/{system}/entities/{entity}/nesteds",
            "/dst/{system}/entitys/{entity}/nesteds","/lite/{system}/entitys/{entity}/nesteds"})
    public ResponseEntity<List<RelationshipModel>> getEntityModelNesteds(@PathVariable("system") String system, @PathVariable("entity") String entity) {
        return ResponseEntity.status(HttpStatus.OK).body(liteModelService.getEntityModel(system,entity).getNesteds());
    }

    @RequestMapping(method = {RequestMethod.POST,RequestMethod.GET}, value = {
            "/dst/{system}/entities/{entity}/get","/lite/{system}/entities/{entity}/get",
            "/dst/{system}/entitys/{entity}/get","/lite/{system}/entitys/{entity}/get"})
    public ResponseEntity<EntityObj> getEntity(@PathVariable("system") String system, @PathVariable("entity") String entity, HttpServletRequest request,@RequestBody(required = false) Map map) {
        Map<String, String[]> params = request.getParameterMap();
        EntityObj entityObj = new EntityObj();
        if(map!=null)
            entityObj.putAll(map);
        for (String key : params.keySet()) {
            entityObj.set(key.toUpperCase(),params.get(key)[0]);
        }
        return ResponseEntity.status(HttpStatus.OK).body(liteDataService.get(system,entity,entityObj.getStringValue("link"),entityObj));
    }

    @RequestMapping(method = RequestMethod.POST, value = {
            "/dst/{system}/entities/{entity}/search{dataset}","/lite/{system}/entities/{entity}/search{dataset}",
            "/dst/{system}/entitys/{entity}/search{dataset}","/lite/{system}/entitys/{entity}/search{dataset}"})
    public ResponseEntity<List<EntityObj>> searchEntity(@PathVariable("system") String system, @PathVariable("entity") String entity, @PathVariable(value = "dataset",required = false) String dataset,@RequestParam(value = "link",required = false) String link,@RequestBody QueryFilter filter) {
        if(StringUtils.isEmpty(dataset))
            dataset="BASE";
        return ResponseEntity.status(HttpStatus.OK).body(liteDataService.search(system,entity,link,filter));
    }

    @RequestMapping(method = RequestMethod.POST, value = {
            "/dst/{system}/entities/{entity}/save","/lite/{system}/entities/{entity}/save",
            "/dst/{system}/entitys/{entity}/save","/lite/{system}/entitys/{entity}/save"})
    public ResponseEntity<Boolean> saveEntity(@PathVariable("system") String system, @PathVariable("entity") String entity,@RequestParam(value = "link",required = false) String link,@RequestBody EntityObj entityObj) {
        return ResponseEntity.status(HttpStatus.OK).body(liteDataService.save(system,entity,link,entityObj));
    }

    @RequestMapping(method = RequestMethod.POST, value = {
            "/dst/{system}/entities/{entity}/batch","/lite/{system}/entities/{entity}/batch",
            "/dst/{system}/entitys/{entity}/batch","/lite/{system}/entitys/{entity}/batch"})
    public ResponseEntity<Boolean> saveEntity(@PathVariable("system") String system, @PathVariable("entity") String entity,@RequestBody List<EntityObj> list, @RequestParam(value = "link",required = false) String link) {
        return ResponseEntity.status(HttpStatus.OK).body(liteDataService.saveBatch(system,entity,link,list));
    }

    @Autowired
    private LiteCoreService liteCoreService;

    @ApiOperation(value = "保存系统", tags = {"系统" },  notes = "保存系统")
    @RequestMapping(method = RequestMethod.POST, value = {"/dst/syncsysmodel","/lite/syncsysmodel"})
    public ResponseEntity<Boolean> syncSysModel(@RequestBody SysModel sysModel) {
        return ResponseEntity.status(HttpStatus.OK).body(liteCoreService.syncSysModel(sysModel));
    }


    @RequestMapping(method = RequestMethod.GET, value = {"/dst/sysapps","/lite/sysapps"})
    public ResponseEntity<List<DstSystem>> getSysApps() {
        return ResponseEntity.status(HttpStatus.OK).body(liteModelService.getSysApp());
    }


    @Autowired
    private BuildResultService buildResultService;

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/report/{reportId}/{dimValue}/config","/dst/report/{reportId}/config",
            "/lite/report/{reportId}/{dimValue}/config","/lite/report/{reportId}/config"})
    public ResponseEntity<FetchResult> getReportViews(@PathVariable(name = "reportId") String reportId, @PathVariable(name = "dimValue",required = false) String dimValue,
                                                      @RequestParam(name = "startTime",required = false) String startTime,
                                                      @RequestParam(name = "endTime",required = false) String endTime) {
        FetchParam param=new FetchParam().setReportId(reportId).setDimValue(dimValue).setStartTime(DataObject.getTimestampValue(startTime,null)).setEndTime(DataObject.getTimestampValue(endTime,null));
        return ResponseEntity.ok(buildResultService.getReportConfig(param));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/report/{reportId}/{dimValue}","/dst/report/{reportId}",
            "/lite/report/{reportId}/{dimValue}","/lite/report/{reportId}"})
    public ResponseEntity<FetchResult> getReportdatas(@PathVariable(name = "reportId") String reportId, @PathVariable(name = "dimValue",required = false) String dimValue,
                                                      @RequestParam(name = "startTime",required = false) String startTime,
                                                      @RequestParam(name = "endTime",required = false) String endTime) {
        FetchParam param=new FetchParam().setReportId(reportId).setDimValue(dimValue).setStartTime(DataObject.getTimestampValue(startTime,null)).setEndTime(DataObject.getTimestampValue(endTime,null));
        return ResponseEntity.ok(buildResultService.getAnalyseResult(param));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/dst/report","/dst/report","/lite/report","/lite/report"})
    public ResponseEntity<FetchResult> fetchReportdatas(@RequestBody FetchParam param) {
        return ResponseEntity.ok(buildResultService.getAnalyseResult(param));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/lookup/{metricId}/{dimValue}",
            "/lite/lookup/{metricId}/{dimValue}"})
    public ResponseEntity<LookupResult> lookup(@PathVariable(name = "metricId") String metricId, @PathVariable(name = "dimValue") String dimValue,
                                               @RequestParam(name = "startTime",required = false) String startTime,
                                               @RequestParam(name = "endTime",required = false) String endTime,
                                               @RequestParam(name = "page",required = false) Integer page,
                                               @RequestParam(name = "size",required = false) Integer size,
                                               @RequestParam(name = "total",required = false) Integer total) {

        FetchParam param=new FetchParam().setMetricId(metricId).setDimValue(dimValue)
                .setStartTime(DataObject.getTimestampValue(startTime,null)).setEndTime(DataObject.getTimestampValue(endTime,null));
        if(page!=null)
            param.setPage(page);
        if(size!=null)
            param.setSize(size);
        if(total!=null)
            param.setTotal(total);
        return ResponseEntity.ok(buildResultService.lookup(param));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/dst/lookup","/lite/lookup"})
    public ResponseEntity<LookupResult> lookup(@RequestBody FetchParam param) {
        return ResponseEntity.ok(buildResultService.lookup(param));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/dst/report/{reportId}/{dimValue}.xls","/dst/report/{reportId}.xls",
            "/lite/report/{reportId}/{dimValue}.xls","/lite/report/{reportId}.xls"})
    public void exportReportdatas(@PathVariable(name = "reportId") String reportId, @PathVariable(name = "dimValue",required = false) String dimValue,
                                  @RequestParam(name = "startTime",required = false) String startTime,
                                  @RequestParam(name = "endTime",required = false) String endTime, HttpServletResponse response) {
        FetchParam param=new FetchParam().setReportId(reportId).setDimValue(dimValue).setStartTime(DataObject.getTimestampValue(startTime,null)).setEndTime(DataObject.getTimestampValue(endTime,null));
        File file = buildResultService.exportExcel(param);
        if(file==null)
            throw new BadRequestAlertException("导出报表失败","Report",reportId);
        try {
            response.setHeader("Content-Disposition", "attachment;filename="+new String(file.getName().getBytes("utf-8"),"iso8859-1"));//防止中文乱码
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        }
        catch (Exception e) {
            //throw e;
        }
        finally {
            if (bis != null) {
                try {
                    bis.close();
                }
                catch (IOException e) {

                }
            }
            if (bos != null) {
                try {
                    bos.close();
                }
                catch (IOException e) {

                }
            }
        }
    }



    @RequestMapping(method = RequestMethod.GET, value = "/lite/{system}/{from}.ibzbak")
    public ResponseEntity<JSONObject> ibzbak(@PathVariable(name="system",required = true) String system, @PathVariable(name="from",required = true) String from)
    {
        MetaFieldSearchContext context=new MetaFieldSearchContext();
        context.setSize(Integer.MAX_VALUE);
        context.setN_systemid_eq(system);
        context.getSearchCond().ge("updatedate", DataObject.getTimestampValue(from, null));
        JSONArray jArray = new JSONArray();
        fieldService.searchDefault(context).getContent().forEach(sx->{
            JSONObject json = new JSONObject();
            JSONObject jo = new JSONObject();

            jo.put("psdefieldname", sx.getFieldName());
            jo.put("predefinetype", sx.getPredefined());
            jo.put("unionkeyvalue", sx.getUnionKey());
            jo.put("codename", sx.getCodeName());

            jo.put("physicalfield", sx.getPhysicalField());
            jo.put("psdeid", DigestUtils.md5DigestAsHex(("2C40DFCD-0DF5-47BF-91A5-C45F810B0001||"+sx.getEntityName()).getBytes()).toLowerCase());
            jo.put("logicname", sx.getFieldLogicName());
            if (sx.getDataLength() != null && sx.getDataLength() > 0)
                jo.put("length", sx.getDataLength());
            if (sx.getDataPreci() != null && sx.getDataPreci() > 0)
                jo.put("precision2", sx.getDataPreci());
            jo.put("ordervalue", sx.getShowOrder());
            jo.put("psdefieldid", DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(("2C40DFCD-0DF5-47BF-91A5-C45F810B0001||"+sx.getEntityName()).getBytes()).toLowerCase()+"||"+sx.getFieldName()).getBytes()).toLowerCase());
            if(1==sx.getPhysicalField()&&(StringUtils.isEmpty(sx.getExpression())))
                jo.put("deftype", 1);
            else {
                jo.put("deftype", 2);
                jo.put("formulaformat",sx.getExpression());
            }
            jo.put("pkey", sx.getKeyField());
            jo.put("pssystemid", "2C40DFCD-0DF5-47BF-91A5-C45F810B0001");
            jo.put("psdename", sx.getEntityName());
            jo.put("tablename", sx.getEntityName());

            String strRT = "文本，可指定长度";
            String strDataTypeId=sx.getFieldType();
            jo.put("psdatatypeid", strDataTypeId);
            if (strDataTypeId.equalsIgnoreCase("DECIMAL"))
                strRT = "数值";
            else if (strDataTypeId.equalsIgnoreCase("INT"))
                strRT = "整型";
            else if (strDataTypeId.equalsIgnoreCase("BIGDECIMAL"))
                strRT = "大数值";
            else if (strDataTypeId.equalsIgnoreCase("BIGINT"))
                strRT = "大整型";
            else if (strDataTypeId.equalsIgnoreCase("LONGTEXT"))
                strRT = "长文本，没有长度限制";
            else if (strDataTypeId.equalsIgnoreCase("LONGTEXT_1000"))
                strRT = "长文本，长度1000";
            else if (strDataTypeId.equalsIgnoreCase("DATE"))
                strRT = "日期型";
            else if (strDataTypeId.equalsIgnoreCase("DATETIME"))
                strRT = "日期时间型";

            jo.put("psdatatypename", strRT);
            jo.put("allowempty", sx.getNullable());
            json.put("srfvalue", jo);
            json.put("srfdeid", "42d91505b9bb15b9900b4298fcca9915");
            json.put("srfdename", "PSDEFIELD");
            jArray.add(json);
        });
        JSONObject jo = new JSONObject();
        jo.put("items", jArray);

        return ResponseEntity.ok(jo);
    }


}
