<template>
  <div class="aos-table aos-table-lease clearfix" ref="aosTableLeaseContainer">
    <div class="aos-table__explain">
      <div v-if="copyTableTemplate.operationColumn && copyTableTemplate.operationColumn.iconList && copyTableTemplate.operationColumn.iconList.length > 0">
        <span>操作列图标说明：</span>
        <span v-for="icon in copyTableTemplate.operationColumn.iconList" :key="icon.code" class="aos-table__explain-item">
          <i :class="'el-icon-'+icon.icon"></i>
          <span>：{{icon.detail ? icon.detail : icon.title}}</span>
        </span>
      </div>
      <div class="aos-table__setting">
        <el-dropdown trigger="click" :hide-on-click="false"  @command="handleSettingItem">
          <i class="el-icon-setting" title="设置操作列的显示/隐藏"></i>
          <el-dropdown-menu slot="dropdown">
            <!-- <el-dropdown-item>
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            </el-dropdown-item> -->
            <el-dropdown-item v-for="(item,index) in copyTableTemplate.tableItem" :key="item.prop">
              <el-checkbox :value="!item.hide" :checked="!item.hide" :label="item.prop" @change="handleItemTypeChange(index)">{{item.label}}</el-checkbox>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="aos-table__container">
      <el-table
        :data="data"
        ref="AosTableLease"
        stripe
        border
        highlight-current-row
        header-cell-class-name="lease-table-header"
        :height="tableHeight"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick">
        <el-table-column
          v-if="copyTableTemplate.selection && copyTableTemplate.selection.showSelection"
          type="selection"
          :selectable="selectable"
          :width="copyTableTemplate.selection.width || '50'">
        </el-table-column>
        <template v-for="item in copyTableTemplate.tableItem">
          <el-table-column
            v-if="!item.hide"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            min-width="150px"
            :resizable="((item.sortable === undefined || item.sortable === null) ? true : item.sortable)"
            :sortable="((item.sortable === undefined || item.sortable === null) ? false : item.sortable)">
            <template slot="header" slot-scope="scope">
              <div v-if="item && item.prop" class="header">
                <div :class=" { 'header-center': inlineSearch}">
                  {{ item.label }}
                </div>
                <div v-if="inlineSearch && item.header.show">
                  <template v-if="item.header.type === 'input'">
                    <el-input v-model="copySearchData[item.prop]" @change="function(data) { handleInlineSearchChange(data, item.prop)}"></el-input>
                  </template>
                  <template v-if="item.header.type === 'defdoc-lease'">
                    <aos-defdoc-lease :value="copySearchData[item.prop]" :defCode="item.defCode" :field="item.prop" :multiple="true" :collapse-tags="true" :editable="true" @change="function(data) { handleInlineSearchChange(data, item.prop)}"></aos-defdoc-lease>
                  </template>
                  <template v-if="item.header.type === 'date'">
                    <inline-date :value="copySearchData[item.prop]" @end="function(data) { handleInlineSearchChange(data, item.prop)}"></inline-date>
                  </template>
                  <template v-if="item.header.type === 'number-range'">
                    <inline-number-range :value="copySearchData[item.prop]" @change="function(data) { handleInlineSearchChange(data, item.prop)}"></inline-number-range>
                  </template>
                </div>
                <div v-if="inlineSearch && !item.header.show" style="height:32px"></div>
              </div>
            </template>
            <template slot-scope="scope" >
              <slot v-if="item.showSlot" :name="item.prop + '-slot'" :scope="scope"></slot>
              <template v-else-if="item.type === 'defdoc-lease'">
                <aos-defdoc-lease :editable="false" :value="scope.row[item.prop] || ''" :field="item.prop" :defCode="item.defCode"></aos-defdoc-lease>
              </template>
              <template v-else-if="item.type === 'ref-lease'">
                <aos-ref-lease :editable="false" :value="scope.row[item.prop] || ''" :field="item.prop" :refUrl="item.refUrl" :baseUrl="item.baseUrl" :queryParams="item.queryParams"></aos-ref-lease>
              </template>
              <template v-else-if="item.type === 'money'">
                <aos-money :editable="false" v-model="scope.row[item.prop]" :decimal="item.decimal || 2" :suffixString="item.suffixString"></aos-money>
              </template>
              <span v-else :title="scope.row[item.prop]">{{scope.row[item.prop]}}</span>
            </template>
          </el-table-column>
        </template>
        <el-table-column
          v-if="copyTableTemplate.operationColumn && copyTableTemplate.operationColumn.showOperation"
          :fixed="copyTableTemplate.operationColumn.fixed || 'right'"
          :label="copyTableTemplate.operationColumn.label || '操作'"
          :width="copyTableTemplate.operationColumn.width || '120px'"
          show-overflow-tooltip>
          <template v-if="inlineSearch" slot="header">
            <div>
              <div v-if="copyTableTemplate.operationColumn.label">{{ copyTableTemplate.operationColumn.label }}</div>
              <div v-else>操作</div>
              <div v-if="inlineSearch" style="height:32px"></div>
            </div>
          </template>
          <template slot-scope="scope">
            <div class="aos-table-operation">
              <slot v-if="copyTableTemplate.operationColumn.showOperationSlot" name="operation-slot" :scope="scope"></slot>
              <template v-if="copyTableTemplate.operationColumn.iconList && copyTableTemplate.operationColumn.iconList.length > 0">
                <i v-for="(icon,index) in copyTableTemplate.operationColumn.iconList" 
                  :key="index" 
                  class="aos-table-icon"
                  :class="'el-icon-'+icon.icon" 
                  :title="icon.title"
                  @click="handleIconClick(icon.code,scope)"></i>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          class="aos-table-pagination"
          v-if="showPagination && total > 5"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handlePrevClick"
          @next-click="handleNextClick"
          :current-page="currentPage"
          :page-sizes="[5,10,20,30,40,50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
