import { observable } from 'mobx';
import { createComponent } from '../../../common/weapp-component'
import { concatClassList, px2rpx } from '../../../common/style'
import { app, $app } from '../../../app/weapps-api'
<%= importor.lifecycle? "import lifeCycle from './lowcode/lifecycle'" : "const lifeCycle = {}" %>
<%= importor.state? "import stateFn from './lowcode/state'" : "const stateFn = {}" %>
<%= importor.computed? "import computedFuncs from './lowcode/computed'" : "const computedFuncs = {}" %>
<% handlers.forEach(h => {%>
import _handler<%= h %> from './lowcode/handler/<%= h %>' <%}) %>
import * as constObj from '../libCommonRes/const'
import * as toolsObj from '../libCommonRes/tools'

const libCode = '<%= materialName %>'

const widgetProps = <%= stringifyObj(widgetProps, {depth: null}) %>

const evtListeners = {<% Object.entries(eventHandlers).map(([handlerName, listeners])=>{%>
  <%= handlerName%>: [
    <%listeners.map(l=> { %>{
      key: '<%= l.key %>',
      handler: <% if (l.type == 'rematch') {%> _handler<%= l.handler %> <%} else {%> <%= l.handler %> <%} %>,
      data: <%= stringifyObj(l.data, {depth: null}) %>,
      boundData: {<% Object.entries(l.boundData).map(([prop, bindMeta])=>{%>'<%= prop %>':($comp, lists, forItems, event, $context, $w) => {<%= bindMeta.imports %> return (
        <%= bindMeta.expression === '' ? 'undefined': bindMeta.expression %>
      )},
        <%}) %>}
    },<%})%>
  ],<%})%>
}

const behaviors = [<% if(formEvents) { %>'wx://form-field'<% } %>]

const properties = {<% Object.entries(propDefs).filter(([prop,def])=>{
  return !!jsonSchemaType2jsClass[def.type]
}).map(([prop, def])=> {%>
  "<%= prop %>": {
    type: <%= jsonSchemaType2jsClass[def.type] %>,<%if(def.extraTypes) { %>
    optionalTypes: [<%= def.extraTypes.split('|').map(t => jsonSchemaType2jsClass[t]).join(',') %>], <% }%>
    <%if(def.default != null) {%>value: <%= JSON.stringify(def.default) %><%}%>
  },<%})%>
}

const events = [<% emitEvents.map(evtName => {%>
  {name: "<%= evtName %>", <% if(formEvents && formEvents[evtName]){%>getValueFromEvent: (event)=> <%= formEvents[evtName] %><%}%>},<%}) %>
]

const handler = {<% handlers.forEach(h => {%>
  <%= h %>: _handler<%= h %>, <%}) %>
}

const dataBinds = {<% Object.entries(dataBinds).map(([id, widgetBinds])=>{%>
  <%= id %>: { <% Object.entries(widgetBinds).map(([prop, bindMeta]) => { %>
    "<%= prop %>": function ($comp, lists, forItems, event, $context, $w) {<%= bindMeta.imports %> return (
      <%= bindMeta.expression === '' ? 'undefined': bindMeta.expression %>
    ); },<% }) %>
  },<%}) %>
}

const config = <%= JSON.stringify(config || {})%>

createComponent('<%= key %>', behaviors, properties, events, handler, dataBinds, evtListeners, widgetProps,
 {}, lifeCycle, stateFn, computedFuncs, config, { const: constObj, tools: toolsObj }, libCode)
