<template ref="table2">
  <div class="q-data-table">
    <template v-if="hasToolbar && toolbar === ''">
      <div class="q-data-table-toolbar upper-toolbar row reverse-wrap items-center justify-end">
        <div v-if="config.title" class="q-data-table-title ellipsis auto" v-html="config.title"></div>
        <div class="row items-end">
          <button v-if="config.refresh && !refreshing" class="primary clear" @click="refresh">
            <i>refresh</i>
          </button>
          <button v-if="refreshing" class="disabled">
            <i class="animate-spin-reverse">cached</i>
          </button>
          <q-select type="toggle" v-if="config.columnPicker" v-model="columnSelection" :options="columnSelectionOptions" :static-label="$t('conponent.tableLabel.show_column')"
            class="text-right" style="margin-left: 10px"></q-select>
        </div>
      </div>
    </template>

    <div class="q-data-table-toolbar upper-toolbar row reverse-wrap items-center justify-end q-data-table-selection" v-show="toolbar === 'selection'">
      <div class="auto">
         已選擇 {{ rowsSelected }}<span v-show="rowsSelected > 1"></span> 筆資料.
        <button class="primary clear small" @click="clearSelection()">清除選擇項目</button>
      </div>
      <div>
        <slot name="selection" :rows="selectedRows"></slot>
      </div>
    </div> 

    <!-- <q-search v-model="search"></q-search> -->
    <!-- <table-filter v-if="filteringCols.length" :filtering="filtering" :columns="filteringCols" :labels="labels"></table-filter> -->
    <div v-if="config.addoption" class="q-data-table-toolbar upper-toolbar row wrap items-center">
      <div class="row sm-width-1of1 bg-width-2of3 width-2of3 items-center">
        <div class="sm-width-1of3 bg-width-1of5 width-1of5">
          <label>系統：</label>
        </div>
        <div class="sm-width-2of3 bg-width-4of5 width-4of5">
          <s-autocomplete v-model="terms" @search="search2" :id="config.model" 
            :min-characters="config.minCharacters === undefined ? 0 : config.minCharacters"
            :max-characters="config.maxCharacters === undefined ? 6 : config.maxCharacters"
            :allowOther="config.allowOther === undefined ? false : config.allowOther"
            @selected="selected2" :delay="0">
              <q-search v-model="terms"></q-search>
          </s-autocomplete>
        <!--<q-autocomplete v-model="terms" @search="search2" :min-characters="0" :max-results="6" @selected="selected2" :delay="0">
          <q-search v-model="terms"></q-search>    
        </q-autocomplete>-->
        </div>     
      </div>
    </div>

    <div v-if="!config.hideOption" class="q-data-table-toolbar upper-toolbar row wrap items-center">
      <div class="row sm-width-1of1 bg-width-2of3 width-2of3 items-center">
        <div class="sm-width-1of3 bg-width-1of5 width-1of5">
          <label>{{$t('conponent.tableLabel.keyword_selection')}}：</label> 
        </div>
        <div class="sm-width-2of3 bg-width-4of5 width-4of5">
          <q-search class="auto" v-model="search" @input="dosearch()"></q-search>
        </div>
              
      </div>
    </div>
    
    <template v-if="responsive">
      <div v-if="message" class="q-data-table-message row items-center justify-center" v-html="message"></div>
      <div v-else :style="bodyStyle" style="overflow: auto">
          <table class="q-table horizontal-delimiter responsive" ref="body">
            <tbody>
              <tr v-for="(row, index) in rows">
                <q-collapsible v-bind:label="pagination.rowsPerPage > 0 ? ((pagination.page-1)*pagination.rowsPerPage + (index+1)).toString() : (index+1).toString()">
                  <td v-if="config.selection !== undefined && config.selection">
                    <div>{{(pagination.page-1)*pagination.rowsPerPage + (index+1)}}</div>
                    <q-checkbox v-if="config.selection === 'multiple'" v-model="rowSelection[index]"></q-checkbox>
                    <q-radio v-else v-model="rowSelection[0]" :val="index"></q-radio>
                  </td>
                  <td v-else>
                    <div>{{(pagination.page-1)*pagination.rowsPerPage + (index+1)}}</div>
                  </td>
                  <td v-if="col.type !=='index' && col.display !== false" v-for="(col, index2) in cols" :data-th="col.label" :style="formatStyle(col, row[col.field], row)" 
                    :class="formatClass(col, row[col.field], row)">
                    <slot :name="'col-'+col.field" :row="row" :col="col" :data="row[col.field]">
                        <div v-if="(col.type === 'text' || col.type === 'label') && (col.modify === true || (row._add === true && col.insert === true))">
                          <input type="text" v-model="row[col.field]" :ref="'field-'+index+'-'+col._index">
                        </div>
                        <div v-if="col.type.toLowerCase() === 'password' && (col.modify === true || (row._add === true && col.insert === true))">
                          <input type="password" v-model="row[col.field]" :ref="'field-'+index+'-'+col._index">
                        </div>
                        <div v-if="col.type.toLowerCase() === 'radio' && (col.modify === true || (row._add === true && col.insert === true))">
                          <q-radio v-model="row[col.field]" :val="index" :ref="'field-'+index+'-'+col._index"></q-radio>
                        </div>
                        <div v-if="col.type.toLowerCase() === 'checkbox' && (col.modify === true || (row._add === true && col.insert === true))">
                          <q-checkbox v-model="row[col.field]"  @value="checkValue(row[col.field], 2,col,row)" 
                          @input="checkValue(row[col.field],1,col,row)" :ref="'field-'+index+'-'+col._index"></q-checkbox>
                        </div>   
                        <div v-if="col.type.toLowerCase() === 'toggle' && (col.modify === true || (row._add === true && col.insert === true))">
                          <q-toggle class="orange" v-model="row[col.field]" v-bind:value="checkValue(row[col.field],2,col,row)"
                          @input="checkValue(row[col.field],1,col,row)" :ref="'field-'+index+'-'+col._index"></q-toggle>
                        </div>
                      <div v-if="(col.type.toLowerCase() === 'date' || col.type.toLowerCase() === 'datetime' || col.type.toLowerCase() === 'time') 
                        && (col.modify === true || (row._add === true && col.insert === true))">
                        <q-datetime v-model="row[col.field]" type="date" @focus="$event.target.select()" :readonly="col.readonly" 
                        class="full-width" :min="range.min" :max="range.max" :ref="'field-'+index+'-'+col._index">
                        </q-datetime>
                      </div>
                      <div v-if="col.type.toLowerCase() === 'select' && (col.modify === true || (row._add === true && col.insert === true))">
                        <s-autocomplete v-model="row[col.field]" @search="search2" :id="col.field" 
                          :min-characters="col.minCharacters === undefined ? 0 : col.minCharacters"
                          :max-characters="col.maxCharacters === undefined ? 6 : col.maxCharacters"
                          :allowOther="col.allowOther"
                          @selected="selected" :delay="0">
                          <s-input-frame class="s-input" :stack-label="col.floatlabel" :float-label="col.floatlabel" >
                            <q-search v-model="row[col.field]" @input="$v.row[col.field].$touch()"></q-search>
                          </s-input-frame>
                        </s-autocomplete>
                      </div>
                        <div v-if="col.type.toLowerCase() === 'radioselect' && (col.modify === true || (row._add === true && col.insert === true))">
                          <q-select type="radio" v-model="row[col.field]" :options="optionObject(col.options)"></q-select>
                        </div>
                        <div v-if="col.type.toLowerCase() === 'checkboxselect' && (col.modify === true || (row._add === true && col.insert === true))">
                          <q-select type="checkbox" v-model="row[col.field]" :options="optionObject(col.options)"></q-select>
                        </div>
                        <div v-if="(col.type.toLowerCase() === 'label' && row._add === false && col.modify === false) || col.type === undefined || (col.modify === false && row._add === false)
                        || (col.insert === false && row._add === true)">
                          <div v-if="col.type.toLowerCase() === 'password'">
                            <input type="password" v-model="row[col.field]" :ref="'field-'+index+'-'+col._index">
                          </div>
                          <div v-else>
                            <span v-html="format(row, col)"></span>
                          </div>
                        </div>
                        <Expand v-if="col.type.toLowerCase() === 'expand'" :row="row" :page="thispage" :render="expandRender" :index="index" :class="expandClasses(col,col.type,col.size)"></Expand>
                    </slot>
                  </td>
                </q-collapsible>


              </tr>
            </tbody>
          </table>

      </div>
    </template>

    <div v-else class="q-data-table-container" @mousewheel="mouseWheel" @DOMMouseScroll="mouseWheel">
      <div v-if="hasHeader" class="q-data-table-head" ref="head" :style="{marginRight: scroll.vert}">
        <table-content head :rowcount="rowcount" :cols="cols" :rows="rows" :sorting="sorting" :scroll="scroll" :selection="config.selection" @sort="setSortField" 
        @checkAll="checkAll"></table-content>
      </div>
      <div class="q-data-table-body" :style="bodyStyle" ref="body" @scroll="scrollHandler">
        <div v-if="message" class="q-data-table-message row items-center justify-center" v-html="message"></div>
        <TableContentGr v-else :cols="cols" :rowcount="rowcount" :selection="config.selection" :config="config" :regularCols="regularCols"
          :rows="rows" :leftStickyColumns="leftStickyColumns" :rightStickyColumns="rightStickyColumns" :activeStyle="activeStyle"
          @mouseOver="mouseOver">
        </TableContentGr>
      </div>

      <template v-if="!message && (leftStickyColumns || config.selection)">
        <div class="q-data-table-sticky-left" ref="stickyLeft" :style="{bottom: scroll.horiz}">
          <table-sticky :no-header="!hasHeader" :rowcount="rowcount" :sticky-cols="leftStickyColumns" :cols="cols" :sorting="sorting" 
            :selection="config.selection">
            <tr v-for="(row, index) in rows" :style="activeStyle[index]" v-on:mouseover="mouseOver(index)">
              <td v-if="config.selection !== undefined && config.selection" style="text-align:right">
                <div style="display:inline;">{{(pagination.page-1)*pagination.rowsPerPage + (index+1)}}</div>
                <div style="display:inline;">
                  <q-checkbox v-if="config.selection === 'multiple'" v-model="rowSelection[index]"></q-checkbox>
                  <q-radio v-else v-model="rowSelection[0]" :val="index"></q-radio>
                </div>
              </td>
              <td v-else style="text-align:right">
                <div style="display:inline;">{{(pagination.page-1)*pagination.rowsPerPage + (index+1)}}</div>
              </td>
              <td v-if="col.type !=='index'" v-for="(col, index2) in leftCols" :style="formatStyle(col, row[col.field], row)" :class="formatClass(col, row[col.field], row)">
                <slot :name="'col-'+col.field" :row="row" :col="col" :data="row[col.field]">
                    <div v-if="(col.type.toLowerCase() === 'text' || col.type.toLowerCase() === 'label') && (col.modify === true || (row._add === true && col.insert === true))">
                      <input type="text" v-model="row[col.field]" :ref="'field-'+index+'-'+col._index">
                    </div>
                    <div v-if="col.type.toLowerCase() === 'password' && (col.modify === true || (row._add === true && col.insert === true))">
                      <input type="password" v-model="row[col.field]" :ref="'field-'+index+'-'+col._index">
                    </div>
                    <div v-if="col.type.toLowerCase() === 'radio' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-radio v-model="row[col.field]" :val="index" :ref="'field-'+index+'-'+col._index"></q-radio>
                    </div>              
                    <div v-if="col.type.toLowerCase() === 'checkbox' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-checkbox v-model="row[col.field]"  @value="checkValue(row[col.field], 2,col,row)" 
                      @input="checkValue(row[col.field],1,col,row)" :ref="'field-'+index+'-'+col._index"></q-checkbox>
                    </div>   
                    <div v-if="col.type.toLowerCase() === 'toggle' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-toggle class="orange" v-model="row[col.field]" v-bind:value="checkValue(row[col.field],2,col,row)" 
                      @input="checkValue(row[col.field],1,col,row)" :ref="'field-'+index+'-'+col._index"></q-toggle>
                    </div>
                    <div v-if="(col.type.toLowerCase() === 'date' || col.type.toLowerCase() === 'datetime' || col.type.toLowerCase() === 'time') 
                       && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-datetime v-model="row[col.field]" type="date" @focus="$event.target.select()" :readonly="col.readonly" 
                      class="full-width" :min="range.min" :max="range.max" :ref="'field-'+index+'-'+col._index">
                      </q-datetime>
                    </div>
                    <div v-if="col.type.toLowerCase() === 'select' && (col.modify === true || (row._add === true && col.insert === true))">
                      <s-autocomplete v-model="row[col.field]" @search="search2" :id="col.field" 
                        :min-characters="col.minCharacters === undefined ? 0 : col.minCharacters"
                        :max-characters="col.maxCharacters === undefined ? 6 : col.maxCharacters"
                        :allowOther="col.allowOther"
                        @selected="selected" :delay="0">
                        <s-input-frame class="s-input" :stack-label="col.floatlabel" :float-label="col.floatlabel" >
                          <q-search v-model="row[col.field]" @input="$v.row[col.field].$touch()"></q-search>
                        </s-input-frame>
                      </s-autocomplete>
                    </div>
                    <div v-if="col.type.toLowerCase() === 'radioselect' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-select type="radio" v-model="row[col.field]" :options="optionObject(col.options)"></q-select>
                    </div>
                    <div v-if="col.type.toLowerCase() === 'checkboxselect' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-select type="checkbox" v-model="row[col.field]" :options="optionObject(col.options)"></q-select>
                    </div>
                    <div v-if="(col.type.toLowerCase() === 'label' && row._add === false && col.modify === false) || col.type === undefined || (col.modify === false && row._add === false)
                    || (col.insert === false && row._add === true)">
                      <div v-if="col.type.toLowerCase() === 'password'">
                        <input type="password" v-model="row[col.field]" :ref="'field-'+index+'-'+col._index">
                      </div>
                      <div v-else>
                        <!--<span v-html="format(row, col)"></span>-->
                        <label>{{row[col.field]}}</label>
                      </div>
                    </div>
                    <Expand v-if="col.type.toLowerCase() === 'expand'" :row="row" :page="thispage" :render="expandRender" :index="index" :class="expandClasses(col,col.type,col.size)"></Expand>
                </slot>
              </td>
            </tr>
          </table-sticky>
        </div>
        <div v-if="hasHeader" class="q-data-table-sticky-left" :style="{bottom: scroll.horiz}">
          <table-sticky head :sticky-cols="leftStickyColumns" :scroll="scroll" :cols="cols" :sorting="sorting" @sort="setSortField"
            :selection="config.selection"></table-sticky>
        </div>
      </template>
      <!--<template v-if="!message && (leftStickyColumns || config.selection)">
        <TableContentLeft :cols="cols" :rowcount="rowcount" :selection="config.selection" :config="config"
          :rows="rows" :activeStyle="activeStyle" :columns="columns" :columnSelection="columnSelection" :scroll="scroll"
          @mouseOver="mouseOver" :hasHeader="hasHeader" :sorting="sorting" :pagination="pagination" :rowSelection="rowSelection">
        </TableContentLeft>
      </template>-->

      <template v-if="!message && rightStickyColumns">
        <div class="q-data-table-sticky-right" ref="stickyRight" :style="{right: scroll.vert, bottom: scroll.horiz}">
          <table-sticky :no-header="!hasHeader" right :sticky-cols="rightStickyColumns" :cols="cols" :sorting="sorting" :selection="config.selection">
            <tr v-for="(row, index) in rows" :style="activeStyle[index]" v-on:mouseover="mouseOver(index)">
              <td v-if="config.selection !== undefined && config.selection" class="invisible"></td>
              <td :colspan="cols.length - rightStickyColumns" class="invisible"></td>
              <td v-if="col.type !=='index'" v-for="(col, index2) in rightCols" :style="formatStyle(col, row[col.field], row)" :class="formatClass(col, row[col.field], row)">
                <slot :name="'col-'+col.field" :row="row" :col="col" :data="row[col.field]">
                    <div v-if="(col.type.toLowerCase() === 'text' || col.type.toLowerCase() === 'label') 
                      && (col.modify === true || (row._add === true && col.insert === true))">
                      <input type="text" v-model="row[col.field]" :ref="'field-'+index+'-'+col._index">
                    </div>
                    <div v-if="col.type.toLowerCase() === 'password' && (col.modify === true || (row._add === true && col.insert === true))">
                      <input type="password" v-model="row[col.field]" :ref="'field-'+index+'-'+col._index">
                    </div>
                    <div v-if="col.type.toLowerCase() === 'radio' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-radio v-model="row[col.field]" :val="index" :ref="'field-'+index+'-'+col._index"></q-radio>
                    </div>
                    <div v-if="col.type.toLowerCase() === 'checkbox' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-checkbox v-model="row[col.field]"  @value="checkValue(row[col.field], 2,col,row)" 
                      @input="checkValue(row[col.field],1,col,row)" :ref="'field-'+index+'-'+col._index"></q-checkbox>
                    </div>   
                    <div v-if="col.type.toLowerCase() === 'toggle' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-toggle class="orange" v-model="row[col.field]" v-bind:value="checkValue(row[col.field],2,col,row)"
                       @input="checkValue(row[col.field],1,col,row)" :ref="'field-'+index+'-'+col._index"></q-toggle>
                    </div>
                    <div v-if="(col.type.toLowerCase() === 'date' || col.type.toLowerCase() === 'datetime' || col.type.toLowerCase() === 'time') 
                       && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-datetime v-model="row[col.field]" type="date" @focus="$event.target.select()" :readonly="col.readonly" 
                      class="full-width" :min="range.min" :max="range.max" :ref="'field-'+index+'-'+col._index">
                      </q-datetime>
                    </div>
                    <div v-if="col.type.toLowerCase() === 'select' && (col.modify === true || (row._add === true && col.insert === true))">
                      <s-autocomplete v-model="row[col.field]" @search="search2" :id="col.field" 
                        :min-characters="col.minCharacters === undefined ? 0 : col.minCharacters"
                        :max-characters="col.maxCharacters === undefined ? 6 : col.maxCharacters"
                        :allowOther="col.allowOther"
                        @selected="selected" :delay="0">
                        <s-input-frame class="s-input" :stack-label="col.floatlabel" :float-label="col.floatlabel" >
                          <q-search v-model="row[col.field]" @input="$v.row[col.field].$touch()"></q-search>
                        </s-input-frame>
                      </s-autocomplete>
                    </div>
                    <div v-if="col.type.toLowerCase() === 'radioselect' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-select type="radio" v-model="row[col.field]" :options="optionObject(col.options)"></q-select>
                    </div>
                    <div v-if="col.type.toLowerCase() === 'checkboxselect' && (col.modify === true || (row._add === true && col.insert === true))">
                      <q-select type="checkbox" v-model="row[col.field]" :options="optionObject(col.options)"></q-select>
                    </div>
                    <div v-if="(col.type.toLowerCase() === 'label' && row._add === false && col.modify === false) || col.type === undefined || (col.modify === false && row._add === false)
                    || (col.insert === false && row._add === true)">
                      <div v-if="col.type.toLowerCase() === 'password'">
                        <input type="password" v-model="row[col.field]" :ref="'field-'+index+'-'+col._index">
                      </div>
                      <div v-else>
                        <!--<span v-html="format(row, col)"></span>-->
                        <label>{{row[col.field]}}</label>
                      </div>
                    </div>
                    <Expand v-if="col.type.toLowerCase() === 'expand'" :row="row" :page="thispage" :render="expandRender" :index="index" :class="expandClasses(col,col.type,col.size)"></Expand>
                </slot>
              </td>
            </tr>
          </table-sticky>
        </div>
        <div v-if="hasHeader" class="q-data-table-sticky-right" :style="{right: scroll.vert}">
          <table-sticky right head :sticky-cols="rightStickyColumns" :scroll="scroll" :cols="cols" :sorting="sorting" @sort="setSortField"
            :selection="config.selection"></table-sticky>
        </div>
      </template>
      
    </div>

    <div class="bottom-toolbar row wrap items-baseline justify-end" style="overflow-y:auto">
      <div v-for="(action,index) in actions">
        <buttonExpand :handler="action.handler" :classes="action.classes" :styles="action.style" :type="action.type" :typeDesc="action.typeDesc"
         :columns="columns" :table="data" :table2="data2" :msg="msg" :tempTable="rows" :addprops="action.columnDefault"
         :data="data" :rows="rows" :rowSelection="rowSelection" @startslide="startslide"></buttonExpand>
      </div>
    </div>
    <table-pagination v-if="pagination" :pagination="pagination" :entries="pagination.entries" :labels="labels"></table-pagination>

    <s-vueDialog ref="layoutModal" v-if="showModal" :blocking="blocking" :header="header" :footer="footer" :body="body" :type="type" :icon="icon" :custom="custom"
      :async="async" @action="action" @close="showModal = false;">
    </s-vueDialog>

    <s-addModalForm id="modal" :row="row" :columns="columns" :config="config" @saveData="saveData" ref="modal">
    </s-addModalForm>
  </div> 
