app-form-json.vue 17.0 KB
Newer Older
sq3536's avatar
sq3536 committed
1 2
<template>
  <div class="app-form-json">
sq3536's avatar
sq3536 committed
3 4
    
    <div :id='id' :innerHTML="id"></div>
sq3536's avatar
sq3536 committed
5
    <el-input type="textarea" :rows="10" placeholder="请输入内容" v-model="CurrentVal">
sq3536's avatar
sq3536 committed
6 7 8 9 10 11 12
    </el-input>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Model, Watch } from "vue-property-decorator";
import { VNode, CreateElement } from "vue";
import { interval, Subject, Subscription } from "rxjs";
sq3536's avatar
sq3536 committed
13
import { Http,Util } from '@/utils';
sq3536's avatar
sq3536 committed
14 15 16 17
import JSONEditor from "@json-editor/json-editor";
import BootstrapVue from "bootstrap-vue";
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-vue/dist/bootstrap-vue.css";
sq3536's avatar
sq3536 committed
18
import "./select2.js";
sq3536's avatar
sq3536 committed
19 20 21
import "select2/dist/css/select2.min.css"
import 'jquery/dist/jquery.min.js'
import $ from 'jquery'
sq3536's avatar
sq3536 committed
22 23
import "../app-form-json/app-form-json.less";

sq3536's avatar
sq3536 committed
24 25 26 27 28 29 30 31 32 33 34 35 36

JSONEditor.defaults.resolvers.unshift(schema => {
  if(schema.type === "selectnew" ) {
    return "selectnew";
  }
  else if(schema.type === "link" ) {
    return "link";
  }

  // If no valid editor is returned, the next resolver function will be used
});

