<template>
  <div
    :class="{
      'ibps-fixed-toolbar':checkMode
    }"
    class="data-template-list"
  >
    <van-sticky>
      <van-nav-bar
        :title="generateTitle(title)"
        :left-text="$t('common.button.back')"
        :right-text="hasToolbar?rightText:''"
        left-arrow
        @click-left="onClickLeft"
        @click-right="toCheckMode()"
      />
      <van-search
        v-show="$utils.isNotEmpty(queryKey)"
        v-model="search"
        :placeholder="$utils.isNotEmpty(queryName)?'请输入'+queryName:''"
        show-action
        @search="onSearch"
      >
        <template v-if="$utils.isNotEmpty(queryColumns) && queryColumns.length >1" #left>
          <div style="width:100px;">
            <ibps-select
              v-model="queryKey"
              :options="queryColumns"
              :clearable="false"
              value-key="prop"
              @change="changeQuery"
            />
          </div>
        </template>
        <template #action>
          <van-icon name="filter-o" :class="stateActive?'active':'disactive'" @click="clickMoreSarch" />
        </template>
      </van-search>
      <!-- 设置过滤条件 -->

      <van-dropdown-menu class="menus" active-color="#3388FF">
        <van-dropdown-item
          v-if="$utils.isNotEmpty(rangeData[rootIndex].options)"
          v-model="checkFilter"
          :options="rangeData[rootIndex].options"
        />
        <van-dropdown-item disabled title-class="menu-slot-text" class="menu-left">
          <template #title>
            <label
              :class="$utils.isNotEmpty(rangeData[rootIndex].options)?null:'options-null'"
            >共{{ pagination?pagination.totalCount||rootIndex :0 }}条</label>
          </template>
        </van-dropdown-item>
        <van-dropdown-item
          class="menu-right"
          @open="onShowFieldsList('fields')"
        >
          <template #title>
            <span
              class="menu-slot-right"
              size="small"
            >
              <van-icon name="password-view" class="custom-icon" /> 显示字段
            </span>
          </template>
        </van-dropdown-item>
      </van-dropdown-menu>
      <!-- <drop-menu
        ref="dropMenu"
        :async="async"
        :data="rangeData"
        :default-value="defaultValue"
        @change="changeFilterCondition"
      >
        <template v-slot:checks="scope">
          <div v-if="$utils.isNotEmpty(rangeData[rootIndex].options)" class="menu-slot-checks" :style="{'color':scope.color}">{{ scope.text||filterCondition }}</div>
        </template>
        <template v-slot:icon="scope">
          <span v-if="$utils.isNotEmpty(rangeData[rootIndex].options)" class="menu-slot-icon" :style="{'color':scope.color}">
            <van-icon :name="scope.icon" />
          </span>
        </template>
        <template slot="text">
          <label class="menu-slot-text" :class="$utils.isNotEmpty(rangeData[rootIndex].options)?null:'options-null'">&nbsp;&nbsp;共 {{ pagination?pagination.totalCount||rootIndex :0 }} 条</label>
        </template>
       设置显示字段 -->
      <!-- <template slot="right">
          <span class="menu-slot-right" size="small" @click="onShowFieldsList('fields')">
            <van-icon name="password-view" class="custom-icon" /> 显示字段
          </span>
        </template>
      </drop-menu> -->
    </van-sticky>
    <!-- 列 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" @load="onLoad">
        <van-cell
          v-for="(item,index) in listData"
          :key="item[idKey]+index"
          class="ibps-p-0"
        >
          <van-swipe-cell
            :right-width="manages.length>0?(manages.length*60):0"
            :on-close="onClose"
          >
            <van-checkbox-group v-model="checkedIds">
              <van-cell
                border
                style="padding:15px 16px"
                @click="onClick(item,index)"
              >
                <template slot="icon">
                  <van-checkbox
                    v-if="checkMode"
                    ref="checkboxes"
                    :name="item"
                    class="ibps-mr-10"
                  />
                </template>
                <!--标题-->
                <template #title>
                  <field-formatter
                    class="titles"
                    :label-key="labelField['name']"
                    :data="item"
                    :template-fields="templateFields"
                  />
                </template>
                <!--描述展示-->
                <template #label>
                  <template v-if="$utils.isNotEmpty(descFields)">
                    <!-- v-if="descField&&descField['name']&&item[descField['name']]" -->
                    <div
                      v-for="descField in descFields"
                      :key="descField['name']"
                      class="van-card-list__desc"
                    >
                      <span class="van-card-list__desc__title desc">{{ descField['label'] }}:</span>
                      <field-formatter
                        :label-key="descField['name']"
                        :data="item"
                        :template-fields="templateFields"
                        class="desc"
                        default-value
                      />
                    </div>
                  </template>
                </template>
              </van-cell>
            </van-checkbox-group>
            <!--删除-->
            <template #right>
              <van-button
                v-for="button in manages"
                :key="button.key"
                :type="button.type"
                :text="button.name"
                class="ibps-swipe-button"
                @click="handleAction(button,item)"
              />
            </template>
          </van-swipe-cell>
          <div v-if="listData.length-1 > index" class="ibps-blank-bar" />
        </van-cell>
      </van-list>
      <ibps-list-result-page
        :result-type="resultType"
        :error-type="errorType"
        :result-message="resultMessage"
      />
    </van-pull-refresh>
    <!--添加按钮-->
    <div v-if="$utils.isNotEmpty(addButton)" v-show="!checkMode" class="palette-button">
      <van-button
        round
        type="info"
        icon="plus"
        size="large"
        style="border-radius: 100%; width: 50px;"
        @click="handleAction(addButton)"
      />
    </div>
    <!--工具栏 -->
    <ibps-toolbar
      v-show="checkMode"
      icon-prefix="ibps-icon"
      :actions="toolbarButtons"
      :more-actions="moreToolbarButtons"
      @action-event="(button)=>handleAction(button)"
    />

    <ibps-more-search
      :show="popupShow"
      :search-forms="searchForms"
      @callback="onSearch"
      @close="callback => popupShow = callback"
      @resetForm="resetForm"
    >
      <template
        v-for="(slotForm,index) in slotForms"
        :slot="slotForm.slotName"
        slot-scope="scopeType"
      >
        <search-field
          ref="moreSearchField"
          :key="slotForm.prop+index"
          input-align="left"
          :forms="searchForms.forms"
          :item="scopeType.item"
        />
      </template>
    </ibps-more-search>
    <van-popup
      v-model="display"
      position="bottom"
      :overlay="true"
    >
      <ibps-picker-toolbar
        :cancel-button-text="$t('cancel') "
        :confirm-button-text=" $t('confirm')"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
      <div class="ibps-popup-wrapper">
        <van-checkbox-group v-model="chooseResult">
          <van-cell-group>
            <van-cell
              v-for="(item, index) in fieldsList"
              :key="item['name']+index"
              :title="item.name"
              size="large"
            >
              <template #right-icon>
                <van-checkbox :name="item.name" />
              </template>
              <!-- <van-checkbox :name="item.name">{{ item.name }}</van-checkbox> -->
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </div>
    </van-popup>

    <data-template-formrender-dialog
      ref="formrender"
      :visible="formrenderVisible"
      :params="formrenderParams"
      @callback="onRefreshCallback"
      @close="visible => formrenderVisible = visible"
    />
  </div>
