var tmpl=`

    <div style="display:flex;">
      <div name="grdid" style="width:99%;">
        <gsb-searchform style="border:1px solid #eee;" ref="searchForm" @onquery="queryClick"  :metaData="searchMetaData"></gsb-searchform>
        <el-card style="margin-top:15px;">
          <el-row>
            <el-col span="14">
                  <gsb-button-group style="margin-top:5px;" @select="onToolbarClick" :ikey="focuskey" :btns="toolbar"></gsb-button-group>
            </el-col>
            <el-col span="10" style="text-align:center;margin-bottom: 20px;">
                  <span v-for="sf  in sum_fields" style="padding:30px;padding-bottom:15px">
                    <el-badge :value="sumdata[sf.field]">
                      <el-button size="mini">{{ sf.label }}</el-button>
                    </el-badge>
                  </span>
                  <span v-for="sf  in avg_fields" style="padding:35px;padding-bottom:15px">
                    <el-badge :value="avgdata[sf.field]">
                      <el-button size="mini">{{ sf.label }}</el-button>
                    </el-badge>
                  </span>
                  <slot name="calcfield" :calc="calcdata"></slot>
            </el-col>
        </el-row>
        <a id="grid2_export"></a>
        <el-table
          :border="border"
          :data="data"
          tooltip-effect="dark"
          style="width: 100%"
          :max-height="tblHeight"
          :header-cell-style="headerCellStyle"
          :highlight-current-row="singleSelect"
          :show-summary="issum"
          sum-text="页合计"
          :summary-method="getSummaries"
          @row-click="randRowclick"
          @selection-change="handleSelectionChange"
          @current-change="handleCurrentChange">
              <el-table-column
                type="selection"
                width="50"
                v-if="!isSingleSelect">
              </el-table-column>
              <el-table-column v-if="isIndexed"
                label="序号"
                type="index"
                width="60">
              </el-table-column>
          <template v-for="(col, index) in columnMetaData">
            <template v-if="!col.isTmpl">
                <el-table-column
                   min-width="5%"
                  :label="col.label"
                  :prop="col.prop"
                  :formatter="colFormatter"
                  :show-overflow-tooltip="col.isShowTip?col.isShowTip:false">
                </el-table-column>
            </template>
            <template v-if="col.isTmpl">
                <el-table-column
                  :fixed="col.pos?col.pos:pos"
                  fit
                  min-width="5%"
                  :label="col.label"
                  :type="col.type"
                  :show-overflow-tooltip="col.isShowTip?col.isShowTip:false">
                  <template slot-scope="scope">
                      <slot v-if="col.isBtns" name="btns" :row="scope.row">
                          <el-button type="text" v-for="btn in toolbar" v-if="btn.isInRow && btnvisbleMethod(scope.row,btn)" @click="rowClick(scope.row,btn.key,btn.title,$event)" >{{formatBtn(scope.row,btn)}}</el-button>
                      </slot>
                      <slot v-if="col.isOther" name="other" :row="scope.row">
                          <img width="30px" height="30px" :src="scope.row[col.prop]"/>
                      </slot>
                      <slot v-if="col.isOther2" name="other2" :row="scope.row">
                      </slot>
                      <slot v-if="col.isOther3" name="other3" :row="scope.row">
                      </slot>
                      <slot v-if="col.isOther4" name="other4" :row="scope.row">
                      </slot>
                  </template>
                </el-table-column>
            </template>
          </template>
        </el-table>
        <gsb-pager style="margin-top:20px;" ref="pagerRef" @pageChange="pageChanged"></gsb-pager>
           </el-card>
      </div>
        <div name="frmid"   style="background-color:white;overflow:hidden;width:90%;min-height:1000px">
          <gsb-detailform :isreadonly="formreadonly" @onselchange="onselchange"  ref="dlgform" @dlgFormClick="onDlgFormClick" :refvalidatemethod="validateformmethod"  :headTitle="headTitle" :metaData="formMetaData" :toolbar="toolbar">
              <slot name="top" slot="top"></slot>
            <slot></slot>
          </gsb-detailform>
        </div>
  </div>

`
module.exports=
`{
   template:'${tmpl}',
   props:["sumparams","readonlyform","calcfields","sumfields","avgfields","cansum","btnvisble","validateformmethod","focuskey","isIndexed","isLazy","border","bizCode","dataSource","colFormatter","headStyle","spaceHeight","isSingleSelect","isDataAuto","listMethod","deleteMethod","initMethod","createMethod","updateMethod"],
   data:function(){
     return {
       sumParams:this.sumparams || [],
       sum_fields:this.sumfields?this.sumfields:[],
       avg_fields:this.avgfields?this.avgfields:[],
       calcdata:this.calcfields?this.calcfields:[{label:"余额",value:1000}],
       sumdata:{},
       avgdata:{},

       issum:this.cansum?this.cansum:false,
       pos:"right",
       border:this.border?true:false,
       toolbar:[],
       data:this.dataSource?this.dataSource:[],
       singleSelect:this.isSingleSelect=="true"?true:false,
       columnMetaData:[],
       searchMetaData:[],
       formMetaData:[],
       headTitle:"",
       status:"common",
       multiSelect:null,
       currentSearchObj:null,
       left_width:"100%",
       right_width:"0",
       tblHeight:"1000",
       btnvisbleMethod:this.btnvisble?this.btnvisble:this.btnctlfunc,
       formreadonly:this.readonlyform?this.readonlyform:false,
     };
   },
   created:function(){
      this.fetchMetaData();
   },
   mounted:function(){
    if(this.isDataAuto){
        this.fetchData();
    }
    this.showLeft();
   },
   watch:{
      header_height:function(a){

      }
   },
   computed:{

   },
   methods:{
     onselchange(prop,formModel,target){
        this.$emit("onselchange",prop,formModel,target);
     },     
     btnctlfunc:function(row,btn){
            if(row.isSystem){
                if(btn.key=="delete"){
                    return false; 
                }
            }
            return true;    
     },
     randRowclick:function(r){
       this.$emit("randrowclick",r);
     },
     linkInInitQuery:function(prop,val){
        console.log("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
        var qm=this.$refs.searchForm.getModel();
        qm[prop]=val;
        this.isLazy=true;
         console.log("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
        this.$refs.searchForm.doquery();
     },
     h(d){
       alert(d);
     },
     getSearchForm(){
      return this.$refs.searchForm;
     },
     showLeft(){
       console.log("xxxxxxxxxxxxxxxxxxxxxx---left");
      $("[name='grdid']").show();
      $("[name='frmid']").hide();
     },
     showRight(){
         console.log("xxxxxxxxxxxxxxxxxxxxxx---right");
         try{
   $("[name='frmid']").show();
      $("[name='grdid']").hide();
         }catch(e){
           console.log(e);
         }
   
      console.log("xxxxxxxxxxxxxxxxxxxxxx---right---over");
     },
     formatBtn:function(row,btn){
       if(btn.falseText!="undefined"){
           if(row[btn.boolProp]==false){
              return btn.falseText;
           }else{
              return btn.title;
           }
       }else{
         return btn.title;
       }
     },
     buildQuery(qobj){
       var rtn={};
       /*需要根据外部环境变量来决定是否使用缓存的查询条件,如果是页签被点*/
       if(this.istabclick){
          var rtnCache= this.$root.localdata(this.bizCode);
          console.log("...................",this.bizCode);
          if(rtnCache){
            this.$store.state.istabclick=false;
            this.$refs.pagerRef.pageInfo.currentPage=rtnCache.pageInfo.pageNo;
            this.$refs.pagerRef.pageInfo.pageSize=rtnCache.pageInfo.pageSize;
            setTimeout(()=>{
              this.$refs.searchForm.initModel(rtnCache.search);
            },1000);

            return rtnCache;
          }
          this.$store.state.istabclick=false;
       }
     
       if(qobj){
         rtn.search=qobj;
         if(qobj.queryClick){
          this.$refs.pagerRef.pageInfo.currentPage=1;
          delete qobj.queryClick;
         }
       }else{
         this.$refs.searchForm.getModel().queryClick=false;
         rtn.search=this.$refs.searchForm.getModel();
       }
       /*汇总查询字段*/
       rtn.aggsinfo={sum:this.sum_fields,avg:this.avg_fields};
       rtn.pageInfo={pageSize:this.$refs.pagerRef.pageInfo.pageSize,pageNo:this.$refs.pagerRef.pageInfo.currentPage};
       delete this.$refs.searchForm.getModel().queryClick;
         /*存储当前grid查询条件*/
       console.log(".....................buildQuery..",this.bizCode);
       this.$root.localdata(this.bizCode,rtn);
       return rtn;
     },
     pageChanged(ps,cp){
       if(this.isDataAuto){
           this.fetchData(this.currentSearchObj);
       }else{
          this.$emit("pagechanged",ps,cp,this.currentSearchObj);
       }
     },
     setpageTotal(total){
        this.$refs.pagerRef.pageInfo.total=total;
     },
     fetchData:function(qobj){
       if(!this.isLazy){
         var self=this;
         var methodName=this.listMethod?this.listMethod:"findAndCountAll";
         var url=this.getUrl(methodName);
         var qc=this.buildQuery(qobj);
         this.$root.showMask();
         this.$root.postReq(url,qc).then(d=>{
           console.log("111qqqqqqqqqqqqqqqq");
            console.log(d);
             this.data=d.data.results.rows;
             this.$refs.pagerRef.pageInfo.total=d.data.results.count;
             if(d.data.aggresult){
                 Object.keys(d.data.aggresult).forEach(k=>{
                     var fieldStr=k.split("_")[0];
                     var keyStr=k.split("_")[1];
                     if(keyStr=="sum"){
                       this.sumdata[fieldStr]=d.data.aggresult[k];
                     }
                     if(keyStr=="avg"){
                       this.avgdata[fieldStr]=d.data.aggresult[k];
                     }
                 });
                 this.$emit("calcfield",this.sum_fields,this.sumdata,this.avg_fields,this.avgdata);
             }
             console.log("===============");
                console.log(this.sumdata);
             this.$root.hideMask();
         });
       }
     },
     fetchData2:function(qobj){
         var self=this;
         var methodName=this.listMethod?this.listMethod:"findAndCountAll";
         var url=this.getUrl(methodName);
         var qc=this.buildQuery(qobj);
         this.$root.showMask();
         this.$root.postReq(url,qc).then(d=>{
             this.data=d.data.rows;
             this.$refs.pagerRef.pageInfo.total=d.data.count;
             this.$root.hideMask();
         });
     },
     fetchMetaData(){
        var self=this;
        this.$root.getReq("/web/metaCtl/getUiConfig",{"biz":this.bizCode}).then(cfg=>{
           if(cfg && cfg.data){
             cfg.data.toolbar.forEach(s=>{
              self.toolbar.push(s);
             });
             self.columnMetaData=cfg.data.list.columnMetaData;
             cfg.data.search.forEach(s=>{
               self.searchMetaData.push(s);
             });
             if(cfg.data.form){
                cfg.data.form.forEach(s=>{
                      self.formMetaData.push(s);
                });
             }
             console.log("grid init searchMetaData.......finished");
           }

        });
     },
     handleSelectionChange:function(val){
       this.multiSelect=val;
       this.$emit("multiSelect",val);
     },
     handleCurrentChange:function(row,oldrow){
       if(row){
         this.$emit("changeRow",row,oldrow);
       }
     },
     headerCellStyle:function(){
         return {
                "background-color": "#F5F5F5",
                "color": "#2F2F2F",
                "font-size": "14px",
                "font-weight":"400"
        };
       if(this.headStyle){
         return this.headStyle;
       }else{
        return {
                "background-color": "#F5F5F5",
                "color": "#2F2F2F",
                "font-size": "14px",
                "font-weight":"400"
        };
       }
      
     },
     rowClick(row,key,t,e){
      if(key=="delete"){
          this.$confirm('此操作将删除当前记录, 是否继续?', '提示', {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           type: 'warning'
         }).then(() => {
           var self=this;
           var methodName=this.deleteMethod?this.deleteMethod:"delete";
           var url=this.getUrl(methodName);
           this.$root.postReq(url,{id:row.id}).then(rtn=>{
             console.log("delete ok");
              console.log(rtn.data);
              if(rtn.status==0){
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.fetchData();
              }
           }
          );
         }).catch(() => {
           this.$message({
             type: 'info',
             message: '已取消删除'
           });
         });
      }
      if(key=="linkquery"){
        this.$emit("linkquery",row,key,e);
        return;
      }
      if(key=="edit"){
        this.showRight();
        this.$nextTick(()=>{
          this.status="edit";
          this.$refs.dlgform.setInitData(row);
          this.$emit("beforeedit",row);
        });
      }
      else{
        this.$emit("rowclick",row,key,e);
      }
     },
     onDlgFormClick:function(k,model){
       this.$emit("onDlgFormClick",k,model);
       if(k=="save"){
          this.$refs.dlgform.validate((valid)=>{
             if(valid){
               var methodName=null;
               if(this.status=="new"){
                 methodName=this.createMethod?this.createMethod:"create";
               }
               if(this.status=="edit"){
                 methodName=this.updateMethod?this.updateMethod:"update";
               }
               var url=this.getUrl(methodName);
               this.$root.showMask();
               this.$root.postReq(url,model).then(d=>{
                 this.$root.hideMask();
                 console.log("new Instance..ok.....");
                 if(d.status==0){
                   if(this.status=="new"){
                       this.$message({
                         type: 'success',
                         message: '新增成功!'
                       });
                   }
                   if(this.status=="edit"){
                       this.$message({
                         type: 'success',
                         message: '修改成功!'
                       });
                   }
                   this.$refs.dlgform.setInitData({});
                   this.showLeft();
                   this.status="common";
                   this.fetchData();
                 }else{
                   console.log(d);
                   this.$message.warning(d.msg+',保存失败!');
                 }
               });
               this.$emit("onsave",model);
             }else{
               console.log("表单验证不过......");
             }
          });

       }
       if(k=="cancel"){
          this.showLeft();
          this.$refs.dlgform.setInitData({});
          this.status="common";
       }

     },
     onToolbarClick:function(k,t){
       this.$emit("toolbarclick",k,t,this.multiSelect);
       if(k=="new"){
         this.status="new";
         var methodName=this.initMethod?this.initMethod:"initNewInstance";
         const url = this.getUrl(methodName);
         this.$root.getReq(url,null).then(d=>{
           console.log("init new initNewInstance........");
           console.log(d);
           if(d.status==0){
              this.showRight();
              this.$nextTick(()=>{
                this.$refs.dlgform.setInitData(d.data);
              });
           }
         });

       }
       if(k=="delete"){
        /*需要检查多选值，如果没有多选值，那么无法删除*/
        if(this.multiSelect && this.multiSelect.length>0){
          var ids=this.multiSelect.map(r=>{
             return r.id;
          });
          this.$confirm('此操作将删除选中记录, 是否继续?', '提示', {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           type: 'warning'
         }).then(() => {
           const url = this.getUrl("bulkDelete");
           this.$root.postReq(url,ids).then(d=>{
               if(d.status==0){
                 this.$message({
                   type: 'success',
                   message: '删除成功!'
                 });
                 this.fetchData();
               }
           });
         }).catch(() => {
             this.$message({
               type: 'info',
               message: '已取消删除'
             });
         });

        }
       }
       if(k=="audit"){
         if(!this.multiSelect){
           this.$message({
             type: 'warning',
             message: '请至少选择一行数据!'
           });
         }
         var tmpFilter= this.multiSelect.filter(f=>f.auditStatus=="dsh");
         if(this.multiSelect.length!=tmpFilter.length){
              this.$message({
                  type: 'warning',
                  message: '目前只能对审核待为【待审核】的数据进行审核!'
                });
              return;
         }
         if(this.multiSelect && this.multiSelect.length>0){
           this.$prompt("若审核不通过,请输入理由","批量审核",{
             closeOnClickModal:false,
             showClose:false,
             confirmButtonText: '不通过',
             cancelButtonText: '通过',
           }).then((value) => {
             const url = this.getUrl("audit");
             if(value=="" || !value){
                 this.$message({
                     type: 'warning',
                     message: '不通过失败，请输入审核不通过的理由!'
                   });
                  return;
             }
             else{
                this.$root.postReq(url,{audlist:this.multiSelect,notes:value,status:"btg"}).then(d=>{
                    if(d.status==0){
                      this.$message({
                        type: 'success',
                        message: '否决完成.'
                      });
                      this.fetchData();
                    }
                });
             }
           }).catch(()=>{
             const url = this.getUrl("audit");
             this.$root.postReq(url,{audlist:this.multiSelect,notes:"同意",status:"tg"}).then(d=>{
                 if(d.status==0){
                   this.$message({
                     type: 'success',
                     message: '审核通过完成.'
                   });
                   this.fetchData();
                 }else{
                 }
             });
           })
         }
       }
       if(k=="export"){
        if(this.multiSelect && this.multiSelect.length>0){
          var ids=this.multiSelect.map(r=>{
             return r.id;
          });
          this.$confirm('此操作将导出选中记录, 是否继续?', '提示', {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           type: 'warning'
         }).then(() => {
           this.tableToExcel(this.multiSelect);
           
         }).catch(()=>{
             this.$message({
               type: 'info',
               message: '已取消导出'
             });
         });

        }
       }
     },
     tableToExcel(jsonData){
      var str = "";
      for(var i=0;i<this.columnMetaData.length;i++){
        if(this.columnMetaData[i] && this.columnMetaData[i].isShowTip){
          str=str+"<td>"+this.columnMetaData[i].label+"</td>"
        }
        
      }
      str=str+"</tr>";
      for(var i = 0 ; i < jsonData.length ; i++ ){
        str+='<tr>';
        var jdata = jsonData[i];
       
        for(var j=0;j<this.columnMetaData.length;j++){
          if(this.columnMetaData[j] && this.columnMetaData[j].isShowTip){
            
            var item = this.columnMetaData[j];
            var itemCode = item.prop;
            var itemCodes = itemCode.split(".");
            var itemName="";
            var value="";
            for(var k=0;k<itemCodes.length;k++){
                itemName = itemCodes[k];
                value = jdata[itemName];
            }
            str+="<td>"+value+"</td>";   
          }
              
        }
        str+="</tr>";
      }

      var worksheet = "Sheet1";
      var uri = 'data:application/vnd.ms-excel;base64,';

      var template = "<html xmlns:o=\'urn:schemas-microsoft-com:office:office\' xmlns:x=\'urn:schemas-microsoft-com:office:excel\' xmlns=\'http://www.w3.org/TR/REC-html40\'>"+
      "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>"+worksheet+"</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"+
      "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>"+str+"</table></body></html>";
      var oa = document.getElementById("grid2_export");
      oa.href = uri + this.base64(template);
      oa.download = "导出.xls";
      oa.click();
      oa.style.display='none';
    },
    base64 (s) { 
      return window.btoa(unescape(encodeURIComponent(s)));
    },
     queryClick:function(qobj){
        this.isLazy=false;
        this.currentSearchObj=qobj;
        this.currentSearchObj.queryClick=true;
        this.fetchData(qobj);
     },
     showDlgForm:function(){
       this.showRight();
     },
     hideDlgForm:function(){
       this.showLeft();
     },
     setInitFormData:function(data){
       this.$nextTick(()=>{
         this.$refs.dlgform.setInitData(data);
       });
     },
     getFormModel:function(){
        return  this.$refs.dlgform.getFormModel();
     },
     getSummaries(param) {
        if(this.sumParams && this.sumParams.length>0){
          var sumObj=['页合计'];
          var cols = param.columns;
          var data = param.data;
          for(var i=1;i<cols.length;i++){
            var col = cols[i];
            if(col.property && this.isInArray(this.sumParams,col.property)){
              var value = 0;
              for(var j=0;j<data.length;j++){
                var d = data[j];
                var da =  d[col.property] || 0;
                da = Number(da);
                value = value+da;
              }
              value = value.toString();
              sumObj[i]=value;
            }else{
              sumObj[i]="";
            }
          }
          return sumObj;
        }else{
          return ['页合计'];
        }
     },
     isInArray(arr,value){
        for(var i = 0; i < arr.length; i++){
            if(value === arr[i]){
                return true;
            }
        }
        return false;
      },
   },
   vname:"gsb-grid2"
}`