</template>

<script>
// import Utils from '../utils'
import clone from '../utils/clone'
import Expand from './expand.vue'
import buttonExpand from './buttonExpand.vue'
import ColumnSelection from './plugins/column-selection/column-selection'
import Filter from './plugins/filter/filter'
import I18n from './plugins/i18n/i18n'
import Pagination from './plugins/pagination/pagination'
import Responsive from './plugins/responsive/responsive'
import RowSelection from './plugins/row-selection/row-selection'
import Scroll from './plugins/scroll/scroll'
import Sort from './plugins/sort/sort'
import StickyColumns from './plugins/sticky-cols/sticky-cols'
import Csv from '../utils/csv'
import ExportCsv from './export-csv'
import moment from 'moment'
import TableContent from './TableContent.vue'
import TableContentGr from './TableContentGr.vue'
import TableContentLeft from './TableContentLeft.vue'
export default {
  mixins: [ColumnSelection, Filter, I18n, Pagination, Responsive, RowSelection, Scroll, Sort, StickyColumns],
  props: {
    table: {
      type: Array,
      default: []
    },
    columns: {
      type: Array,
      default: []
    },
    size: {
      validator (value) {
        return this.oneOf(value, ['small', 'large', 'default'])
      }
    },
    config: {
      type: Object,
      default () {
        return {}
      }
    },
    actions: {
      type: Array,
      default () {
        return {}
      }
    },
    msg: {
      type: Object,
      default () {
        return {}
      }
    },
    apiPath: {
      type: String,
      default () {
        return ''
      }
    }
  },
  data () {
    return {
      headerstring: '{ headers: { \'Content-Type\': \'application/json\' } }',
      row: {},
      showModal: false,
      icon: '',
      header: '',
      footer: '',
      level: 2,
      terms: '',
      search: '',
      selected: false,
      toolbar: '',
      refreshing: false,
      thispage: 0,
      rows2: [],
      data: this.table,
      data2: [],
      globalLocales: [],
      pageLocales: [],
      globalI18n: [],
      active: [],
      activeStyle: [],
      rows: [],
      rowcount: false,
      range: {
        min: moment('1950-01-01T10:40:14.674Z').subtract(3, 'days').format(),
        max: moment().add(4, 'hours').add(10, 'minutes').add(1, 'month').format()// .add(1, 'month').add(1, 'year')
      }
    }
  },
  created () {
    this.init()
  },
  updated () {
  },
  computed: {
    rowStyle (index) {
      /* if (this.config.rowHeight) {
        return {height: this.config.rowHeight}
      } */
      /* var classes = ''
      if (this.active[index] === true) {
        classes = {
          'background-color': '#ffa',
          height: '60px'
        }
      }
      else {
        classes = {
          height: '60px'
        }
      } */
      return {height: '60px'}
    },
    bodyStyle () {
      // return this.config.bodyStyle || {}
      return {
        maxHeight: '500px'
      }
    },
    hasToolbar () {
      return this.config.title || this.filteringCols.length || this.config.columnPicker || this.config.refresh
    },
    hasHeader () {
      return !this.config.noHeader
    },
    expandRender () {
      let render = function () {
        return ''
      }
      for (let i = 0; i < this.columns.length; i++) {
        const column = this.columns[i]
        if (column.type && column.type === 'expand') {
          if (column.render) render = column.render
        }
      }
      return render
    }
  },
  methods: {
    padLeft (str, lenght) {
      if (str.length >= lenght) {
        return str
      }// &nbsp;
      else {
        return this.padLeft(` ` + str, lenght)
      }
    },
    optionObject (functionName) {
      var option = ''
      if (typeof done !== 'function') {
        return functionName
      }
      else {
        option = this.$emit(functionName, () => {
        })
        // console.log(option)
        return option
      }
    },
    rowss () {
      let length = this.data.length

      if (!length) {
        return []
      }

      // let rows = Utils.clone(this.data)
      // this.rows = Utils.clone(this.data)
      this.rows = clone(this.data)
      // let rows = this.data
      this.rows.forEach((row, i) => {
        row.__index = i
      })

      if (this.filtering.terms) {
        this.rows = this.filter(this.rows)
      }
      if (this.sorting.field) {
        this.sort(this.rows)
      }
      this.pagination.entries = this.rows.length
      if (this.pagination.rowsPerPage > 0) {
        this.rows = this.paginate(this.rows)
      }
      this.thispage = this.pagination.page
      this.rows2 = this.rows.slice()
      return this.rows
    },
    init () {
      var i = 0
      var flag = false
      for (i = 0; i < this.data.length; i++) {
        if (this.data[i]._modify === undefined) {
          this.data[i]._modify = false
          this.data[i]._add = false
        }
        this.data[i]._key = i
        this.data[i]._index = i + 1
        this.active[i] = false
        this.activeStyle[i] = {height: '60px'}
      }

      for (i = 0; i < this.columns.length; i++) {
        if (this.columns[i].field === '_index') {
          this.columns[i].sort = false
          this.columns[i].width = '0px'
          this.columns[i].type = 'index'
          flag = true
        }
        else if (this.columns[i].field === '_key') {
          this.columns[i].width = '0px'
          this.columns[i].type = 'index'
        }
      }
      if (flag === false) {
        var arrToInsert = [
          {
            label: '',
            field: '_index',
            sort: false,
            width: '50px',
            type: 'label'
          }
        ]
        this.insertArrayAt(this.columns, 0, arrToInsert)
      }

      for (i = 0; i < this.columns.length; i++) {
        this.columns[i]._index = i
        if (this.columns[i].type === 'checkbox' || this.columns[i].type === 'toggle') {
          for (var j = 0; j < this.data.length; j++) {
            if (this.data[j][this.columns[i].field] === undefined || this.data[j][this.columns[i].field] === '0' || this.data[j][this.columns[i].field] === '') {
              this.data[j][this.columns[i].field] = false
            }
            else if (this.data[j][this.columns[i].field] === '1') {
              this.data[j][this.columns[i].field] = true
            }
          }
        }
      }
      this.data2 = []
      this.data2 = [].concat(this.data || [])
      this.rowss()
    },
    isObjectValueEqual (a, b) {
      var aProps = Object.getOwnPropertyNames(a)
      var bProps = Object.getOwnPropertyNames(b)
      if (aProps.length !== bProps.length) {
        return false
      }
      for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i]
        if (a[propName] !== b[propName]) {
          return false
        }
      }
      return true
    },
    insertAt (array, index) {
      var arrayToInsert = Array.prototype.splice.apply(arguments, [2])
      return this.insertArrayAt(array, index, arrayToInsert)
    },
    insertArrayAt (array, index, arrayToInsert) {
      Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert))
      return array
    },
    checkAll (col, dataCheckAll) {
      for (var i = 0; i < this.rows.length; i++) {
        this.rows[i][col.field] = dataCheckAll
      }
    },
    checkValue (val, type, col, row) {
      var val2 = false
      if (type === 2) {
        if (val === true || val === 1) {
          val2 = true
        }
        else {
          val2 = false
        }
      }
      else {
        if (val === true || val === 1) {
          val2 = false
        }
        else {
          val2 = true
        }
      }
      return val2
    },
    oneOf (value, validList) {
      for (let i = 0; i < validList.length; i++) {
        if (value === validList[i]) {
          return true
        }
      }
      return false
    },
    expandClasses (cell, type, size) {
      return [
        {
          [`sce-button-` + type]: true,
          [`sce-button-` + size]: true
        }
      ]
    },
    search2 (terms, done) {
      this.$emit('search', terms, done, () => {
      })
    },
    dosearch () {
      this.$emit('dosearch', this.search, () => {
      })
    },
    selected2 (item) {
      this.$emit('selected', item, this.terms, () => {
      })
    },
    resetBody () {
      let body = this.$refs.body

      if (body) {
        body.scrollTop = 0
      }
      this.pagination.page = 1
    },
    format (row, col) {
      return col.format ? col.format(row[col.field], row) : row[col.field]
    },
    refresh (state) {
      if (state === false) {
        this.refreshing = false
      }
      else if (state === true || !this.refreshing) {
        this.refreshing = true
        this.$emit('refresh', () => {
          this.refreshing = false
        })
      }
    },
    formatStyle (col, value, row) {
      return typeof col.style === 'function' ? col.style(value) : col.style
    },
    formatClass (col, value, row) {
      if (typeof col.classes === 'function') {
        return col.classes(value)
      }
      else {
        if (col !== undefined && col._index === 2 && row._modify !== undefined && row._modify === true) {
          if (col.classes === undefined) {
            return ` column-dirty`
          }
          else {
            return col.classes + ` column-dirty`
          }
        }
        else {
          return col.classes
        }
      }
    },
    action (actionReturn) {
    },
    exportCsv (params) {
      if (params.filename) {
        if (params.filename.indexOf('.csv') === -1) {
          params.filename += '.csv'
        }
      }
      else {
        params.filename = 'table.csv'
      }

      let columns = []
      let datas = []
      if (params.columns && params.data) {
        columns = params.columns
        datas = params.data
      }
      else {
        columns = this.columns
        if (!('original' in params)) params.original = true
        datas = params.original ? this.data : this.rows
      }
      let noHeader = false
      if ('noHeader' in params) noHeader = params.noHeader

      const data = Csv(columns, datas, ',', noHeader)
      ExportCsv.download(params.filename, data)
      // this.$emit('exportCsv', ExportCsv, params.filename, data, () => {
      // })
    },
    getUpdateTable () {
      var temp = []
      var flag = false
      var selected = this.getSelected()
      for (var i = 0; i < this.data.length; i++) {
        flag = false
        for (var j = 0; j < selected.length; j++) {
          if (this.data[i]._key === selected[j]._key && selected[j]._check === true) {
            this.data[i]._check = selected[j]._check
            temp.push(this.data[i])
            flag = true
          }
        }
        if (flag === false) {
          if (this.data[i]._modify === true) {
            temp.push(this.data[i])
          }
          else if (this.data[i]._add === true) {
            temp.push(this.data[i])
          }
        }
      }
      return temp
    },
    getSelected () {
      var selected = []
      for (var i = 0; i < this.rows.length; i++) {
        var obj = Object.create(null)
        obj._key = this.rows[i]._key
        if (this.config.selection === 'multiple') {
          obj._check = this.rowSelection[i]
        }
        else {
          if (this.rowSelection.length > 0) {
            obj._check = this.rowSelection[0]
          }
          else {
            obj._check = null
          }
        }
        selected.push(obj)
      }
      return selected
    },
    getAllTable () {
      var temp = []
      var selected = this.getSelected()
      for (var i = 0; i < this.data.length; i++) {
        temp.push(this.data[i])
        for (var j = 0; j < selected.length; j++) {
          if (this.data[i]._key === selected[j]._key) {
            temp[i]._check = selected[j]._check
          }
        }
      }
      // this.$emit('getAllTable', temp, () => {
      // })
      return temp
    },
    startslide () {
      this.row = this.table[0]
      this.$refs.modal.startslide('ins', this.row)
    },
    modifyModal (row) {
      this.row = row
      this.$refs.modal.startslide('upd', this.row)
    },
    deleteRow (row) {
      this.saveData(row, 'del')
    },
    saveRow (row) {
      this.saveData(row, 'upd')
    },
    saveData (row, operation) {
      this.$emit('saveDataRow', row, operation, () => {
      })
    },
    mouseOver (index) {
      for (var i = 0; i < this.active.length; i++) {
        this.active[i] = false
        this.$set(this.activeStyle, i, {
          height: '60px'}
        )
      }
      this.active[index] = true
      this.$set(this.activeStyle, index, {
        'background-color': '#ffa',
        height: '60px'}
      )
    }
  },
  watch: {
    'pagination.page': {
      handler: function (val, oldVal) {
        this.rowss()
      }
    },
    'table.column': {
      // immediate: true,
      handler: function (val, oldVal) {
      },
      deep: true
    },
    'table.row': {
      // immediate: true,
      handler: function (val, oldVal) {
      },
      deep: true
    },
    table: {
      immediate: true,
      handler: function (val, oldVal) {
        this.data = []
        // this.data = val.slice()
        this.data = val
        this.init()
      },
      deep: false
    },
    rows: {
      handler: function (val, oldVal) {
        var flag = false
        // var index = -1
        var strName = ''
        var strValue2 = ''
        for (var j = 0; j < val.length; j++) {
          var vals = val[j]
          flag = false
          for (var i = 0; i < this.data2.length; i++) {
            if (this.data2[i]._key === vals._key) {
              // index = i
              for (strName in this.data2[i]) {
                strValue2 = this.data2[i][strName]
                if (String(vals[strName]) !== String(strValue2)) {
                  // this.$set(this.data[i], strName, vals[strName])
                  this.data[i][strName] = vals[strName]
                  flag = true
                  this.data[i]['_modify'] = flag
                  vals['_modify'] = flag
                }
              }
            }
          }

          /* if (index !== -1) {
            this.data[index]['_modify'] = flag
            vals['_modify'] = flag
          } */
          /* for (i = 0; i < this.data.length; i++) {
            if (this.data[i]._key === vals._key) {
              vals._modify = flag
              this.data[index]['_modify'] = flag
            }
          } */
        }
      },
      deep: true
    },
    sorting: {
      handler: function (val, oldVal) {
        this.sort(this.rows)
      },
      deep: true
    }
  },
  components: {
    TableContent,
    Expand,
    buttonExpand,
    Csv,
    ExportCsv,
    TableContentGr,
    TableContentLeft
  }
}
</script>

