import { getWedaAPI, createComponent, concatClassList, px2rpx } from '@cloudbase/weda-client'
<%= 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 %>' <%}) %>

const app = new Proxy({}, { get: function(obj, prop){ return getWedaAPI()?.app?.[prop] }});
const $app = new Proxy({}, { get: function(obj, prop){ return app[prop] }});

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

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(',')
}%>

<% function printEventHandler(eventHandlers) {
  Object.entries(eventHandlers).map(([handlerName, listeners])=>{
    print(`"${handlerName}": [
      ${listeners.map(l=>{
        return `{
          key: '${l.key||''}',
          sourceKey: '${ l.sourceKey||"" }',
          handler: ${l.generateHandler('../') || 'undefined'},
          args: ${JSON.stringify(l.args||{}, undefined, 2)},
          argsBinds: {${printBoundData(l.argsBinds)}}
        }`
      }).join(',')}
    ],`)
  })
}%>

const evtListeners = {<% printEventHandler(eventHandlers) %>}

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 query = {<% Object.entries(query).map(([id, item])=>{%>
  <%= id %>: { <% const {dataBinds={}, eventHandlers, handler, ...rest } = item %>
    ...(<%= JSON.stringify(rest, undefined, 2) %>),
    handler: <%= handler %>,
    dataBinds: {<%= printBoundData(dataBinds) %>},
    eventHandlers: {<% printEventHandler(eventHandlers) %>}
  },<%}) %>
}

const eventFlows = [<% eventFlows.map(flow => {%> { <% const { eventHandlers, ...rest } = flow %>
  ...(<%= JSON.stringify(rest, undefined, 2) %>),
  eventHandlers: {<% printEventHandler(eventHandlers) %>}
},<%}) %>
]

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

createComponent({
  key: '<%= key %>',
  behaviors,
  properties,
  events,
  handler: handlers,
  dataBinds,
  evtListeners,
  widgetProps,
  lifeCycle,
  stateFn,
  computedFuncs,
  config,
  datasetProfile,
  query,
  eventFlows,
  nativeMode: !!<%= nativeMode %>,
})
