<%
(*
Note: The contents of this file will be directly overwritten when EZDML is upgraded. Instead of modifying this file directly, copy the file to a new name and modify the new file.

注意：程序升级时会直接覆盖此文件内容，请不要直接修改此文件，如果需要请将此文件复制到新名称，然后对新文件进行修改。

2021-12-25: 第一版发布

*)

//参考：https://baidu.gitee.io/amis/zh-CN/components/page

const sFieldEditorTypes=
    'TextEdit=input-text' + #13#10 +
    'Memo=textarea' + #13#10 +
    'RichText=input-rich-text' + #13#10 +
    'Password=input-password' + #13#10 +    
    'GUID=input-text' + #13#10 +
    'ButtonEdit=picker' + #13#10 +
    'ComboBox=select' + #13#10 +
    'ListSelect=list-select' + #13#10 +
    'TagEdit=input-tag' + #13#10 +
    'RadioBox=radios' + #13#10 +
    'ButtonGroup=button-group-select' + #13#10 +
    'CheckBox=checkbox' + #13#10 +
    'Switch=switch' + #13#10 +
    'SpinEdit=input-number' + #13#10 +
    'NumberEdit=input-number' + #13#10 +
    'CalcEdit=input-number' + #13#10 +
    'TrackBar=input-range' + #13#10 +
    'ScoreRate=input-rating' + #13#10 +
    'CurrencyEdit=input-text' + #13#10 +
    'DateEdit=input-date' + #13#10 +
    'DateRange=input-date-range' + #13#10 +
    'TimeEdit=input-time' + #13#10 +
    'DateTime=input-datetime' + #13#10 +
    'WeekSelect=input-date' + #13#10 +
    'MonthSelect=input-month' + #13#10 +
    'QuarterSelect=input-quarter' + #13#10 +
    'YearSelect=input-year' + #13#10 +
    'ColorSelect=input-color' + #13#10 +
    'DataGrid=input-table' + #13#10 +
    'KeyValueList=input-table' + #13#10 +
    'FileNameEdit=input-text' + #13#10 +
    'ImageFile=input-image' + #13#10 +
    'UploadFile=input-file' + #13#10 +
    'LocationMap=location-picker' + #13#10 +
    'Button=button' + #13#10 +
    'HyperLink=link' + #13#10 +
    'Picture=image' + #13#10 +
    'BarCode=input-text' + #13#10 +   
    'QRCode=qr-code' + #13#10 +
    'Chart=chart';  
    
function GetFieldEditorType(fd: TCtMetaField): string;
begin
  Result:='input-text';
  if fd<>nil then
  begin
    Result := GetCtDropDownTextOfValue(fd.PossibleEditorType,sFieldEditorTypes);
    if Result='' then
      Result:='input-text';
    if Result='checkbox' then
      if Trim(fd.DropDownItems)<>'' then
        Result := 'checkboxes';
  end;
end;

function GetSheedEditorDropDownItems(fd: TCtMetaField): string;
var
  s,t,v: string;
  I,po: Integer;
  ss:TStringList;
begin
  Result:='';
  if fd=nil then
    Exit;
  t:=LowerCase(fd.PossibleEditorType);

  if Pos(','+t+',', LowerCase(',ComboBox,ListSelect,TagEdit,RadioBox,ButtonGroup,CheckBox,'))=0 then
    Exit;

  if t='checkbox' then
    if Trim(fd.DropDownItems)='' then
      Exit;
  S:= fd.GetDemoItemList(False);
  if S='' then
    Exit;

  ss:=TStringList.Create;
  try
    ss.Text := S;
    for I:=0 to ss.Count-1 do
    begin
      S := ss[I];
      po:=Pos('=',S);
      if po>0 then
      begin
        V:=Copy(S,1,po-1);
        T:=Copy(S,po+1,Length(S));
      end
      else
      begin
        T:=S;
        V:=S;
      end;
      Result:=Result+'{"label": "'+T+'","value": "'+V+'"},'#13#10;
    end;
  finally
    ss.Free;
  end;

  Result:= '['+Result+']';
