this.primevue = this.primevue || {};
this.primevue.form = (function (vue, utils) {
  'use strict';

  var script = {
      name: 'Form',
      emits: ['row-new-init','item-change'],

      props: {
         disabled:{
              type:Boolean,
              default:false
          },
          
          readonly:{
              type:Boolean,
              default:false
          },

          labelWidth: {
              type: [String, Number],
              default: '',
          },
          
          hideRequiredAsterisk: {
              type: Boolean,
              default: false,
          },
      },
      
      provide(){
          return {
              "Form": vue.computed(()=>{
                  return {
                       "setFocus": this.setFocus,
                       "primaryData": this.d_primaryData,
                       "onItemChange": this.onItemChange,
                       ...this.$props
                      }
              })
          }
       },
       
       data() {
          return {
              d_primaryData:null,
              d_modified:false
          }
      },

      methods: {
          getChildren() {
              return this.$slots.default ? this.$slots.default() : null;
          },

          recursiveGetChildren(children, results) {
              if (!results) {
                  results = [];
              }

              if (children && children.length) {
                  children.forEach((child) => {
                          if (child.type.name == 'FormItem') {
                             results.push(child);
                          }
                          else if (child.children && child.children instanceof Array) {
                              this.recursiveGetChildren(child.children, results);
                          }
                          else if(child.children && ( typeof child.children.default )==='function'){
                               this.recursiveGetChildren(child.children.default(), results);
                          }
                  });
              }

              return results;
          },
          formItemProp(item, prop) {
              return utils.ObjectUtils.getVNodeProp(item, prop);
          },

         setFocus(field){
             if(!field)
               return;

             setTimeout(() => {
                  const itemEl = this.$el.querySelector(`[data-field=${field}`);

                  if(itemEl){
                      // itemEl.scrollIntoView && itemEl.scrollIntoView({ block: 'nearest', inline: 'start' });
                      const focusableEl = utils.DomHandler.getFirstFocusableElement(itemEl);

                      focusableEl && focusableEl.focus();
                  }
              }, 50);
         },
        
         setData(newData){
             this.d_primaryData = (newData) ? utils.DataHandler.Proxy(newData, 1, this._interalSetModified ) : null ;
             this.d_modified=false;
          },

         getData(){
              return this.d_primaryData ;
          },

         new(){
              let _items = this.items|| [] ;
              let rowData =(this.d_primaryData)? utils.DataHandler.Initialize( this.d_primaryData,1 ,this._interalSetModified ) : {}  ;
              
              for (let i = 0; i <_items.length; i++) {
                  const item = _items[i];
                  const field= this.formItemProp(item, 'field') || '';
                  const initial = this.formItemProp(item, 'initial')  ;
                  const colType =  this.formItemProp(item, 'colType') || '';
                  
                  if (field) {
                      rowData[field] =(initial!==null && initial!==undefined && initial!=='' )? utils.ObjectUtils.initailValue(initial, colType) : null ;
                  }
              }

              if(!('rowId' in rowData) || !('originalData' in rowData)){
                  rowData=utils.DataHandler.Proxy(rowData,1, this._interalSetModified );
              }

              utils.DomHandler.clearSelection();
              this.$emit('row-new-init', rowData);
              rowData['rowStatus'] = utils.RowStatus.New;
              this.d_primaryData = rowData; 
              this.d_modified=false;

              return rowData;  // 返回新增行的数据，以便对新增行的数据进行赋值 
         }, 

         setItem(fieldName,value){
              this.d_primaryData[fieldName] = value;
          },

          getItem(fieldName){
              return this.d_primaryData[fieldName] ;
          },

          reset(){
              this.d_primaryData = null;
              this.d_modified=false;
          },

          resetUpdate(){
              if(!this.d_primaryData)
                  return;

              this.d_primaryData.resetUpdate();
              this.d_modified=false;
          },
          isModified(){
              /*
             if(!this.d_primaryData)
                  return false ;

             return (this.d_primaryData.rowStatus=== RowStatus.DataModified ||  this.d_primaryData.rowStatus=== RowStatus.NewModified) ? true:false;
             */
             
             return this.d_modified;
          },

         onKeydown(event){

           var target = event.target || event.srcElement;
           if( (target.nodeName ||'').toUpperCase()==='TEXTAREA')
              return;

           switch (event.code) {
              case 'Enter':
              case 'NumpadEnter':
                 {
                  const focusableEl = utils.DomHandler.getNextFocusableElement(this.$el , target);

                  if(focusableEl )
                  {
                     event.preventDefault();
                     event.stopPropagation();
                     focusableEl.focus();
                  }
                 }

                 break;
           }
         },
         onItemChange(event){
            this.$emit('item-change', event);
         },

         _interalSetModified(newData){
             this.d_modified=newData;
          },
      },
      computed:{
          items() {
              let children = this.getChildren();

              if (!children) {
                  return;
              }

              return  this.recursiveGetChildren(children, []);
          },
      }
  };

  function render(_ctx, _cache, $props, $setup, $data, $options) {
    return (vue.openBlock(), vue.createElementBlock("div", {
      class: "form-container",
      onKeydown: _cache[0] || (_cache[0] = (...args) => ($options.onKeydown && $options.onKeydown(...args)))
    }, [
      vue.renderSlot(_ctx.$slots, "default")
    ], 32 /* HYDRATE_EVENTS */))
  }

  function styleInject(css, ref) {
    if ( ref === void 0 ) ref = {};
    var insertAt = ref.insertAt;

    if (!css || typeof document === 'undefined') { return; }

    var head = document.head || document.getElementsByTagName('head')[0];
    var style = document.createElement('style');
    style.type = 'text/css';

    if (insertAt === 'top') {
      if (head.firstChild) {
        head.insertBefore(style, head.firstChild);
      } else {
        head.appendChild(style);
      }
    } else {
      head.appendChild(style);
    }

    if (style.styleSheet) {
      style.styleSheet.cssText = css;
    } else {
      style.appendChild(document.createTextNode(css));
    }
  }

  var css_248z = "\n.form-container{\r\n      padding: 6px ;\n}\n.form-row{\r\n     height: 30px;\r\n     display: flex;\r\n     flex-wrap: nowrap;\r\n     align-items: center;\r\n     margin-bottom: 8px;\n}\n.form-row:last-child{\r\n        margin-bottom:  0;\n}\n.form-item{\r\n     display: flex;\r\n     align-items: center;\n}\n.form-item-label{\r\n      padding: 0 0.5rem;\r\n      color:#606266;\r\n      text-align: right;\n}\n.required::before{\r\n    content: \"*\";\r\n    color:#db2828;\r\n    margin-right: 4px;\n}\n.form-item-content{\r\n      flex:1;\n}\n.form-item-suffix{\r\n    padding-left: 0.5rem;\r\n    color:#606266;\n}\n.form-item .p-inputtext{\r\n    width:100%;\n}\r\n\r\n";
  styleInject(css_248z);

  script.render = render;
  script.__file = "components/lib/form/Form.vue";

  return script;

})(Vue, primevue.utils);