</div>
</template>
<script>
import ElTable from '../../table';
import ElPagination from '../../pagination';
import {addResizeListener,removeResizeListener} from 'aos-element/src/utils/resize-event.js'
import debounce from 'throttle-debounce/debounce';
import InlineDate from './inline-date'
import InlineNumberRange from './inline-number-range'
export default {
  name: 'AosTableLease',
  components: {
    ElTable,
    ElPagination,
    InlineDate,
    InlineNumberRange
  },
  props:{
    // table绑定的数据
    data: {
      type: Array,
      required: true,
      default: function(){
        return []
      }
    },
    searchData: {
      type: Object,
      default: function () {
        return {}
      }
    },
    // 是否在表格的头部显示搜索
    headerSearch: {
      type: Boolean,
      default: false
    },
    // 头部搜索模板
    headerSearchTemplate: {
      type: Array,
      default: function () {
        return []
      }
    },
    // table构成列属性
    tableTemplate: {
      type: Object,
      required: true
    },
    // 是否显示分页
    showPagination: {
      type: Boolean,
      default: true
    },
    // 分页的当前页
    currentPage: {
      type: Number,
      default: 1
    },
    // 分页的页的数量
    pageSize: {
      type: Number,
      default: 10
    },
    // 当前table数据总共的数量
    total: {
      type: Number,
      default: 0
    },
    showType: {
      type: String,
      default: 'table'
    },
    fixedHead: {
      type: Boolean,
      default: false
    },
    maxTableHeight: {
      type: Number
    },
    inlineSearch: {
      type: Boolean,
      default: false
    },
    // 当使用复选框是设置复选框是否可选
    selectable: {
      type: Function,
      default: function () {
        return function () { return true }
      }
    }
  },
  data(){
    return {
      tableHeight: null,
      copySearchData: {},
      pickerOptions: {
        shortcuts: [{
          text: '本月',
          onClick(picker) {
            picker.$emit('pick', [new Date(), new Date()]);
          }
        }, {
          text: '今年至今',
          onClick(picker) {
            const end = new Date();
            const start = new Date(new Date().getFullYear(), 0);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setMonth(start.getMonth() - 6);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      checkAll: false,
      copyTableTemplate: {},
      isIndeterminate: false,
      copyTableItemObject: {}
    }
  },
  // computed: {
    // copyData: {
    //   get: function() {
    //     return this.data instanceof Array ? this.data : [];
    //   },
    //   set: function(){}
    // },
    // copyTableTemplate(){
    //   return this.tableTemplate
    // }
  // },
  watch: {
    fixedHead(val, oldVal) {
      if (val && !this.$_.isEqual(val, oldVal)) {
        if (this.maxTableHeight) {
          this.tableHeight = this.maxTableHeight;
        } else {
          addResizeListener(this.$refs.aosTableLeaseContainer.parentElement.parentElement, this.resizeTableHeight);
        }
      }
    },
    tableTemplate: {
      handler: function (val, oldVal) {
        if (val && !this.$_.isEqual(val, oldVal)) {
          this.copyTableTemplate = this.$_.cloneDeep(val);
          this.copyTableTemplate.tableItem.forEach(item => {
            this.$set(this.copyTableItemObject, item.prop, item)
            if (!item.hasOwnProperty('hide')) {
              this.$set(item, 'hide', false)
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleSettingItem () {},
    handleInlineSearchChange: function (data, prop) {
      const self = this
      self.$set(self.copySearchData, prop, data)
      let conditionStr = this.$Base64.encode(self.buildSearchCondition())
      self.$emit('search', conditionStr)
    },
    buildSearchCondition () {
      let sql = ''
      let type = ''
      Object.keys(this.copySearchData).forEach(item => {
        if (this.copyTableItemObject[item] && this.copyTableItemObject[item].header) {
          type = this.copyTableItemObject[item].header.type ? this.copyTableItemObject[item].header.type : 'default'
        }
        if (this.copySearchData[item]) {
          sql += this.sqlMaker(type)(this.copySearchData[item], this.copyTableItemObject[item].dbField)
        }
      })
      console.log('buildSearchCondition', sql)
      return sql;
    },
    sqlMaker (type) {
      let fn = ''
      switch (type) {
        case 'defdoc-lease':
          fn = function (value, dbField) {
            return " and " + dbField + " in (" + value + ")";
          }
          break;
        case 'date':
          fn = function (value, dbField) {
            let sql = ''
            if (value && Array.isArray(value)) {
              if (value[0] && value[0] !== ' ') {
                sql = " and " + dbField + " >= to_date('" + value[0] + " 23:59:59', 'yyyy-mm-dd hh24:mi:ss')";
              }
              if (value[1] && value[1] !== ' ') {
                sql += " and " + dbField + " <= to_date('" + value[1] + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss')";
              }
            } 
            return sql;
          }
          break;
        case 'number-range':
          fn = function (value, dbField) {
            let sql = ''
            if (value && Array.isArray(value)) {
              if (value[0] && value[0] !== ' ') {
                sql = " and " + dbField + " >= " + value[0];
              }
              if (value[1] && value[1] !== ' ') {
                sql += " and " + dbField + " <= " + value[1];
              }
            } 
            return sql;
          }
          break;
        case 'input':
          fn = function (value, dbField) {
            return " and " + dbField + " like '%" + value + "%'";
          }
          break;
        default:
          fn = function (value, dbField) {
            return " and " + dbField + " like '%" + value + "%'";
          }
          break;
      }
      return fn;
    },
    handleCheckAllChange (val) {
      const propList = []
      this.copyTableTemplate.tableItem.forEach(item => {
        item.hide = !item.hide
        propList.push(item.prop)
      })
      this.isIndeterminate = false;
    },
    handleItemTypeChange(index) {
      this.copyTableTemplate.tableItem[index].hide = !this.copyTableTemplate.tableItem[index].hide
    },
    handleItemChange (value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.copyTableTemplate.tableItem.length
      this.isIndeterminate = checkedCount > 0 && checkedCount === this.copyTableTemplate.tableItem.length
    },
    // 多选框选择事件
    handleSelectionChange(data){
      this.$emit('table-selection-change',data);
    },
    handleRowClick(row,column,event){
      this.$emit('table-row-click',row,column,event);
    },
    // 抛出操作列点击按钮
    handleIconClick(type,scope){
      this.$emit('table-'+type+'-click',scope)
    },
    // 当前数量改变
    handleSizeChange(size){
      this.$emit('table-size-change',size);
    },
    // 当前页数改变
    handleCurrentChange(page){
      this.$emit('table-current-change',page);
    },
    // 点击上一页
    handlePrevClick(page){
      this.$emit('table-prev-click',page);
    },
    // 点击下一页
    handleNextClick(page){
      this.$emit('table-next-click',page);
    },
    resizeTableHeight(){
      const self = this;
      this.$nextTick(() => {
        let boxHeight = self.$refs.aosTableLeaseContainer.parentElement.parentElement.offsetHeight;
        console.log('---- leaseTable boxHeight ----', boxHeight)
        if(boxHeight < 600){
          if(self.showPagination){
            self.tableHeight  = boxHeight - 99
          } else {
            self.tableHeight = boxHeight - 35;
          }
        } else {
          self.tableHeight  = 600;
        }
      })
    },
    handleInlineSearch () {}
  },
  created () {
    this.copySearchData = this.$_.cloneDeep(this.searchData)
  },
  mounted(){
    if(this.fixedHead){
      if (this.maxTableHeight) {
        this.tableHeight = this.maxTableHeight
      } else {
        addResizeListener(this.$refs.aosTableLeaseContainer.parentElement.parentElement,this.resizeTableHeight);
      }
    }
  },
  beforeDestroy(){
    if(this.fixedHead && !this.maxTableHeight){
      removeResizeListener(this.$refs.aosTableLeaseContainer.parentElement.parentElement,this.resizeTableHeight);
    }
  }
}
</script>

