<template>
  <div class="query-list-page" :style="{height: queryList.height ? 'auto' : listPageHeight}">
    <query-form
      v-show="!(queryForm.show === false)"
      ref="queryForm"
      :query-form="queryForm"
      :left-span="queryForm.leftSpan"
      :query-list="queryList"
      :before-query="queryForm.beforeQuery"
      :can-query="canQuery"
      @query="query"
      @queryExport="queryExport"
      @disableQuery="disableQuery"
      @enableQuery="enableQuery"
    />
    <el-card v-loading="loading">
      <el-table
        ref="table2"
        highlight-current-row
        stripe
        border
        :data="queryList.data"
        size="medium"
        :header-cell-style="headerCellStyle"
        :default-sort="queryList.defaultSort"
        @row-click="onRowClick"
        @select="onSelect"
        @select-all="onSelectAll"
        @selection-change="onSelectionChange"
      >
        <el-table-column v-if="queryList.selectCheckShow" type="selection" width="55" />
        <el-table-column v-if="queryList.indexShow" type="index" width="50" />
        <el-table-column v-if="queryList.radioShow" :label="`#${$t('global.select')}`" width="60">
          <template slot-scope="scope">
            <el-radio v-model="choose" :label="scope.row">{{ `` }}</el-radio>
          </template>
        </el-table-column>
        <template v-for="(column, index) in queryList.columns">
          <el-table-column
            v-if="checkColumnTyep(column, 'basic')"
            :key="index"
            :prop="column.prop"
            :label="column.title"
            :width="column.width"
            show-overflow-tooltip
            :sortable="column.sortable"
          />
          <el-table-column
            v-else-if="checkColumnTyep(column, 'basicText')"
            :key="index"
            :label="column.title"
            :width="column.width"
            :sortable="column.sortable"
          >
            <template slot-scope="scope">
              <span class="hideOutContent">{{ column.columnValue(scope.row, scope.$index) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="checkColumnTyep(column, 'tag')"
            :key="index"
            :label="column.title"
            :width="column.width"
            :sortable="column.sortable"
          >
            <template slot-scope="scope">
              <el-tag v-if="column.columnValue(scope.row, scope.$index)" :type="column.tagType(scope.row, scope.$index)">{{ column.columnValue(scope.row, scope.$index) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="checkColumnTyep(column, 'replicText')"
            :key="index"
            :label="column.title"
            :width="column.width"
            :sortable="column.sortable"
          >
            <template slot-scope="scope">
              <span>{{ column.columnValue(scope.row, scope.$index) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="checkColumnTyep(column, 'tagMore')"
            :key="index"
            :label="column.title"
            :width="column.width"
            :sortable="column.sortable"
          >
            <template slot-scope="scope">
              <template v-for="tag in column.columnValue(scope.row)">
                <el-tag
                  :key="tag"
                  :type="column.tagType(scope.row, scope.$index)"
                  style="margin-right: 10px; margin-bottom: 5px;"
                >{{ tag }}</el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="checkColumnTyep(column, 'formatter')"
            :key="index"
            :prop="column.prop"
            :label="column.title"
            :formatter="column.formatter"
            :sortable="column.sortable"
          />
          <el-table-column
            v-else-if="checkColumnTyep(column, 'button') && !(column.hide && column.hide(column))"
            :key="index"
            :label="column.title"
            :width="column.width"
          >
            <template slot-scope="scope">
              <template v-for="(button, idx) in column.buttons">
                <el-button
                  v-if="button.show === undefined ? ((button.showControl === undefined) ? true: button.showControl(scope.row)): button.show"
                  :key="idx"
                  size="mini"
                  :type="button.type ? button.type : 'primary'"
                  :disabled="isTableBtnDisabled(button, scope.$index, scope.row)"
                  @click="button.handleClick(scope.$index, scope.row) "
                >{{ getTableBtnName(button.name, scope.$index, scope.row) }}</el-button>
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div v-if="queryList.selectCheckShow" style="margin-top: 8px; margin-left: 8px;">
        <el-button
          size="mini"
          :type="'primary'"
          :disabled="!queryList.selection.length"
          @click="queryList.selectAllClick(queryList.selection)"
        >{{ $t('global.selectAdd') }}</el-button>
      </div>
      <div class="page-container " style="text-align: center; margin: 10px 0; height: 40px;">
        <el-pagination
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100] "
          :page-size="pageSize "
          layout="total, sizes, prev, pager, next, jumper "
          :total="queryList.total "
          @size-change="pageSizeChange "
          @current-change="changePage "
        />
      </div>
    </el-card>
  </div>
</template>

<script>
// import QueryForm from '@/components/QueryListPage/QueryForm'
// import { mapGetters } from 'vuex'

export default {
	components: {
		QueryForm: resolve => { require(['@/components/QueryListPage/QueryForm'], resolve); } // 懒加载
	},
	props: {
		queryForm: {
			type: Object,
			required: true
		},
		pagerConfig: {
			type: Object,
			default() {
				return {};
			}
		},
		queryList: {
			type: Object,
			required: true
		}
	},
	data() {
		return {
			loading: false,
			choose: null,
			queryData: {},
			currentpagerConfig: {},
			headerCellStyle: {
				// "background-color ": 'rgba(48, 60, 86, 1)',
				// color: 'white'
			},
			listPageHeight: '100%',
			tableHeight: 0,
			pageSize: 10,
			pageIndex: 1,
			pageOffset: 0,
			canQuery: true, // 查询按钮是否可点
			thirdQRCodeMakeUrl: 'http://s.jiathis.com/qrcode.php?url='
		};
	},
	computed: {
		globalPagerConfig: function() {
			const pagerConfig = {
				pageSize: 'pageSize',
				pageIndex: 'pageNow'
			};
			return pagerConfig;
		}
	},
	created() {
		const self = this;
		// queryList 如果没有data属性,就创建并赋值为[]
		if (!this.queryList.data) {
			this.$set(this.queryList, 'data', []);
		}
		// queryList 如果没有total属性,就创建并赋值为0
		if (!this.queryList.total) {
			this.$set(this.queryList, 'total', 0);
		}
		// 如果设置了pageConfig就使用它,否则使用globalPageConfig
		if (!this.pagerConfig) {
			this.currentpagerConfig = Object.assign({}, this.globalPagerConfig);
		} else {
			this.currentpagerConfig = Object.assign({}, this.pagerConfig);
		}
		// queryList 如果没有selection属性,就创建并赋值为[]
		if (!this.queryList.selection) {
			this.$set(this.queryList, 'selection', []);
		}
		// 给queryList添加数据重载的方法
		this.queryList.reload = function() {
			return self.commitQuery();
		};
	},
	mounted() {
		// this.commitQuery();
		// this.tableHeight = this.$refs.table2.$el.offsetHeight + 23;
	},
	methods: {
		// 根据类型显示
		checkColumnTyep(column, typeName) {
			if (column.show === false) {
				return false;
			} else if (column.isShow) {
				return column.isShow();
			}
			if (typeof column.type === 'undefined') {
				if (column.formatter instanceof Function) {
					column.type = 'formatter';
				} else {
					column.type = 'basic';
				}
			}
			// 类型是否匹配
			const typeFlag = column.type === typeName;
			return typeFlag;
		},
		isTableBtnDisabled(button, index, row) {
			if (button.isDisabled) {
				return button.isDisabled(index, row);
			} else {
				return false;
			}
		},
		// 计算列表的列为链接时显示的名称，可能为列对象的字段
		getTableBtnName(btnName, index, row) {
			if (typeof btnName.trim() === 'function') {
				return btnName(index, row);
			} else {
				return btnName;
			}
		},
		// 按钮查询
		query(queryData) {
			this.queryData = queryData;
			this.queryList.reload();
		},
		// 导出操作
		queryExport(queryData) {
			const self = this;
			self.disableQuery();
			self.queryData = queryData;
			import('@/utils/Export2Excel').then(excel => {
				const tHeader = self.queryForm.exportConfig.header;
				self.prepareExportData().then(data => {
					excel.export_json_to_excel(tHeader, data, self.queryForm.exportConfig.filename);
					self.enableQuery();
				}).catch(error => {
					self.enableQuery();
					self.$message.error(`${this.$t('error.exportFailed')}: ${error.message}`);
				});
			});
		},
		// 导出数据准备
		prepareExportData() {
			return new Promise((resolve, reject) => {
				const filterVals = this.queryForm.exportConfig.filterVals;
				this.queryExportData().then(result => {
					const list = result.list;
					const data = this.formatJson(filterVals, list);
					resolve(data);
				}).catch(error => {
					reject(error);
				});
			});
		},
		// 格式化数据列表
		formatJson(filterVals, list) {
			return list.map(v => filterVals.map(fv => {
				let keys = [];
				if (typeof (fv) === 'string') {
					keys = fv.split('.');
				} else {
					keys = fv.key.split('.');
				}
				let obj = v;
				keys.forEach(element => {
					obj = obj[element];
				});
				if (fv.type === 'date') {
					const format = fv.format || 'yyyy-MM-dd';
					return new Date(obj).Format(format);
				} else if (fv.formatter instanceof Function) {
					return fv.formatter(v);
				} else {
					return obj;
				}
			}));
		},
		// 查询需要导出的数据列表
		queryExportData() {
		},
		/**
		 * 翻页方法
		 * pageIndex: 翻页后是第几页
		 * params: 查询条件
		 **/
		changePage(pageIndex, params) {
			this.pageIndex = pageIndex;
			this.pageOffset = (this.pageIndex - 1) * this.pageSize;
			if (params) {
				// 如果是点查询按钮到这来的，不用混合分页信息，已经有默认的第一页信息
				this.queryData = params;
				// 以防pageSize改变, 重新赋值
				this.queryData[this.currentpagerConfig.pageSize] = this.pageSize;
			} else {
				// 如果是点翻页按钮到这来的，把分页信息混合到this.queryData里
				this.mixinBackPageInfoToQueryData();
			}
			// 加时间戳
			// this.queryData._time = this.$moment()._d.getTime();
			this.queryList.reload();
		},
		/**
		 * 改变分页大小回调函数，执行完毕后，iview会自动触发changePage事件，去查第一页数据
		 */
		pageSizeChange(newPageSize) {
			if (newPageSize) {
				this.pageSize = newPageSize;
				this.changePage(1, this.queryData);
			}
		},
		/**
		 * 把分页信息混合到this.queryData里
		 */
		mixinBackPageInfoToQueryData() {
			// 当前的分页信息
			const pagerParams = {
				pageSize: this.pageSize,
				pageIndex: this.pageIndex,
				pageOffset: this.pageOffset
			};
			const tempPagerParams = {};
			// 肯定要有pageSize
			tempPagerParams[this.currentpagerConfig.pageSize] = pagerParams.pageSize || this.queryData[this.currentpagerConfig.pageSize];
			// 判断使用 pageIndex 还是 pageOffset
			if (this.currentpagerConfig.pageIndex) {
				// 使用 pageIndex
				tempPagerParams[this.currentpagerConfig.pageIndex] = pagerParams.pageIndex || this.queryData[this.currentpagerConfig.pageIndex];
			} else {
				// 使用 pageOffset
				tempPagerParams[this.currentpagerConfig.pageOffset] = pagerParams.pageOffset !== undefined ? pagerParams.pageOffset : this.queryData[this.currentpagerConfig.pageOffset];
			}
			// 将分页信息封装到查询条件中
			this.queryData = { ...this.queryData, ...tempPagerParams };
		},
		preCommitQueryHandler() {
			// 填充表单
			// this.$refs.form2.initFormData(this.queryData);
			// 预设分页组件
			this.pageIndex = parseInt(this.queryData[this.currentpagerConfig.pageIndex] || this.pageIndex);
			this.pageSize = parseInt(this.queryData[this.currentpagerConfig.pageSize]);
		},
		commitQuery() {
			const self = this;
			return new Promise((resolve, reject) => {
				self.disableQuery();
				self.mixinBackPageInfoToQueryData();
				const postData = this.queryData;
				if (postData === false) {
					self.enableQuery();
					return;
				}
				if (this.queryList.query instanceof Function) {
					this.queryList.query(this.queryData).then(response => {
						self.enableQuery();
						if (this.queryList.afterQuery && this.queryList.afterQuery instanceof Function) {
							this.queryList.afterQuery(response.data);
						}

						const resultData = response.data;
						this.$set(this.queryList, 'data', resultData.list);
						this.$set(this.queryList, 'total', resultData.total);
					}).catch(error => {
						self.enableQuery();
						this.$message.error(`${this.$t('error.getListFailed')}：${error.message}`);
					});
				} else {
					const data = this.queryList.data;
					if (data) {
						self.enableQuery();
						if (this.queryList.afterQuery && this.queryList.afterQuery instanceof Function) {
							this.queryList.afterQuery(data);
						}
						this.$set(this.queryList, 'data', data);

						let total = this.queryList.total;
						if (!total) {
							total = this.queryList.data.length;
						}
						this.$set(this.queryList, 'total', total);
					}
				}
			});
		},
		enableQuery() {
			this.canQuery = true;
			this.loading = false;
		},
		disableQuery() {
			// 禁止查询按钮
			this.canQuery = false;
			this.loading = true;
			// 清空表格的数据
			// this.queryList.data = [];
		},
		onSelect(selection, row) {
			this.queryList.onSelect && this.queryList.onSelect(selection, row);
			this.queryList.selection = selection;
		},
		onSelectAll(selection) {
			this.queryList.onSelectAll && this.queryList.onSelectAll(selection);
			this.queryList.selection = selection;
		},
		onSelectionChange(selection) {
			this.queryList.onSelectionChange && this.queryList.onSelectionChange(selection);
			this.queryList.selection = selection;
		},
		onRowClick(row) {
			this.choose = row;
		},
		currentChoose() {
			return this.choose;
		},
		refresh(flag) {
			if (flag) {
				this.commitQuery();
			}
			this.queryList.data = [...this.queryList.data];
		}
	}

};

</script>
