import { observable } from 'mobx';
import { createPage, PAGE_ROOT_SYMBOL } from '<%= subLevelPath %>../../common/weapp-page'
import { concatClassList, px2rpx } from '<%= subLevelPath %>../../common/style'
import { app, $app } from '<%= subLevelPath %>../../app/weapps-api'
import { <%= pageNameVar %> as handlers } from '../../app/handlers'
<%= importor.lifecycle? `import lifecycle from '../../lowcode/${pageName}/lifecycle'` : "const lifecycle = {}" %>
<%= importor.state? `import state from '../../lowcode/${pageName}/state'` : "const state = {}" %>
<%= importor.computed? `import computed from '../../lowcode/${pageName}/computed'` : "const computed = {}" %>
import { $page, $w } from './api'
import { widgetProps } from './data'

<% function printBoundData(boundData={}) {
  const list = []
  Object.entries(boundData).map(([prop, bindMeta])=>{
    const str = `'${prop}': ($page, lists, forItems, event, $context, $w, params) => {${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(subLevelPath) || 'undefined'},
          args: ${JSON.stringify(l.args||{}, undefined, 2)},
          argsBinds: {${printBoundData(l.argsBinds)}}
        }`
      }).join(',')}
    ],`)
  })
}%>

/** widget event listeners **/
const evtListeners = {<% printEventHandler(eventHandlers) %>}

const dataBinds = {
  [PAGE_ROOT_SYMBOL]: {
    <%= printBoundData(pageDataBinds) %>
  },<% 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 datasetProfile = <%= datasetProfile %>

createPage({
  app,
  pageContext: $page,
  id: '<%= pageName %>',
  widgetProps,
  lifecycle,
  state,
  computed,
  evtListeners,
  dataBinds,
  handlers,
  query,
  eventFlows,
  pageAttributes: <%= pageAttributes? JSON.stringify(pageAttributes):'{}' %>,
  resetShare: <%= resetShare %>,
  datasetProfile
})
