<template>
  <div class="aos-table clearfix" ref="aosTableContainer">
    <div class="aos-table__explain">
      <div v-if="copyTableTemplate.operationColumn && copyTableTemplate.operationColumn.iconList && copyTableTemplate.operationColumn.iconList.length > 0">
        <span class="aos-table__explain-title">操作列图标说明：</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-checkbox-group v-model="allItem" @change="handleItemChange"> -->
              <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-checkbox-group> -->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="aos-table__container">
      <el-table
        :data="data"
        ref="AosTable"
        stripe
        highlight-current-row
        :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 || '60'">
        </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="item.minWidth || '100px'"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :sortable="item.sortable"
            :align="item.align ? item.align : 'left'">
            <template slot-scope="scope" >
              <slot v-if="item.showSlot" :name="item.prop + '-slot'" :scope="scope"></slot>
              <template v-else-if="item.type === 'defdoc'">
                <aos-defdoc :value="scope.row[item.prop]" :editable="false" :defCode="item.defCode" :tag="item.tag" :multiple="item.multiple"></aos-defdoc>
              </template>
              <template v-else-if="item.type === 'rule-defdoc'">
                <aos-rule-defdoc :value="scope.row[item.prop]" :editable="false" :defCode="item.defCode" :multiple="item.multiple"></aos-rule-defdoc>
              </template>
              <template v-else-if="item.type === 'ref'">
                <aos-ref :value="scope.row[item.prop]" :editable="false" :refCode="item.refCode" :filters="item.filters" :multiple="item.multiple" :onlyTranslate="true" :translateRefValueLable="scope.row[item.prop + 'Label']"></aos-ref>
              </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>
              <template v-else-if="item.type === 'city'">
                <aos-city :templateValue="scope.row" :edit="false" :province="item.province" :city="item.city" :county="item.county"></aos-city>
              </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'">
          <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 in copyTableTemplate.operationColumn.iconList" 
                  :key="icon.code"
                  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 AosForm from '../../aos-form'