JSONEditor.defaults.editors.selectnew =  JSONEditor.defaults.editors.select.extend({
sq3536's avatar
sq3536 committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    remoteCached : {},
    getRemoteItems: function(url){
      var self = this
      if(self.remoteCached[url])
          return self.remoteCached[url];
      const token = window.localStorage.getItem('token');
      var new_items = [];
                 $.ajax({
                            url: url,
                            headers: { 
                              "Authorization":"Bearer "+token//此处放置请求到的用户token
                            },
                            type: 'get',
                            contentType: 'application/json',
                            dataType: 'text',
                            async: false, // 同步
                            success: function (result) {
                                var resObj = JSON.parse(result);
                                resObj.forEach((item: any)=>{
                                    new_items.push(item);
                                });
                                self.remoteCached[url]=new_items;
                            },
                            error: function (result) {
                            }
                        });
        return new_items;                
    },

sq3536's avatar
sq3536 committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    onWatchedFieldChange: function() {
    var self = this, vars, j;

    // If this editor uses a dynamic select box
    if(this.enumSource) {
      vars = this.getWatchedFieldValues();
      var select_options = [];
      var select_titles = [];

      for(var i=0; i<this.enumSource.length; i++) {
        // Constant values
        if(Array.isArray(this.enumSource[i])) {
          select_options = select_options.concat(this.enumSource[i]);
          select_titles = select_titles.concat(this.enumSource[i]);
        }
        else {
          var items = [];
          // Static list of items
          if(Array.isArray(this.enumSource[i].source)) {
            items = this.enumSource[i].source;
          // A watched field
          } else {
            items = vars[this.enumSource[i].source];
          }

          if(items) {
            // Only use a predefined part of the array
            if(this.enumSource[i].slice) {
              items = Array.prototype.slice.apply(items,this.enumSource[i].slice);
            }
            // Filter the items
            if(this.enumSource[i].filter) {
              var new_items = [];
              for(j=0; j<items.length; j++) {
                if(this.enumSource[i].filter({i:j,item:items[j],watched:vars})) new_items.push(items[j]);
              }
              items = new_items;
            }

            if(this.enumSource[i].url)
            {
              var url=this.enumSource[i].url;
sq3536's avatar
sq3536 committed
108
             
sq3536's avatar
sq3536 committed
109 110 111
              var p0=vars[this.enumSource[i].p0];
              var p1=vars[this.enumSource[i].p1];
              var p2=vars[this.enumSource[i].p2];
sq3536's avatar
sq3536 committed
112
              var p3=vars[this.enumSource[i].p3];
sq3536's avatar
sq3536 committed
113
              if(p0&&p0!='null')
sq3536's avatar
sq3536 committed
114
                url=url.replace('${p0}',p0);
sq3536's avatar
sq3536 committed
115
              if(p1&&p1!='null')
sq3536's avatar
sq3536 committed
116
                url=url.replace('${p1}',p1);
sq3536's avatar
sq3536 committed
117
              if(p2&&p2!='null')
sq3536's avatar
sq3536 committed
118
                url=url.replace('${p2}',p2);
sq3536's avatar
sq3536 committed
119
              if(p3&&p3!='null')
sq3536's avatar
sq3536 committed
120 121 122 123 124 125 126 127 128 129 130 131 132
                url=url.replace('${p3}',p3);  
              
              var localdata;
              if(url.indexOf("${localdata.")>0)
              {
                localdata = window.localStorage.getItem('localdata');
                if(localdata)
                {
                  url=url.replace('${localdata.dstsystemid}',localdata["dstsystemid"]);   
                }
                
              } 
              
sq3536's avatar
sq3536 committed
133
              var new_items = [];
sq3536's avatar
sq3536 committed
134
              if(url.indexOf("${")<0)
sq3536's avatar
sq3536 committed
135
              { 
sq3536's avatar
sq3536 committed
136 137
                var firstObj = (JSON.parse(JSON.stringify(items[0])));
                items = JSON.parse(JSON.stringify(this.getRemoteItems(url)));
sq3536's avatar
sq3536 committed
138
                items.unshift(firstObj);            
sq3536's avatar
sq3536 committed
139 140 141 142 143
              }
              else
              {
                  new_items.unshift(JSON.parse(JSON.stringify(items[0])));
                  items = new_items;
sq3536's avatar
sq3536 committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
              }
            }
            if(this.enumSource[i].filterText)
            {
              var filterText=vars[this.enumSource[i].filterText];

              if(filterText)
              {
                var new_items = [];
                new_items=items.filter(item22 => ((item22.text&&item22.text.indexOf(filterText)>=0)||
                          (item22.value&&item22.value.indexOf(filterText)>=0)||
                          (item22.filter&&item22.filter.indexOf(filterText)>=0)));
                new_items.unshift({text:"--",id:""});
                items = new_items;
              }
            }


            var item_titles = [];
            var item_values = [];
            for(j=0; j<items.length; j++) {
              var item = items[j];

              // Rendered value
              if(this.enumSource[i].value) {
                item_values[j] = this.typecast(this.enumSource[i].value({
                  i: j,
                  item: item
                }));
              }
              // Use value directly
              else {
                item_values[j] = items[j];
              }

              // Rendered title
              if(this.enumSource[i].title) {
                item_titles[j] = this.enumSource[i].title({
                  i: j,
                  item: item
                });
              }
              // Use value as the title also
              else {
                item_titles[j] = item_values[j];
              }
            }

            // TODO: sort

            select_options = select_options.concat(item_values);
            select_titles = select_titles.concat(item_titles);
          }
        }
      }

      var prev_value = this.value;

      this.theme.setSelectOptions(this.input, select_options, select_titles);
      this.enum_options = select_options;
      this.enum_display = select_titles;
      this.enum_values = select_options;

      if(this.select2) {
        this.select2.select2('destroy');
      }

      // If the previous value is still in the new select options, stick with it
      if(select_options.indexOf(prev_value) !== -1) {
        this.input.value = prev_value;
        this.value = prev_value;
      }
      // Otherwise, set the value to the first select option
      else {
        this.input.value = select_options[0];
        this.value = this.typecast(select_options[0] || "");  
        if(this.parent) this.parent.onChildEditorChange(this);
        else this.jsoneditor.onChange();
        this.jsoneditor.notifyWatchers(this.path);
      }

      this.setupSelect2();
    }
sq3536's avatar
sq3536 committed
227
    // {
sq3536's avatar
sq3536 committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
      var vars;
      if(this.header_template) {
        vars = $.extend(this.getWatchedFieldValues(),{
          key: this.key,
          i: this.key,
          i0: (this.key*1),
          i1: (this.key*1+1),
          title: this.getTitle()
        });
        var header_text = this.header_template(vars);

        if(header_text !== this.header_text) {
          this.header_text = header_text;
          this.updateHeaderText();
          this.notify();
          //this.fireChangeHeaderEvent();
        }
      }
sq3536's avatar
sq3536 committed
246 247 248 249 250 251 252
      if(this.link_watchers.length) {
        vars = this.getWatchedFieldValues();
        for(var i=0; i<this.link_watchers.length; i++) {
          this.link_watchers[i](vars);
        }
      }
    // }
sq3536's avatar
sq3536 committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
  },
    getLink: function(data) {
        var holder, link;

        // Get mime type of the link
        var mime = data.mediaType || 'application/javascript';
        var type = mime.split('/')[0];

        // Template to generate the link href
        var href = this.jsoneditor.compileTemplate(data.href,this.template_engine);
        var relTemplate = this.jsoneditor.compileTemplate(data.rel ? data.rel : data.href,this.template_engine);

        // Template to generate the link's download attribute
        var download = null;
        if(data.download) download = data.download;

        if(download && download !== true) {
            download = this.jsoneditor.compileTemplate(download, this.template_engine);
        }

        {
            link = holder = this.theme.getBlockLink();
            //holder.setAttribute('target','_blank');
            holder.textContent = data.rel;

            // When a watched field changes, update the url
            this.link_watchers.push(function(vars) {
                var url = href(vars);
                var rel = relTemplate(vars);
                holder.setAttribute('href',url);
                holder.textContent = rel || url;
            });
        }

        if(download && link) {
            if(download === true) {
                link.setAttribute('download','');
            }
            else {
                this.link_watchers.push(function(vars) {
                    link.setAttribute('download',download(vars));
                });
            }
        }
        if(data.class) link.classList.add(data.class);
        if(this.jsoneditor.options.no_link_holder){
            holder.hidden = true;
        }else{
            holder.hidden = false;
        }
        return holder;
    }
});


