<%
/*
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: 第一版发布

*/

//本页面采用EZDML模板语法（<%开头的脚本编译前会自动进行转换，类似JSP，脚本调试器里点编译能看到转换后的代码）
//生成的结果内容中也包含JS，所以要注意分清哪些代码是EZDML执行、哪些是浏览器执行的

//VUE ElementUI List and Sheet
//参考文档：https://element.eleme.cn/#/zh-CN
                  

#include "VueElementLib.js_"

//main函数主程序开始

var tb=curTable; //记录当前表和字段列表
if(!tb)
  Abort();
var fds=tb.metaFields;

//检查是否需要显示合计
var afCount=0;
var fdAggrMap={};
for(var k=0; k<fds.count; k++) 
{ //字段循环开始
  var fd = fds.getItem(k); //取第k个字段
  if(!fd.canDisplay('grid')) //判断字段可否在列表显示
    continue;
  if(fd.aggregateFun) //是否有合计
    afCount++;
  fdAggrMap[fd.name]=fd.aggregateFun;
}

//下面开始输出HTML
%>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <!-- import CSS -->
  <link rel="stylesheet" href="https://npm.elemecdn.com/element-ui@2.15.7/lib/theme-chalk/index.css">
  <style>
  .el-row {
    margin-bottom: 8px;
  }
  </style>
</head>
<body>
  <div id="app">
    <template>
      <el-row>
        <el-button type="primary" @click="handleOper(null, null, 'new')">新增</el-button>
        <el-button type="danger" @click="handleOper(null, null, 'batch_delete')">批量删除</el-button>
      </el-row>
      
      <el-table
        :data="itemList"
        border
        stripe
        @row-click="handleRowClick"
<%if(afCount>0){ /*合计*/%>
        :summary-method="getSummaries"
        show-summary
<%}%>
        style="width: 100%">
        <el-table-column
          type="selection"
          width="40">
        </el-table-column>
<%
  var filterMap={};
  //遍历所有字段
  for(var k=0; k<fds.count; k++) 
  { //字段循环开始
    var fd = fds.getItem(k); //取第k个字段
    if(!fd.canDisplay('grid')) //判断字段可否在列表显示
      continue;
    var W = fd.colWidth; //获取字段宽度
    if(W <= 10)
      W = 120;
    //下面输出字段
%>
        <el-table-column
          prop="${fd.name}"
          label="${fd.getLabelText()}"
          min-width="${W}"<% 
        if(fd.colSortable) { %>
          sortable<% }
        if(fd.showFilterBox) {
          //生成示例过滤内容
          filterMap[fd.name]=getDropdownItems(fd);
          %>
          :filters="colFilterMaps['${fd.name}']"
          :filter-method="filterHandler"
        <%} %> >
        </el-table-column>
<%
  } //字段循环结束
%>
        <el-table-column 
          label="操作"
          min-width="220">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleOper(scope.column, scope.row, 'view')">查看</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="handleOper(scope.column, scope.row, 'edit')">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleOper(scope.column, scope.row, 'delete')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      
      <el-dialog
        :title="sheetTitle"
        :visible.sync="sheetDialogVisible"
        :before-close="handleSheetClose"
        width="800px">
        <el-form
          :model="formData"
          label-width="80px">
<%
  //遍历所有字段
  for(var k=0; k<fds.count; k++) 
  { //字段循环开始
    var fd = fds.getItem(k); //取第k个字段
    if(!fd.canDisplay('sheet')) //判断字段可否在表单显示
      continue;
%>
          <el-form-item
            label="${fd.getLabelText()}"<%
    if (fd.isRequired())
    {
%>
            required<%
    }%> > <% 
    writeFieldFormItem(fd); //表单项比较复杂，改用脚本输出 
%>
          </el-form-item>
<%
  }
%>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="sheetDialogVisible = false">确 定</el-button>
          <el-button @click="sheetDialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>

    </template>
  </div>
</body>

<!-- import Vue before Element -->
<script src="https://npm.elemecdn.com/vue@2.6.14/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://npm.elemecdn.com/element-ui@2.15.7/lib/index.js"></script>

<script>
//标题
var elDataTitle='${tb.UIDisplayName}';

//输出过滤项
var elFilterMap=${JSON.stringify(filterMap,null,2)};
//输出统计栏配置
var elAggrMap=${JSON.stringify(fdAggrMap,null,2)};

<%
//准备示例数据列表
var rc=10; //输出10行
var ds=[];
for(var r=0; r<rc; r++){  
  var json=getDemoJson(tb,r,'[GRID]');
  ds.push(json);
}
var rmap=getDemoJson(tb,r,'[LABELTEXT]');
//下面输出列表和表单数据
%>
var elDataList=${JSON.stringify(ds,null,2)};

var elFormData=${JSON.stringify(rmap,null,2)};


var vueAppInfo= 
{
  el:'#app',
  components: {},
  props: [],
  data() {
    return {
      title: elDataTitle,
      itemList: elDataList,
      colFilterMaps: elFilterMap,
      sheetDialogVisible: false,
      formData: elFormData,
      sheetTitle: '表单'
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    filterHandler(value, row, column) {
        const property = column['property'];
        return row[property] === value;
    },
    handleRowClick(row, column){
      if(!column)
        return;
      if(column.label=='操作')
        return;
      this.handleOper(column, row, 'view');
    },
    handleOper(column, row, act) {
      if(act == 'delete' || act == 'batch_delete'){
        this.$confirm('确定要删除选中的记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'info',
            message: '操作执行完成!'
          });
        }).catch(() => {
        });
        return;
      }

      var tt=elDataTitle;
      if(act=='view')
        tt='查看 '+tt;
      else if(act=='new')
        tt='新增 '+tt;
      else if(act=='edit')
        tt='修改 '+tt;
      this.$data.sheetTitle=tt;

      var rec=elFormData;
      if(act=='new'){
        rec={};
        for(var idx in elFormData){
          rec[idx]='';
        }
      }
      this.$data.formData=rec;

      this.$data.sheetDialogVisible=true;
    },
    handleSheetClose(done){
      console.log('handleSheetClosed');
      this.$data.sheetDialogVisible=false;
    },
    
<%if(afCount>0){ /*合计开始*/%>
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        var afun=elAggrMap[column.property];
        if (!afun) {
          sums[index] = ' ';
          return;
        }
        var cfuns='count,sum,avg,max,min'.split(',');
        var bfun=afun.toLowerCase();
        if(bfun.indexOf("text:")==0){
          afun=afun.substr(5);
          var bFound=false;
          for(var idx in cfuns)
            if(bfun.indexOf('%'+cfuns[idx]+'%')>=0){
              afun=cfuns[idx];
              bfun=afun.toLowerCase();
              bFound=true;
              break;
            }
          if(!bFound){
            sums[index] = afun;
            return;
          }
        }

        if(bfun=='count'){
            sums[index] = data.length;
            return;
        }

        const values = data.map(item => Number(item[column.property]));
        if(bfun=='max'){
          sums[index]=values.reduce(function (x,y) {
            return x>y?x:y
          });
        } else if(bfun=='min'){
          sums[index]=values.reduce(function (x,y) {
            return x<y?x:y
          });
        } else {
          var res=values.reduce(function (x,y) {
            return x+y
          });
          if(bfun=='avg' && values.length>0)
            res=res/values.length;
          sums[index]=parseFloat(Number(res).toFixed(3));
        }
      });

      return sums;
    },
<%} /*合计结束*/%>
  }
};

var vueApp=new Vue(vueAppInfo);

</script>


</html>