<template>
  <view class="page">
    <!-- 主列表页 -->
    <view class="mainpage" style="padding-top: 80rpx; height: calc(100vh - var(--window-top));">
      <!-- 顶部条目/分页信息栏 -->
      <l-customlist-banner :buttonShow="false">{{ tips }}</l-customlist-banner>

      <!-- 滚动列表，跨端支持上拉/下拉 -->
      <l-scroll-list v-if="ready" @pullDown="pullDown" @toBottom="fetchList()" ref="list">
        <l-customlist :tips="loadState" showTips>
          <!-- 单条记录 -->
          <view class="customlist-item" v-for="item of list" :key="item[primaryKey]">
            <!-- 主字段 -->
            <view v-for="scheme of mainSchemes" :key="scheme" class="customlist-item-field margin-bottom-sm">
              <text class="customlist-item-field-title">{{ scheme.title }}：</text>
              {{ displayListItem(item, scheme) }}
            </view>

            <!-- 副字段 -->
            <view v-for="scheme of subSchemes" :key="scheme" class="customlist-item-field" style="font-size: 0.9em;">
              <text class="customlist-item-field-title">{{ scheme.title }}：</text>
              {{ displayListItem(item, scheme) }}
            </view>

            <!-- 操作区 -->
            <l-customlist-action
              @view="action('view', item[primaryKey])"
              @edit="action('edit', item[primaryKey])"
              @delete="action('delete', item[primaryKey])"
              showEdit
              showDelete
            />
          </view>
        </l-customlist>
      </l-scroll-list>
    </view>

    <l-customlist-add @click="action('create')" />
  </view>
</template>

<script>
import get from 'lodash/get'
import moment from 'moment'
import customFormMixins from '@/common/customform.js'