sq3536's avatar
sq3536 committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
JSONEditor.defaults.editors.link = JSONEditor.defaults.editors.string.extend({
    getLink: function(data) {
        var holder, link;

        // Get mime type of the link
        var mime = data.mediaType || 'application/javascript';
        var type = mime.split('/')[0];

        // Template to generate the link href
        var href = this.jsoneditor.compileTemplate(data.href,this.template_engine);
        var relTemplate = this.jsoneditor.compileTemplate(data.rel ? data.rel : data.href,this.template_engine);

        // Template to generate the link's download attribute
        var download = null;
        if(data.download) download = data.download;

        if(download && download !== true) {
            download = this.jsoneditor.compileTemplate(download, this.template_engine);
        }

        // Image links
        if(type === 'image') {
            holder = this.theme.getBlockLinkHolder();
            link = document.createElement('a');
            link.setAttribute('target','_blank');
            var image = document.createElement('img');

            this.theme.createImageLink(holder,link,image);

            // When a watched field changes, update the url
            this.link_watchers.push(function(vars) {
                var url = href(vars);
                var rel = relTemplate(vars);
                link.setAttribute('href',url);
                link.setAttribute('title',rel || url);
                image.setAttribute('src',url);
            });
        }
        // Audio/Video links
        else if(['audio','video'].indexOf(type) >=0) {
            holder = this.theme.getBlockLinkHolder();

            link = this.theme.getBlockLink();
            link.setAttribute('target','_blank');

            var media = document.createElement(type);
            media.setAttribute('controls','controls');

            this.theme.createMediaLink(holder,link,media);

            // When a watched field changes, update the url
            this.link_watchers.push(function(vars) {
                var url = href(vars);
                var rel = relTemplate(vars);
                link.setAttribute('href',url);
                link.textContent = rel || url;
                media.setAttribute('src',url);
            });
        }
        // Text links
        else {
            link = holder = this.theme.getBlockLink();
            //holder.setAttribute('target','_blank');
            holder.textContent = data.rel;

            // When a watched field changes, update the url
            this.link_watchers.push(function(vars) {
                var url = href(vars);
                var rel = relTemplate(vars);
                holder.setAttribute('href',url);
                holder.textContent = rel || url;
            });
        }

        if(download && link) {
            if(download === true) {
                link.setAttribute('download','');
            }
            else {
                this.link_watchers.push(function(vars) {
                    link.setAttribute('download',download(vars));
                });
            }
        }
        if(data.class) link.classList.add(data.class);
        if(this.jsoneditor.options.no_link_holder){
            holder.hidden = true;
        }else{
            holder.hidden = false;
        }
        return holder;
    }
});