end;

function GetFieldFooterAgg(fd: TCtMetaField; var tp: string): string;
var
  ss:TStringList;
  I: Integer;
  bText: Boolean;
  T: String;
begin
  Result := Trim(fd.AggregateFun);
  bText := False;
  if LowerCase(Copy(Result,1,5))='text:' then
  begin
    Result:=Copy(Result,6,Length(Result));
    bText := True;
  end;
  
  ss:=TStringList.Create;
  try
    ss.CommaText := 'Count,StdDev,Sum,Avg,Max,Min';
    for I:=0 to ss.Count-1 do
    begin
      T := ss[I];
      if bText then
        T:='%'+T+'%';
      if Pos(LowerCase(T), LowerCase(Result))>0 then
      begin
        Result:='$'+'{items|pick:'+fd.Name+'|'+LowerCase(ss[I])+'}';
        tp:='tpl';
        Exit;
      end;
    end;
  finally
    ss.Free;
  end;
end;

function GetFieldInputTableCols(fd: TCtMetaField): string;
var
  V, S: string;
  I: Integer;
  ts: TStringList;
begin
  Result := '';
  V := '';
  if (fd.DataType=cfdtObject) and (fd.RelateTable <> '') then
  begin
    V := fd.getRelateTableDemoJson(0, '[LABELTEXT][NAMESONLY]');
    if V='' then
      Exit;
    Result := '['#13#10;
    Result := Result +'{"type": "text","name": "key","label": "属性"},'#13#10;
    Result := Result +'{"type": "text","name": "value","label": "值"},'#13#10;
    Result := Result +']';
  end
  else if (fd.DataType=cfdtList) and (fd.RelateTable <> '') then
  begin
    V := fd.getRelateTableDemoJson(0, '[LABELTEXT][NAMESONLY]');
    if V='' then
      Exit;
    ts:=TStringList.Create;
    try
      ts.CommaText := V;
      Result := '['#13#10;
      for I:=0 to ts.Count-1 do
      begin
        S := ts[I];
        Result := Result +'{"type": "text","name": "'+S+'","label": "'+S+'"},'#13#10;
      end;
      Result := Result +']';
    finally
      ts.Free;
    end;
  end;
end;

var
  amisDir, tbN, S, T, V, edt: String;
  F: TCTMetaField;
  I, Y, C, totalRows, qfCount, afCount: Integer;
begin
  amisDir := 'https://npm.elemecdn.com/amis@1.5.3/';
  tbN:=CurTable.UIDisplayName;
  totalRows := 10;

  qfCount := 0;
  afCount := 0;
  for I:=0 to CurTable.MetaFields.Count-1 do
  begin
    F:=CurTable.MetaFields.Items[I];
    if F.Queryable then
      Inc(qfCount);
    if  F.CanDisplay('grid') and (Trim(F.AggregateFun) <> '') then
      Inc(afCount);
  end;