export default {
  mixins: [customFormMixins],

  data() {
    return {
      formId: '',
      formScheme: {},
      dataSource: {},

      // 主键
      primaryKey: '',

      // 主副字段
      mainSchemes: [],
      subSchemes: [],

      // 分页
      page: 1,
      total: 2,
      list: [],

      // 页面相关参数
      ready: false,
      tips: '加载中…',
      loadState: '向下翻以加载更多'
    }
  },

  async onLoad({ formId }) {
    await this.init(formId)
  },

  onUnload() {
    this.OFF('custom-list-change')
  },

  methods: {
    // 初始化页面
    async init(formId) {
      this.ON('custom-list-change', this.refreshList)

      // 加载页面参数（列表 scheme）
      this.formId = formId
      const pageInfo = this.GET_PARAM()
      const listScheme = JSON.parse(pageInfo.F_Scheme)
      this.SET_TITLE(pageInfo.F_Name)

      // 拉取表单结构（表单 scheme），提取出主、副字段
      const formScheme = await this.fetchFormScheme()
      const scheme = formScheme.F_Scheme

      const mainTitleIds = listScheme.title.split(',')
      const subTitleIds = listScheme.content.filter(Boolean)

      // 提取主表、主键信息
      const mainTable = scheme.dbTable.find(t => !t.relationName)
      const tableName = mainTable.name
      this.primaryKey = `${mainTable.field.toLowerCase()}${scheme.dbTable.findIndex(t => !t.relationName)}`

      this.formScheme = formScheme

      // 依次提取主副显示字段的 scheme，并生成它们的 dataSource
      const mainSchemes = []
      const subSchemes = []

      for (let tableIndex = 0; tableIndex < scheme.data.length; ++tableIndex) {
        const { componts } = scheme.data[tableIndex]
        componts.forEach(t => {
          if (t.table === tableName) {
            if (mainTitleIds.includes(t.id)) {
              mainSchemes.push({ ...t, __path__: `${t.field.toLowerCase()}${tableIndex}` })
            } else if (subTitleIds.includes(t.id)) {
              subSchemes.push({ ...t, __path__: `${t.field.toLowerCase()}${tableIndex}` })
            }
          }
        })
      }

      this.mainSchemes = mainSchemes
      this.subSchemes = subSchemes
      this.dataSource = await this.fetchDataSource([...mainSchemes, ...subSchemes])

      this.ready = true
      await this.fetchList()
    },

    // 拉取列表
    async fetchList() {
      if (this.page > this.total) {
        return
      }

      const result = await this.HTTP_GET(
        '/custmer/pagelist',
        {
          pagination: { rows: 10, page: this.page, sidx: this.primaryKey, sord: 'ASC' },
          queryJson: JSON.stringify({}),
          formId: this.formId
        },
        '加载数据时出错'
      )

      if (!result) {
        return
      }

      this.total = result.total
      this.page = result.page + 1
      this.list = this.list.concat(result.rows)

      this.tips = `已加载 ${Math.min(result.page, result.total)} / ${result.total} 页，共 ${result.records} 项`
      this.loadState = result.page >= result.total ? '已加载所有项目' : '向下翻以加载更多'
    },

    // 刷新清空列表
    async refreshList() {
      this.page = 1
      this.total = 2
      this.list = []

      await this.fetchList()
    },

    // 拉取自定义应用的定义 JSON
    async fetchFormScheme() {
      const result = await this.HTTP_GET('/form/scheme', [{ id: this.formId, ver: '' }])
      const scheme = result[this.formId]
      scheme.F_Scheme = JSON.parse(scheme.F_Scheme)

      return scheme
    },

    // 拉取自定义应用需要数据源的字段的数据源
    async fetchDataSource(schemes) {
      const dsObj = {}
      for (const scheme of schemes) {
        const dsItem = await this.getSourceData(scheme)
        if (dsItem) {
          dsObj[scheme.field] = dsItem
        }
      }

      return dsObj
    },

    // 点击打开/编辑按钮
    async action(type = 'create', id = 'no') {
      switch (type) {
        default:
        case 'create':
        case 'view':
        case 'edit':
          this.NAV_TO(`./single?type=${type}&id=${id}`, this.formScheme, true)
          break

        case 'delete':
          if (!(await this.CONFIRM('删除项目', '确定要删除该项吗？', true))) {
            return
          }

          this.LOADING('提交删除中…')
          this.HTTP_POST('/form/delete', { schemeInfoId: this.formId, keyValue: id }, '删除失败').then(success => {
            this.HIDE_LOADING()
            if (!success) {
              return
            }

            this.TOAST('删除成功', 'success')
            this.refreshList()
          })
          break
      }
    },

    // 列表下拉
    pullDown() {
      this.refreshList().then(() => {
        this.$refs.list.stopPullDown()
      })
    },

    // 获取自定义应用表单项的值
    displayListItem(item, scheme) {
      const value = item[scheme.__path__]
      const field = scheme.field

      switch (scheme.type) {
        case 'currentInfo':
        case 'organize':
          switch (scheme.dataType) {
            case 'user':
              return get(this.GET_GLOBAL('user'), `${value}.name`, '')
            case 'department':
              return get(this.GET_GLOBAL('department'), `${value}.name`, '')
            case 'company':
              return get(this.GET_GLOBAL('company'), `${value}.name`, '')
            default:
              return value || ''
          }

        case 'radio':
        case 'select':
          const selectItem = this.dataSource[field].find(t => t.value === value)
          return get(selectItem, 'text', '')

        case 'checkbox':
          if (!value || value.split(',').length <= 0) {
            return ''
          }
          const checkboxItems = value.split(',')
          return this.dataSource[field]
            .filter(t => checkboxItems.includes(t.value))
            .map(t => t.text)
            .join('，')

        case 'datetime':
          if (!value) {
            return ''
          }
          return moment(value).format(Number(scheme.dateformat) === 0 ? 'YYYY年 M月 D日' : 'YYYY-MM-DD HH:mm')

        default:
          return value || ''
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/common/css/customlist.less';
</style>