<style scoped>
.column-dirty {
  border-left:5px solid #000;
  border-left-color: red;
  padding-left: 5px;
}
q-table {
  overflow: hidden;
}

/* div table tbody tr:hover {
  background-color: #ffa;
} */

/* td, th {
  position: relative;
} */
td:hover::after,
th:hover::after {
  content: "";
  position: absolute;
  background-color: #ffa;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}
td:focus::after,
th:focus::after { 
  content: '';  
  background-color: lightblue;
  position: absolute;  
  left: 0;
  height: 10000px;
  top: -5000px;
  width: 100%;
  z-index: -1;
}

td:focus::before {
  background-color: lightblue;
  content: '';  
  height: 100%;
  top: 0;
  left: -5000px;
  position: absolute;  
  width: 10000px;
  z-index: -1;
}

.sce-button-primary {
  color: #fff;
  background-color: #2d8cf0;
  border-color: #2d8cf0;
}
.sce-button-small {
  padding: 2px 7px;
  font-size: 12px;
  border-radius: 3px;
}
.sce-button {
  display: inline-block;
  margin-bottom: 0;
  font-weight: 400;
  text-align: center;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  background-image: none;
  border: 1px solid transparent;
  white-space: nowrap;
  line-height: 1.5;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  padding: 6px 15px;
  font-size: 12px;
  border-radius: 4px;
  transition: color .2s linear,background-color .2s linear,border .2s linear;
  color: #495060;
  background-color: #f7f7f7;
  border-color: #dddee1;
}
.sce-button-error {
  color: #fff;
  background-color: #ed3f14;
  border-color: #ed3f14;
}
</style>