%>

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <title>${tbN}列表</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta
    name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1"
  />
  <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
  <link rel="stylesheet" href="${amisDir}sdk/sdk.css" />
  <link rel="stylesheet" href="${amisDir}sdk/helper.css" />
  <link rel="stylesheet" href="${amisDir}sdk/iconfont.css" />
  <!-- 这是默认主题所需的，如果是其他主题则不需要 -->
  <!-- 从 1.1.0 开始 sdk.css 将不支持 IE 11，如果要支持 IE11 请引用这个 css，并把前面那个删了 -->
  <!-- <link rel="stylesheet" href="${amisDir}sdk/sdk-ie11.css" /> -->
  <!-- 不过 amis 开发团队几乎没测试过 IE 11 下的效果，所以可能有细节功能用不了，如果发现请报 issue -->
  <style>
    html,
    body,
    .app-wrapper {
      position: relative;
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>
  <div id="root" class="app-wrapper"></div>
  <script src="${amisDir}sdk/sdk.js"></script>
<script type="text/javascript">
(function () {
let amis = amisRequire('amis/embed');
//
let amisDataList=[
<%
  for Y:=0 to totalRows-1 do
  begin
%>
      {<%
    for I:=0 to CurTable.MetaFields.Count-1 do
    begin
      F:=CurTable.MetaFields.Items[I];
      if not F.CanDisplay('grid') and (F.KeyFieldType <> cfktId) then
        Continue;
      V := F.GenDemoData(Y, '', nil);
%>
        "${F.Name}": "${V}",<%
    end; 
%>
        "_rowNo": "${Y}"
      },
<%
  end;
%>
     ];

     
let amisDataMap=
      {<%
    for I:=0 to CurTable.MetaFields.Count-1 do
    begin
      F:=CurTable.MetaFields.Items[I];
      if not F.CanDisplay('sheet') and (F.KeyFieldType <> cfktId) then
        Continue;
      V := F.GenDemoData(0, '', nil);
      if (F.DataType=cfdtObject) and (F.RelateTable <> '') then
      begin
        V := #13#10+F.getRelateTableDemoJson(CurTable.Id, '[LABELTEXT][KEYVALUELIST]');
      end
      else if (F.DataType=cfdtList) and (F.RelateTable <> '') then
      begin
        V:=#13#10'['#13#10;
        V:=V+ F.getRelateTableDemoJson(CurTable.Id, '[LABELTEXT]')+','#13#10;
        V:=V+ F.getRelateTableDemoJson(CurTable.Id+1, '[LABELTEXT]')+','#13#10;
        V:=V+ F.getRelateTableDemoJson(CurTable.Id+2, '[LABELTEXT]')+','#13#10;
        V:=V+ F.getRelateTableDemoJson(CurTable.Id+3, '[LABELTEXT]')+','#13#10;
        V:=V+ F.getRelateTableDemoJson(CurTable.Id+4, '[LABELTEXT]')+#13#10']';
      end
      else
        V:='"'+V+'"';
%>
        "${F.Name}": ${V},<%
    end; 
%>
      };

// 表单配置
let amisSheetJSON = 
{
  "title": "${tbN}详情",
  "remark": "amis表单",
  "size": "md",
  "body": {
    "type": "form",
    "mode": "horizontal",
    "body": [
    
<%
  for I:=0 to CurTable.MetaFields.Count-1 do
  begin
    F:=CurTable.MetaFields.Items[I];
    if not F.CanDisplay('sheet') then
      Continue;
    edt := GetFieldEditorType(F);
%>
        {
          "type": "${edt}",
          "name": "${F.Name}",
          "label": "${F.GetLabelText}",<%
    if F.Hint <> '' then
    begin %>
          "placeholder": "${F.Hint}",<%
    end;
    if F.ExplainText <> '' then
    begin %>
          "description": "${F.ExplainText}",<%
    end;
    if edt='input-table' then
    begin
      T := GetFieldInputTableCols(F);
      if T <> '' then
      begin   %>
          "columns": ${T},<%
      end;
    end
    else
    begin
      T:=GetSheedEditorDropDownItems(F);
      if T <> '' then
      begin %>
          "options": ${T},<%
      end;
      if F.IsRequired then
      begin
    %>
          "required": true,<%
      end;
    end;
    %>
        },
<%
  end; 
%>
    ],

    "actions": [
      {
        "type": "submit",
        "primary": true,
        "label": "提交"
      },
      {
        "type": "action",
        "label": "取消"
      }
    ],

  }
}
;
function getSheetDialgConfig(tp){
  var s=JSON.stringify(amisSheetJSON);
  var res=JSON.parse(s);
  if(tp!='new')
    res.body.data=amisDataMap;
  return res;
}

// 列表配置
let amisListJSON = 
{
  "title": "${tbN}列表",
  "remark": "amis增删改查",
  "toolbar": [
    {
      "type": "button",
      "label": "新增",
      "icon": "fa fa-plus pull-left",
      "primary": true,
      "actionType": "dialog",
      "dialog": getSheetDialgConfig('new')
    }
  ],
  "body": {
    "type": "crud",
    "draggable": true,
    "autoGenerateFilter": true,
    "perPage": 15,
    "filter": {
      "title": "搜索",
      "body": [
<%
  C := 0;
  for I:=0 to CurTable.MetaFields.Count-1 do
  begin
    F:=CurTable.MetaFields.Items[I];
    if qfCount > 0 then
    begin
      if not F.Queryable then
        Continue;
    end
    else
    begin
      if C >=8 then
        Break;
      if not F.CanDisplay('grid') then
        Continue;
    end;
    Inc(C);
%>
        {
          "type": "input-text",
          "name": "${F.Name}",
          "label": "${F.GetLabelText}",<%
    if F.Hint <> '' then
    begin %>
          "placeholder": "${F.Hint}",<%
    end;
    %>
        },
<%
  end; 
%>
      ]
    },
    "filterDefaultVisible": false, 
    "filterTogglable": true,
    "headerToolbar": [
      "filter-toggler",
      "export-csv",
      "export-excel",
      {
        "type": "tpl",
        "tpl": "当前有 ${totalRows} 条数据。",
        "className": "v-middle"
      },
      {
        "type": "columns-toggler",
        "align": "right"
      },
      {
        "type": "drag-toggler",
        "align": "right"
      },
      {
        "type": "pagination",
        "align": "right"
      }
    ],
    "footerToolbar": [
      "statistics",
      "switch-per-page",
      "pagination"
    ],
    "columns": [

<%
  for I:=0 to CurTable.MetaFields.Count-1 do
  begin
    F:=CurTable.MetaFields.Items[I];
    if not F.CanDisplay('grid') then
      Continue;
%>
      {
        "name": "${F.Name}",
        "label": "${F.GetLabelText}",
        "width": <% if F.ColWidth> 10 then PrintVar(F.ColWidth) else PrintVar(120); %>, <%
  if F.ShowFilterBox then
  begin
  %>
        "filterable": true,<%
  end
  else if F.ColSortable then
  begin %>
        "sortable": true,<% 
  end; 
  if F.ExplainText <> '' then
  begin
  %>
        "remark": "${F.ExplainText}",<%
  end;
  %>
        "type": "text"
      },
<%
  end; 
%>

      {
        "type": "operation",
        "label": "操作",
        "width": 100,
        "buttons": [
          {
            "type": "button",
            "icon": "fa fa-eye",
            "tooltip": "查看",
            "actionType": "dialog",
            "dialog": getSheetDialgConfig('view')
          },
          {
            "type": "button",
            "icon": "fa fa-pencil",
            "tooltip": "编辑",
            "actionType": "dialog",
            "dialog": getSheetDialgConfig('modify')
          },
          {
            "type": "button",
            "icon": "fa fa-times text-danger",
            "actionType": "ajax",
            "tooltip": "删除",
            "confirmText": "您确认要删除?"
          }
        ],
        "toggled": true
      }
    ],
    "itemAction": {
      "type": "button",
      "actionType": "dialog",
      "dialog": getSheetDialgConfig('view')
    },

<%
if afCount > 0 then
begin
%>
    "affixRow": [

<%
  for I:=0 to CurTable.MetaFields.Count-1 do
  begin
    F:=CurTable.MetaFields.Items[I];
    if not F.CanDisplay('grid') then
      Continue;
    T := 'text';
    S := GetFieldFooterAgg(F, T);
%>
      {
        "type": "${T}",
        "${T}": "${S}"
      },
<%
  end;
%>
    ],
<%
end;
%>
    "data": {
    "items": amisDataList,
     "count": 201,
     "hasNext": true 
    }


  }
}
;

let amisScoped = amis.embed('#root', amisListJSON);
})();
</script>
</body>
</html>

<%
end.
%>
