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 _hanlder<%= h %> from './lowcode/handler/<%= h %>' <%}) %>
import * as constObj from '../libCommonRes/const'
import * as toolsObj from '../libCommonRes/tools'

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

const libCode = '<%= materialName %>'

const widgetProps = <%= JSON.stringify(widgetProps, undefined, 2) %>

<% function printBoundData(boundData={}) {
  const list = []
  Object.entries(boundData).map(([prop, bindMeta])=>{
    const str = `'${prop}': ($comp, lists, forItems, event, $context, $w) => {${bindMeta.imports} return(
      ${bindMeta.expression === '' ? 'undefined': bindMeta.expression}
    )}`
    list.push(str)
  })
  return list.join(',')
}%>

const evtListeners = {<% Object.entries(eventHandlers).map(([handlerName, listeners])=>{%>
  <%= handlerName%>: [
    <%listeners.map(l=> { %>{
      key: '<%= l.key %>',
      sourceKey: '<%= l.sourceKey %>',
      handler: <%= l.generateHandler('../') %>,
      args: <%= JSON.stringify(l.args, undefined, 2) %>,
      argsBinds: { <%= printBoundData(l.argsBinds) %>}
    },<%})%>
  ],<%})%>
}

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 dataBinds = {<% Object.entries(dataBinds).map(([id, widgetBinds])=>{%>
  <%= id %>: { <%= printBoundData(widgetBinds) %>
  },<%}) %>
}

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

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