import {addResizeListener,removeResizeListener} from 'aos-element/src/utils/resize-event.js'
export default {
  name: 'AosTable',
  components: {
    ElTable,
    ElPagination,
    AosForm
  },
  props:{
    // table绑定的数据
    data: {
      type: Array,
      required: true,
      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
    },
    // 当使用复选框是设置复选框是否可选
    selectable: {
      type: Function,
      default: function () {
        return function () { return true }
      }
    }
  },
  data(){
    return {
      tableHeight: null,
      refLableList: [],
      refValueDataListObject: {},
      copyData: [],
      checkAll: false,
      copyTableTemplate: {},
      isIndeterminate: false,
      allItem: [],
      currentTableTemplate: []
    };
  },
  computed: {
    // copyTableTemplate() {
    //   return this.tableTemplate;
    // },
    refPropList () {
      let refPropList = []
      if (this.tableTemplate && this.tableTemplate.tableItem) {
        this.tableTemplate.tableItem.forEach(item => {
          if (item.type === 'ref') {
            refPropList.push(item)
          }
        });
      }
      return refPropList
    }
  },
  watch: {
    fixedHead(val, oldVal) {
      if (val && !this.$_.isEqual(val, oldVal)) {
        if (this.maxTableHeight) {
          this.tableHeight = this.maxTableHeight;
        } else {
          addResizeListener(this.$refs.aosTableContainer.parentElement.parentElement, this.resizeTableHeight);
        }
      }
    },
    data: {
      handler: function(val, oldVal) {
        if (val && Array.isArray(val) && !this.$_.isEqual(val, oldVal)) {
          this.translateRef(val)
        }
      },
      deep: true,
      immediate: true
    },
    tableTemplate: {
      handler: function (val, oldVal) {
        if (val && !this.$_.isEqual(val, oldVal)) {
          this.copyTableTemplate = this.$_.cloneDeep(val);
          this.copyTableTemplate.tableItem.forEach(item => {
            if (!item.hasOwnProperty('hide')) {
              this.$set(item, 'hide', false)
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleSettingItem () {},
    handleCheckAllChange (val) {
      const propList = []
      this.copyTableTemplate.tableItem.forEach(item => {
        item.hide = !item.hide
        propList.push(item.prop)
      })
      this.allItem = val ? propList : []
      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
        if (self.$refs && self.$refs.aosTableContainer && self.$refs.aosTableContainer.parentElement && self.$refs.aosTableContainer.parentElement.parentElement) {
          boxHeight = self.$refs.aosTableContainer.parentElement.parentElement.offsetHeight;
        }
        if(boxHeight < 600){
          if(self.showPagination){
            self.tableHeight  = boxHeight - 100
          } else {
            self.tableHeight = boxHeight - 35;
          }
        } else {
          self.tableHeight  = 600;
        }
      });
    },
    translateRef (val) {
      if (val.length > 0 && this.refPropList.length > 0) {
        // 拿到对应prop列的值
        this.refPropList.forEach(item => {
          this.$set(this.refValueDataListObject, item.prop, {})
          val.forEach((dataItem, index) => {
            if (dataItem && !dataItem[item.prop + 'Label']) {
              this.$set(dataItem, item.prop + 'Label', '');
            }
            if (!this.refValueDataListObject[item.prop].valueList) {
              this.$set(this.refValueDataListObject[item.prop], 'valueList', [])
            }
            if (!this.refValueDataListObject[item.prop].labelValueList) {
              this.$set(this.refValueDataListObject[item.prop], 'labelValueList', [])
            }
            if (!this.refValueDataListObject[item.prop].labelValueObject) {
              this.$set(this.refValueDataListObject[item.prop], 'labelValueObject', {})
            }
            if (dataItem[item.prop]) {
              if (this.refValueDataListObject[item.prop].valueList.indexOf(dataItem[item.prop]) === -1) {
                this.refValueDataListObject[item.prop].valueList.push(dataItem[item.prop])
              }
            }
          });
        });
        let allGetLabel = []
        this.refPropList.forEach(item => {
          // this.getRefLabel(item.refCode, this.refValueDataListObject[item.prop])
          allGetLabel.push(this.getRefLabel(item.refCode, this.refValueDataListObject[item.prop]))
        })
        window.Promise.allSettled(allGetLabel).then(() => {
          this.refPropList.forEach(item => {
            val.forEach((dataItem, index) => {
              if (this.refValueDataListObject[item.prop].labelValueObject[dataItem[item.prop]]) {
                dataItem[item.prop + 'Label'] = this.refValueDataListObject[item.prop].labelValueObject[dataItem[item.prop]]
              } else {
                dataItem[item.prop + 'Label'] = dataItem[item.prop]
              }
            });
          });
          this.$emit('update: data', val)
        }).catch(error => {
          console.log('error===>', error)
        })
      }
    },
    getRefLabel(refCode, refValueDataListObject) {
      if (!refCode) {
        this.$message({
          type: 'error',
          message: '参照对应的 refCode 不能为空.'
        });
        return;
      }
      const paramsData = refValueDataListObject.valueList.join(',')
      if (!paramsData) {
        return;
      }
      return this.$optimizeHttp({
        url: '/ap/ref/translate/' + refCode,
        method: 'get',
        params: {
          code: paramsData
        }
      }).then(res => {
        refValueDataListObject.labelValueList = res.data;
        refValueDataListObject.labelValueObject = this.arrayToObject(refValueDataListObject.labelValueList)
      }).catch((res) => {
        this.$message({
          type: 'error',
          message: res.data.title || '请求参照翻译出错'
        });
      });
    },
    arrayToObject (array) {
      if (!array && !Array.isArray(array))  return {}
      let object = {}
      array.forEach(item => {
        object[item.code] = item.value
      })
      return object
    },
  },
  mounted(){
    if(this.fixedHead){
      if (this.maxTableHeight) {
        this.tableHeight = this.maxTableHeight
      } else {
        addResizeListener(this.$refs.aosTableContainer.parentElement.parentElement,this.resizeTableHeight);
      }
    }
  },
  beforeDestroy(){
    if(this.fixedHead && !this.maxTableHeight){
      removeResizeListener(this.$refs.aosTableContainer.parentElement.parentElement,this.resizeTableHeight);
    }
  }

};
</script>