</template>
<script>
import { queryDataByKey, removeFormData } from '@/api/platform/data/dataTemplate'
import { loadDataTemplateById, getDataTemplateListTemplate, buildDataTemplateFields } from '@/business/platform/data/utils'
import ButtonsConstants, { hasButton } from '@/business/platform/data/constants/buttons'

import TreeUtils from '@/utils/tree'
import ActionUtils from '@/utils/action'
import i18n from '@/utils/i18n'
import storage from '@/utils/storage'
import IbpsMoreSearch from '@/components/ibps-more-search'
import IbpsListResultPage from '@/components/ibps-list-result-page'
import IbpsToolbar from '@/components/ibps-toolbar'
import FieldFormatter from '@/business/platform/data/data-template/field-formatter'
import JTemplate from '@/business/platform/data/utils/JTemplate' // 自定义脚本
// import DropMenu from './components/dropMenu'

import SearchField from './components/search-field'

import DataTemplateFormrenderDialog from '@/business/platform/data/form/dialog'
import IbpsPickerToolbar from '@/components/ibps-picker-toolbar'

export default {
  name: 'template-list',
  components: {
    // DropMenu,
    SearchField,
    IbpsListResultPage,
    // IbpsPaletteButton,
    IbpsToolbar,
    IbpsMoreSearch,
    FieldFormatter,
    DataTemplateFormrenderDialog,
    IbpsPickerToolbar
  },
  props: {
    value: {
      type: [String, Number, Boolean, Array, Object, Date]
    }
  },

  data() {
    return {
      stateActive: false,
      popupShow: false,
      resetFields: false,
      dateFormat: 'yyyy-MM-dd',
      searchForms: {},
      firsthand: [],
      params: {},
      slotForms: [],
      paramsForm: {},
      searchParams: {},
      async: false,
      rootIndex: 0,
      filterCondition: '',

      fieldsList: [],
      display: false,
      chooseResult: [],
      checkFilter: '',
      configKey: '',
      defaultValue: [],
      rangeData: [{ options: [] }],
      search: '',
      title: '',
      listData: [],
      pagination: {},
      sorts: {},

      loading: false,
      finished: false,
      refreshing: false,
      resultType: 'init',
      errorType: null,
      resultMessage: null,

      idKey: '',
      labelField: '',
      descFields: [],

      dataTemplate: '',

      queryColumns: [],
      queryKey: '',
      queryName: '',

      isTree: false,
      templateId: '',
      templateKey: '',
      formKey: '',

      templateFields: {}, // 模版字段

      editButtons: '', // 编辑按钮
      functionButtons: [], // 功能按钮

      checkMode: false,
      checkedIds: [],

      toolbars: [],
      manages: [],

      defaultToolbars: [],
      defaultManages: [],

      isInitialization: false,

      // 表单
      formrenderVisible: false,
      formrenderParams: {}
    }
  },
  computed: {

    toolbarButtons() {
      return this.toolbars.length > 4 ? this.toolbars.slice(0, 4) : this.toolbars
    },
    moreToolbarButtons() {
      return this.toolbars.length > 4 ? this.toolbars.slice(4, this.toolbars.length) : null
    },
    hasToolbar() {
      return this.toolbars.length > 0 && this.$utils.isNotEmpty(this.listData)
    },
    addButton() {
      for (let i = 0; i < this.defaultToolbars.length; i++) {
        const button = this.defaultToolbars[i]
        if (button.button_type === 'add') {
          return button
        }
      }
      return null
    },

    editButton() {
      return this.includesFunctionButton('edit')
    },
    rightText() {
      return this.checkMode
        ? this.$t('common.button.cancel')
        : this.$t('common.button.manage')
    },
    hasScript() {
      const tmpDef = this.dataTemplate
      return !!(tmpDef && tmpDef.attrs && tmpDef.attrs.mobile_script)
    }
  },
  created() {
    const params = this.$route.params
    this.templateId = params.id
    this.loadDataTemplate(this.templateId)
  },
  mounted() {
    // if (this.isInitialization && this.hasScript) {
    //   JTemplate._onLoad(this)
    // }
  },
  methods: {
    onCancel() {
      this.display = false
    },
    onConfirm() {
      if (this.chooseResult.length === 0) {
        this.$toast('显示字段至少选择一项！')
        return
      }
      ActionUtils.initListData(this)
      this.checkedIds = []
      this.loadDataTemplate(this.templateId)
      storage.set('chooseFields', this.chooseResult)
      this.display = false
    },
    onShowFieldsList(keys) {
      this.async = !this.async
      this.configKey = keys
      this.display = true
    },
    changeFilterCondition(barItem, listItem) {
      this.checkFilter = listItem.name
      storage.set('filterCondition', listItem)
      this.onSearch()
    },
    initFilterText() {
      const listItem = storage.get('filterCondition')
      if (this.$utils.isNotEmpty(listItem)) {
        this.checkFilter = listItem.value
      } else {
        this.checkFilter = this.$utils.isNotEmpty(this.rangeData[this.rootIndex].options) ? this.rangeData[this.rootIndex].options[this.rootIndex].value : ''
      }
    },

    loadDataTemplate(id) {
      const params = {}
      loadDataTemplateById(id, params)
        .then(data => {
          this.initFormData(data)
        })
        .catch(e => {
          console.error(e)
        })
    },
    initFormData(data) {
      this.title = data['name']
      this.dataTemplate = data
      // 初始化脚本
      if (!this.isInitialization) {
        this.initJTemplate()
        this.isInitialization = true
      }
      if (this.isInitialization && this.hasScript) {
        JTemplate._onLoad(this)
      }
      i18n.setTitle(this.title)
      const template = getDataTemplateListTemplate(data)
      this.templateFields = buildDataTemplateFields(data.fields)
      this.buildKey(data, template)
      this.loadData()
      this.initFilterText()
    },
    buildKey(dataTemplate, template) {
      this.idKey = dataTemplate['unique']
      this.templateKey = dataTemplate['key']
      this.formKey = dataTemplate['attrs']['form_key']

      this.buildQuerycolumns(template['query_columns'])

      const fieldsList = template['display_columns'] ? template['display_columns'] : []
      if (this.$utils.isNotEmpty(fieldsList)) {
        this.fieldsList = fieldsList.map(i => {
          return { name: i.label }
        })
      } else {
        this.$toast('显示字段不能为空！请在PC端中配置。')
      }
      this.initOptions(fieldsList)
      const colums = []
      const chooseResult = storage.get('chooseFields')
      if (chooseResult !== undefined) {
        this.chooseResult = chooseResult
      }
      for (let i = 0; i < this.chooseResult.length; i++) {
        for (let l = 0; l < fieldsList.length; l++) {
          if (this.chooseResult[i] === fieldsList[l].label) {
            colums.push(fieldsList[l])
          }
        }
      }
      const displayColumns = colums
      const filterActions = this.$utils.isNotEmpty(template['filter_conditions']) ? template['filter_conditions'] : []
      if (this.$utils.isNotEmpty(filterActions)) {
        this.rangeData[this.rootIndex].options = filterActions.map(i => {
          return { text: i.label, value: i.key }
        })
      }
      this.initFilter(filterActions, this.rootIndex)

      if (dataTemplate.showType === 'tree') {
        this.isTree = true
        if (this.$utils.isNotEmpty(displayColumns)) {
          this.labelField = displayColumns['name_key']
          this.idKey = displayColumns['id_key']
          this.parentIdKey = displayColumns['pid_key']
        }
      } else if (dataTemplate.showType === 'list') {
        this.isTree = false
        if (this.$utils.isNotEmpty(displayColumns)) {
          // 显示字段顺序预处理
          const arr = []
          for (var i = 0; i < displayColumns.length; i++) {
            for (var l = 0; l < fieldsList.length; l++) {
              if (displayColumns[i].label === fieldsList[l].label) {
                arr[l] = fieldsList[l]
              }
            }
          }
          const columns = arr.filter(e => {
            if (e !== '' && e !== undefined) {
              return e
            }
          })

          this.labelField = columns[0] || {}
          this.descFields = columns.filter((e, i) => {
            return i > 0
          })
        }
        this.editButtons = template['buttons']['edit_buttons']
        this.functionButtons = template['buttons']['function_buttons']
        this.initToolbarAction()
      }
    },
    onSearch() {
      this.stateActive = false
      ActionUtils.initListData(this)
      this.checkedIds = []
      const moreSearchField = this.$refs.moreSearchField
      if (moreSearchField) {
        for (var i = 0; i < moreSearchField.length; i++) {
          const obj = moreSearchField[i].getParams()
          for (var j in obj) {
            if (moreSearchField[i].item.prop === j) {
              this.paramsForm[j] = obj[j]
            }
          }
        }
      }
      this.searchParams = Object.assign({}, this.paramsForm)

      this.loadData()
    },
    resetForm() {
      const moreSearchField = this.$refs.moreSearchField
      if (!moreSearchField) return
      for (var i = 0; i < moreSearchField.length; i++) {
        const def = moreSearchField[i].resetForm()
        for (var j in def) {
          this.paramsForm[j] = def[j]
        }
      }
    },
    clickMoreSarch() {
      this.popupShow = true
      this.stateActive = false
    },
    onLoad() {
      this.loadData()
    },
    loadData() {
      if (this.$utils.isEmpty(this.templateKey)) {
        return
      }
      if (this.checkFilter === '') {
        const listItem = storage.get('filterCondition')
        if (listItem !== undefined) {
          this.checkFilter = listItem.name
        }
      }
      const params = {
        key: this.templateKey,
        dynamicParams: '', // 动态参数,获取页面的值
        filterConditionKey: this.checkFilter || '' // 多个过滤条件
      }
      if (this.$utils.isNotEmpty(this.search) && this.queryKey) {
        params[this.queryKey] = this.search
      } else {
        Object.assign(params, this.searchParams)
      }
      // 加载数据
      queryDataByKey(ActionUtils.formatParams(params, this.pagination))
        .then(response => {
          const responseData = response.data
          if (this.isTree) {
            const dataResult = responseData.dataResult
            this.pagination = responseData.pageResult || {}
            this.listData = TreeUtils.transformToTreeFormat(dataResult, {
              idKey: this.idKey,
              parentIdKey: this.parentIdKey,
              childrenKey: this.childrenKey
            })

            // 初始化最顶级数据
            this.initRootTreeData(response.vars)
            this.finished = true
          } else {
            if (!this.finished) {
              // 处理数据
              ActionUtils.handleListData(this, responseData)
            }
          }
        })
        .catch(e => {
          ActionUtils.handleErrorData(this, e)
        })
    },
    // 默认显示字段列表
    initOptions(list) {
      list.forEach((val, index) => {
        if (this.configKey === '') {
          if (index < 2) {
            this.chooseResult.push(val.label)
          }
        }
      })
    },
    initFilter(list, index) {
      if (this.$utils.isNotEmpty(list)) {
        if (!this.$utils.isNotEmpty(this.defaultValue)) {
          const listItem = storage.get('filterCondition')
          if (this.$utils.isNotEmpty(listItem)) {
            const i = list.findIndex(i => i.label === listItem.text)
            this.defaultValue = [list[i].key]
          } else {
            this.defaultValue = [list[index].key]
          }
        }
      }
    },
    onRefreshCallback() {
      this.checkMode = false
      this.onRefresh()
    },
    onRefresh() {
      this.refreshing = true
      this.finished = false
      this.loading = true
      this.onSearch()
    },
    onClick(item, index) {
      if (this.checkMode) {
        this.$refs.checkboxes[index].toggle()
      } else {
        return
        // this.gotoForm({
        //   readonly: true,
        //   pkValue: item[this.idKey]
        // })
      }
    },

    generateTitle(name, title) {
      // generateTitle by vue-i18n
      return i18n.generateTitle(name, title)
    },

    onClickLeft() {
      this.$router.push({ name: 'dashboard' })
      storage.remove('filterCondition')
      storage.remove('chooseFields')
    },

    onClose(clickPosition, instance) {
      switch (clickPosition) {
        case 'left':
        case 'cell':
        case 'outside':
          instance.close()
          break
        case 'right':
          instance.open()
          break
      }
    },
    handleAction(button, data) {
      const buttonType = button.button_type || button.key
      const position = button.position
      const selection = this.getSelection(position, data)
      // 前置事件
      // this.beforeScript(command, position, selection, data, () => {
      this.readonly = false
      switch (buttonType) {
        case 'add':// 添加
          this.handleEdit('', button)
          break
        case 'edit':// 编辑
        case 'detail':// 明细
          ActionUtils.selectedRecord(selection).then((id) => {
            this.handleEdit(id, button)
          }).catch(() => { })
          break
        case 'remove':// 删除
          ActionUtils.removeRecord(selection).then((ids) => {
            this.handleRemove(ids, button)
          }).catch(() => { })

          break
        case 'sefStartFlow':// 启动自定义流程

          break
        case 'custom':// 自定义按钮
          break

        default:
          break
      }
      // })
    },
    getSelection(position, data) {
      const selection = []
      if (position === 'toolbar') {
        this.checkedIds.forEach((d) => {
          selection.push(d[this.idKey])
        })
      } else {
        selection.push(data[this.idKey])
      }
      return selection
    },
    handleEdit(pkValue, button) {
      if (this.$utils.isEmpty(this.formKey)) {
        ActionUtils.warning('请绑定表单')
        return
      }
      const buttonType = button.button_type || button.key
      // TODO: 左树右列数据处理
      // if (this.relatedTreeFields && this.$utils.isNotEmpty(this.defaultData)) {
      //   const selection = this.defaultData[this.relatedTreeFields]
      //   this.defaultFormData = action === 'add' ? this.getDefaultFormData(selection) : null
      // } else {
      //   this.defaultFormData = {}
      // }
      this.gotoForm({
        pkValue,
        readonly: buttonType === 'detail'
      })
    },
    gotoForm({ pkValue = '', readonly = true }) {
      this.formrenderParams = {
        templateKey: this.templateKey,
        formKey: this.formKey,
        pkValue: pkValue,
        toolbars: !readonly ? this.editButtons : [],
        readonly: readonly
      }
      this.formrenderVisible = true
    },
    handleRemove(ids) {
      this.removeRecord(ids, r => {
        this.checkMode = false
        this.checkedIds = []
      })
    },
    removeRecord(ids, callback) {
      removeFormData({
        ids: ids,
        idKey: this.idKey,
        formKey: this.formKey
      }).then(() => {
        this.$notify({
          type: 'success',
          message: '删除成功'
        })

        if (callback) {
          callback(true)
        }
        this.onRefresh()
      })
    },
    toCheckMode() {
      if (!this.hasToolbar) {
        return
      }
      if (this.checkMode) {
        this.show = true
        this.checkedIds = []
      }
      this.checkMode = !this.checkMode
    },
    /**
     * 初始化工具栏
     */
    initToolbarAction() {
      const functionButtons = this.functionButtons || []

      const toolbars = []
      const manages = []
      // 功能按钮
      functionButtons.forEach((rf, i) => {
        const btn = this.buildButton(rf, i)
        // 顶部按钮
        if (hasButton(rf.button_type, 'toolbar', rf.position)) {
          btn.position = 'toolbar'
          toolbars.push(JSON.parse(JSON.stringify(btn)))
        }

        // 管理列按钮
        if (hasButton(rf.button_type, 'manage', rf.position)) {
          btn.position = 'manage'
          manages.push(JSON.parse(JSON.stringify(btn)))
        }
      })

      // TODO:目前版本支持按钮
      const allowButtons = ['edit', 'detail', 'remove']

      this.defaultToolbars = toolbars
      this.toolbars = toolbars.filter((b) => {
        if (allowButtons.includes(b.button_type)) {
          return b
        }
      })

      this.defaultManages = manages
      this.manages = manages.filter((b) => {
        if (allowButtons.includes(b.button_type)) {
          return b
        }
      })
    },
    /**
     * 构建按钮
     */
    buildButton(rf, i) {
      const defaultButton = ButtonsConstants[rf.button_type] || {}
      let key = rf.button_type
      let mode
      let rightIcon
      let menus
      if (key === 'custom' || key === 'sefStartFlow') {
        key = rf.code ? rf.code : key + i
      }
      if (rf.button_type === 'export') {
        mode = 'dropdown'
        rightIcon = true
        menus = ButtonsConstants[rf.button_type].menus
      }
      let disabled = false
      let hidden = false
      if (this.hasButtonAction(key, rf)) {
        hidden = (row, data) => {
          return JTemplate._onLoadActions(this, key, rf, 'hidden', row, data)
        }
        disabled = (row, data) => {
          return JTemplate._onLoadActions(this, key, rf, 'disabled', row, data)
        }
      }
      return {
        '$index': i,
        key: key,
        button_type: rf.button_type,
        code: rf.code,
        name: rf.label || defaultButton.label,
        icon: rf.icon ? rf.icon : defaultButton.icon,
        type: this.converType(rf.style || defaultButton.type),
        deflow: rf.deflow || null,
        mode: mode,
        rightIcon: rightIcon,
        menus: menus,
        disabled: disabled,
        hidden: hidden
      }
    },
    converType(type) {
      if (type === 'primary') return 'info'
      if (type === 'info') return 'gray'
      if (type === 'success') return 'primary'
      return type
    },
    // 自定义格式数据事件
    hasButtonAction: function(key, button) {
      const buttonActionResult = JTemplate._onLoadActions(this, key, button)
      if (typeof (buttonActionResult) !== 'undefined' && buttonActionResult) {
        return true
      }
      return false
    },
    customCallback(item) {
      this.beforeSubmit('custom')
      // TODO 后面是自定义按钮的事
    },
    beforeSubmit(alias) {
      // 前置事件
      if (this.hasScript) {
        const beforSubmitResult = JTemplate._beforeSubmit(
          this,
          alias,
          this.dataTemplate
        )
        if (typeof beforSubmitResult !== 'undefined' && !beforSubmitResult) {
          return
        }
      }
    },
    includesFunctionButton(key) {
      const btns = this.functionButtons.map(button => {
        return button['button_type']
      })
      return btns.includes(key)
    },
    buildQuerycolumns(queryColumns) {
      this.searchForms.forms = []
      if (this.$utils.isEmpty(queryColumns)) {
        return
      }

      // 目前基础数据类型为4种，后续开发再补充。
      const dataType = ['varchar', 'date', 'clob', 'number']
      const arr = [
        'text',
        'number',
        'numberRange',
        'hidden',
        'select',
        'dateRange',
        'datePicker',
        'autoNumber'
      ]
      const fieldTypeArr = [
        'dateRange',
        'select',
        'dictionary',
        'number',
        'date',
        'datePicker'
      ]
      const queryColumnsData = []
      queryColumns.forEach(column => {
        const field = this.templateFields[column.name]
        let fieldType = column.field_type ? column.field_type : field.field_type
        if (!fieldType) {
          fieldType = field.type
        }

        let fieldOptions = {}
        if (!column.field_options) {
          fieldOptions = field.field_options
        }
        if (fieldType === 'date') {
          fieldType = 'datePicker'
        }

        column.fieldType = fieldType
        if (dataType.includes(field.type)) {
          if (
            field.type === 'varchar' ||
            field.type === 'clob' ||
            field.type === 'number' ||
            field.type === 'date'
          ) {
            if (!fieldTypeArr.includes(column.field_type)) {
              column.name = 'Q^' + column.name + '^SL'
            }
            if (
              column.field_type === 'select' ||
              column.field_type === 'dictionary'
            ) {
              column.name = 'Q^' + column.name + '^S'
            }
            if (column.field_type === 'datePicker') {
              column.name = 'Q^' + column.name + '^D'
            }
            if (column.field_type === 'number') {
              column.name = 'Q^' + column.name + '^DB'
            }
          }
          // TODO: 数据类型为日期类时改其余控件数据类型 PC端配置日期改其他类型控件无效果，日期类型绑定字段暂且为目前字段。
        }

        const fielder = {
          fieldType: fieldType,
          slotName: !arr.includes(fieldType)
            ? column.name + 'searchForm'
            : null,
          prop: column.name,
          label: column.label,
          fieldOptions: fieldOptions,
          options: fieldOptions.options || []
        }
        // 目前查询字段只支持text
        if (fieldType === 'text' || fieldType === 'textarea' || fieldType === 'autoNumber') {
          queryColumnsData.push(fielder)
        }
        this.searchForms.forms.push(fielder)
        if (!arr.includes(fieldType)) {
          this.slotForms.push(fielder)
        }
        this.slotForms.forEach(v => {
          this.paramsForm[v.prop] = ''
        })
      })

      // 顶部查询条件
      this.queryColumns = queryColumnsData || []
      const queryColumn = this.$utils.isNotEmpty(this.queryColumns) ? this.queryColumns[0] : {}
      this.queryKey = queryColumn.prop || ''
      this.queryName = queryColumn.label || ''
    },
    changeQuery(val, data) {
      this.queryName = data['label']
    },
    /**
     * 初始化脚本
     */
    initJTemplate() {
      const id = 'JTemplate'
      let el = document.getElementById(id)
      if (el) {
        el.parentNode.removeChild(el)
      }

      if (this.dataTemplate.attrs && this.dataTemplate.attrs.mobile_script) {
        const code = this.dataTemplate.attrs.mobile_script
        el = document.createElement('script')
        el.type = 'text/javascript'
        el.id = id
        document.body.appendChild(el)
        try {
          el.appendChild(document.createTextNode(code))
        } catch (ex) {
          el.text = code
        }
        document.body.appendChild(el)
      }
    }
  }
}
</script>
<style lang="scss">
.data-template-list {
  .options-null{
    bottom: -9px !important;
  }
  .palette-button {
    position: fixed;
    right: 30px;
    bottom: 30px;
    z-index: 500;
  }
  .titles{
    font-weight: 600;
    font-size: 16px;
    display: block;
  }
  .desc{
    font-size: 14px;
    line-height: 22px;
  }
  .active {
    color: #4688f9;
  }
  .disactive {
    color: #666;
  }
  .menus{
    .van-dropdown-menu__bar{
      height: 40px;
       background-color: #f1f4f8;
    }
    .van-dropdown-menu__item--disabled{
      justify-content: end;
      margin: 0 7px;
    }
    .van-dropdown-menu__item--disabled + .van-dropdown-menu__item{
      justify-content: flex-end;
      margin: 0 20px;
    }
    .menu-slot-right{
      color: #3388FF;
    }
  }
}
.van-dropdown-menu__item--disabled{
  .van-dropdown-menu__title::after{
    border:0
  }
}

</style>