sq3536's avatar
sq3536 committed
402 403
@Component({})
export default class AppFormJson extends Vue {
sq3536's avatar
sq3536 committed
404 405 406



sq3536's avatar
sq3536 committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
  /**
   * 双向绑定值
   *
   * @type {*}
   * @memberof AppFormJson
   */
  @Model("change") itemValue?: any;

  /**
   * 表单数据
   *
   * @type {*}
   * @memberof AppFormJson
   */
  @Prop() public data!: any;

sq3536's avatar
sq3536 committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436
  /**
   * 数据格式
   *
   * @type {*}
   * @memberof AppFormJson
   */
  @Prop() public schema?: any;

  /**
   * 格式选项
   *
   * @type {*}
   * @memberof AppFormJson
   */
sq3536's avatar
sq3536 committed
437
  @Prop() public options?: any;
sq3536's avatar
sq3536 committed
438

sq3536's avatar
sq3536 committed
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
  /**
   * 当前值
   *
   * @return {*}
   * @memberof AppFormJson
   */
  get CurrentVal() {
    return this.itemValue;
  }

  /**
   * 设置值
   *
   * @param {*} [value]
   * @memberof AppFormJson
   */
  set CurrentVal(val: any) {
    this.$emit("change", val);
  }

  /**
   * 表单状态
   *
   * @type {Subject<any>}
   * @memberof AppFormJson
   */
  @Prop() public formState?: Subject<any>;

  /**
   * 表单状态事件
   *
   * @private
   * @type {(Unsubscribable | undefined)}
   * @memberof AppFormJson
   */
  private formStateEvent: Subscription | undefined;

  /**
   * Vue生命周期(实例销毁后)
   *
   * @memberof AppFormJson
   */
  public destroyed() {
    if (this.editor) this.editor = null;
sq3536's avatar
sq3536 committed
483
    window["showdetail"]=null;
sq3536's avatar
sq3536 committed
484 485 486 487 488 489 490 491 492 493 494 495 496
  }

  /**
   * Vue生命周期(实例挂载后)
   *
   * @memberof AppFormJson
   */
  public mounted() {
    if (!this.formState) {
      return;
    }
    this.formStateEvent = this.formState.subscribe(($event: any) => {
      if (Object.is($event.type, "load")) {
sq3536's avatar
sq3536 committed
497
          this.renderJsoneditor();
sq3536's avatar
sq3536 committed
498 499 500 501 502 503 504 505 506 507 508 509
      } 
            if (Object.is($event.type, 'save')) { 
                this.renderJsoneditor();
            }
            // 表单项更新
            if (Object.is($event.type, 'updateformitem')) {
                if (!$event.data) {
                    return;
                } 
                this.renderJsoneditor();
            }
            
sq3536's avatar
sq3536 committed
510
    });
sq3536's avatar
sq3536 committed
511
     
sq3536's avatar
sq3536 committed
512
    window["showdetail"]=this.showdetail;
sq3536's avatar
sq3536 committed
513 514 515 516 517 518 519 520 521 522
  }

  /**
   * 编辑器对象
   *
   * @type {*}
   * @memberof AppFormJson
   */
  public editor: any;

sq3536's avatar
sq3536 committed
523 524
  public id: any = this.$util.createUUID();

sq3536's avatar
sq3536 committed
525

sq3536's avatar
sq3536 committed
526
  public async getSchema(): Promise<any>{
sq3536's avatar
sq3536 committed
527 528 529 530 531 532
    if(this.schema)
      return this.schema;
    else
      return {};
  }

sq3536's avatar
sq3536 committed
533
  public async getOptions(): Promise<any>{
sq3536's avatar
sq3536 committed
534
    let _options={
sq3536's avatar
sq3536 committed
535 536 537 538 539 540 541 542 543
      theme: "bootstrap3",
      iconlib: "fontawesome4",
      disable_edit_json: true,
      display_required_only: true,
      disable_collapse: true,
      disable_array_delete_last_row: true,
      ajax: true,
    };

sq3536's avatar
sq3536 committed
544
    _options["schema"]=await this.getSchema();
sq3536's avatar
sq3536 committed
545

sq3536's avatar
sq3536 committed
546
    if (this.CurrentVal) {
sq3536's avatar
sq3536 committed
547
      _options["startval"] = JSON.parse(this.CurrentVal);
sq3536's avatar
sq3536 committed
548 549
    }

sq3536's avatar
sq3536 committed
550 551
    if(this.options){
      return Object.assign({},_options,this.options)
sq3536's avatar
sq3536 committed
552
    }
sq3536's avatar
sq3536 committed
553
    return _options;
sq3536's avatar
sq3536 committed
554 555
  }

sq3536's avatar
sq3536 committed
556 557 558 559 560
  /**
   * 编辑器生成
   *
   * @memberof AppFormJson
   */
sq3536's avatar
sq3536 committed
561
  public async renderJsoneditor() {
sq3536's avatar
sq3536 committed
562
    var _this = this;
sq3536's avatar
sq3536 committed
563
    var element = document.getElementById(_this.id);
sq3536's avatar
sq3536 committed
564 565 566 567 568
    if (this.editor) {
      this.editor.destroy();
    }


sq3536's avatar
sq3536 committed
569
    let opt:any = await _this.getOptions();
sq3536's avatar
sq3536 committed
570
    this.editor = new JSONEditor(element, opt);
sq3536's avatar
sq3536 committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

    this.editor.on("change", () => {
      let value = _this.editor.getValue();
      _this.CurrentVal = JSON.stringify(value);
    });
  }

  /**
   * 设置编辑器值
   *
   * @param {*} [val]
   * @memberof AppFormJson
   */
  public setEditValue(val: any): void {
    if (val) {
      this.editor.setValue(val);
    } else {
      this.editor.setValue({});
    }
  }
sq3536's avatar
sq3536 committed
591 592 593 594 595 596 597 598 599 600


  public showdetail(path:any,arg:any)
  {
          const view: any = {
              viewname: path,
              height: 0,
              width: 0,
              title: '查看',
          };
sq3536's avatar
sq3536 committed
601
          this.$appmodal.openModal(view, arg, {});
sq3536's avatar
sq3536 committed
602 603
  }

sq3536's avatar
sq3536 committed
604 605
}
</script>