<template>
	<div style="height:100%;padding: 10px">
		<!-- 表格主题 -->
		<Table
			:columns="formatedColumns"
			:data="currentData"
			:loading="loading"
			:ref="name"
			@on-selection-change="seletionChange"
			@on-drag-drop="onDragDrop"
			:size="size"
			:height="height"
			:width="width"
			:stripe="stripe"
			:border="border"
			:show-header="showHeader"
			:disabled-hover="disabledHover"
			:row-class-name="rowClassName"
			:no-data-text="noDataText"
			:max-height="maxHeight"
			:draggable="draggable"
			:tooltip-theme="tooltipTheme"
			:row-key="rowKey"
		>
			<template slot="loading">
				<Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
				<div>Loading</div>
			</template>
		</Table>
		<!-- 工具栏 -->
		<div class="tools" v-if="toolbar || page">
			<!-- 按钮工具栏 -->
			<Toolbar
				@on-refresh="getData"
				@on-print="print"
				@on-export="exportTable"
				:option="toolbar"
				:columns="columns"
				:dicts="dicts"
				:buttonSize="toolbarButtonSize"
				@fastquery="fastquery"
				v-if="toolbar"
			></Toolbar>
			<!-- 分页工具栏 -->
			<Page
				v-if="page"
				:total="pager.recordCount"
				show-sizer
				show-elevator
				show-total
				placement="top"
				:page-size="pager.pageSize"
				:page-size-opts="pageSizeOpts"
				id="pager"
				@on-change="pageChange"
				@on-page-size-change="pageSizeChange"
			></Page>
		</div>
		<Modal v-model="showPhotoModal" title="大图" width="432">
			<img :src="photoPath" alt style="width:400px" />
			<div slot="footer">
				<Button type="default" @click="showPhotoModal = false">关闭</Button>
			</div>
		</Modal>
		<Modal v-model="showQRModal" title="二维码" width="432">
			<QrcodeVue :value="qrcode" :size="400">
				<div slot="footer">
					<Button type="default" @click="showQRModal = false">关闭</Button>
				</div>
			</QrcodeVue>
		</Modal>
		<Modal v-model="exportModal" title="导出" width="432">
			<Form :model="exportObj" label-position="right" ref="formData" :label-width="80">
				<FormItem label="模式">
					<RadioGroup v-model="exportObj.state">
						<Radio label="0">全表</Radio>
						<Radio label="1">当前页</Radio>
					</RadioGroup>
				</FormItem>
				<FormItem label="条目上限" v-if="exportObj.state==='0'">
					<Slider
						v-model="exportObj.max"
						show-input
						:max="pager.recordCount?pager.recordCount:5000"
						style="width:100%;"
					></Slider>
				</FormItem>
			</Form>
			<div slot="footer">
				<Button type="default" @click="exportModal = false">关闭</Button>
				<Button type="primary" @click="doExport">导出</Button>
			</div>
		</Modal>
	</div>
</template>
<script>
import Toolbar from "./toolbar";
import columnsFormat from "./columnsFormat";
import dataFormat from "./dataFormat";
import exportExcel from "./exportExcel.js";
import QrcodeVue from 'qrcode.vue';
const TYPES = ["string", "number", "boolean", "date"];
import { tools } from 'hq-tools';
import lodash from 'lodash';
export default {
	name: "HongqiTable",
	components: {
		Toolbar,
		QrcodeVue
	},
	data() {
		return {
			//分页实体，与后端相对应
			pager: {
				pageSize: Number(window.localStorage.getItem(this.name + "pageSize")) ? Number(window.localStorage.getItem(this.name + "pageSize")) : 10,
				nowPage: 1,
				recordCount: 10,
				exhibitDatas: [],
				data: []
			},
			//工具栏传出的快速查询选项
			toolBarFast: [],
			//异步翻译的字典
			asyncDicts: {},
			//读取中视觉控制
			loading: false,
			formatedColumns: [],
			//实际用于显示的数据
			currentData: [],
			//大图的src
			photoPath: "",
			//大图模态框toggle
			showPhotoModal: false,
			//二维码的code
			qrcode: "",
			//大图模态框toggle
			showQRModal: false,
			//导出模态款
			exportModal: false,
			exportObj: {
				state: "0",
				max: 5000
			},
			//自定义表头的显示与排序控制
			sortObj: window.localStorage.getItem(this.name + "sortObj")
				? JSON.parse(window.localStorage.getItem(this.name + "sortObj"))
				: {}
		};
	},
	computed: {
		exportColumns() {
			return this.formatedColumns
				.filter((item, index) => !(TYPES.indexOf(item.type) < 0 || !item.export))
				.map(item => {
					return {
						codeTable: item.codeTable ? item.codeTable : {},
						columnAlign: item.align ? item.align : "center",
						columnId: item.key,
						columnTitle: item.title,
						dataType: item.type ? item.type : "string",
						format: item.format
							? item.format
							: item.type === "date"
								? "yyyy-MM-dd HH:mm:ss"
								: "",
						subtotal: this.subTotal ? true : false,
						subtotalName: this.subTotal ? this.subTotal : ''
					};
				});
		},
		exportURL() {
			if (this.exportExcel && typeof this.exportExcel === 'string') {
				return this.exportExcel;
			} else {
				let str = this.loadURL.match(/pager\w+|pager/)[0];
				return this.loadURL.replace(str, str + "Export");
			}
		}
	},
	mounted: function () {
		//获取之前选择的每页长度；
		if (!this.page) {
			this.pager.pageSize = 100000;
		}
		this.sortObj = window.localStorage.getItem(this.name + "sortObj")
			? JSON.parse(window.localStorage.getItem(this.name + "sortObj"))
			: {};
	},
	watch: {
		value: function () {
			this.pager.externalParameters = this.externalParameters;
			this.pager.externalObj = this.externalObj;
			if (this.value) {
				this.getData();
			}
		}
	},
	methods: {
		showPhoto(params) {
			this.photoPath = params.row.photoPath;
			this.showPhotoModal = true;
		},
		showQRCode(params) {
			this.qrcode = params;
			this.showQRModal = true;
		},
		//按钮点击事件
		btnOnClick(name, params) {
			params.origin = this.data
				? this.data[params.index]
				: this.pager.exhibitDatas[params.index];
			params.origin = params.origin ? params.origin : {};
			this.$emit("btnclick", {
				name: name,
				params: params
			});
			this.$emit("on-btn-click", {
				name: name,
				params: params
			});
		},
		//Td点击事件
		tdOnClick(name, params) {
			params.origin = this.data
				? this.data[params.index]
				: this.pager.exhibitDatas[params.index];
			params.origin = params.origin ? params.origin : {};
			this.$emit("on-td-click", {
				name: name,
				params: params
			});
		},
		//翻页
		pageChange: function (nowPage) {
			this.pager.nowPage = nowPage;
			this.getData();
		},
		//改变页大小
		pageSizeChange: function (pageSize) {
			this.pager.pageSize = pageSize;
			this.getData();
		},
		//远程获取数据
		getData: function () {
			this.formatedColumns = columnsFormat(
				this.columns,
				this.dicts,
				this.asyncDicts,
				this.sortObj,
				{
					onBtnClick: this.btnOnClick,
					showPhoto: this.showPhoto,
					showQRCode: this.showQRCode
				},
				this
			);
			this.pager.fastQueryParameters = [...this.fastQueryParameters, ...this.toolBarFast];
			if (!this.loadURL || tools.trim(this.loadURL) === "") {
				this.currentData = dataFormat(
					this.data.filter(item => !item._subtotal_row),
					this.columns,
					this.asyncDicts,
					this
				);
				this.$emit("input", false);
				this.$emit("on-load-success", false);
				this.seletionChange([]);
				this.loading = false;
				return;
			}
			this.pager.exhibitDatas = [];
			this.loading = true;
			this.$http
				.getByPager(this.loadURL, this.pager, this)
				.then(pager => {
					if (!pager.exhibitDatas) {
						pager.exhibitDatas = [];
					}
					this.pager = Object.assign(this.pager, {
						exhibitDatas: pager.exhibitDatas,
						nowPage: pager.nowPage,
						pageCount: pager.pageCount,
						pageSize: pager.pageSize,
						recordCount: pager.recordCount
					});
					window.localStorage.setItem(
						this.name + "pageSize",
						pager.pageSize
					);
					//return this.currentData = pager.exhibitDatas;
					this.currentData = dataFormat(
						this.pager.exhibitDatas,
						this.columns,
						this.asyncDicts,
						this
					);
					if (this.dataLoaded && typeof this.dataLoaded === 'function') {
						this.dataLoaded(this.currentData);
					}
				})
				.catch(error => {
					this.currentData = [];
					console.error(error);
				})
				.then(data => {
					this.seletionChange([]);
					this.$emit("input", false);
					this.loading = false;
				});
		},
		//打印
		print() {
			exportExcel(
				this.columns,
				this.$refs[this.name],
				this.name,
				"print",
				this
			);
		},
		//导出
		exportTable: function () {
			this.exportObj.state = "0";
			this.exportObj.max = this.pager.recordCount;
			this.exportModal = true;
			return;
		},
		//执行导出
		doExport() {
			this.$Message.info("开始导出");
			this.$http.axios
				.post(
					this.exportURL,
					{
						exportAllData:
							this.exportObj.state === "1" ? false : true,
						exportColumns: this.exportColumns,
						exportFileName: this.exportFileName
							? this.exportFileName
							: this.name,
						externalObj: this.pager.externalObj,
						externalParameters: this.pager.externalParameters,
						fastQueryExpression: "",
						fastQueryParameters: this.pager.fastQueryParameters,
						maxRecorderCount:
							this.exportObj.state === "1"
								? 5000
								: this.exportObj.max,
						nowPage:
							this.exportObj.state === "1"
								? this.pager.nowPage
								: 1,
						pageSize: this.pager.pageSize
					},
					{ responseType: "arraybuffer" }
				)
				.then(response => {
					//console.log(response);
					let url = window.URL.createObjectURL(
						new Blob([response.data])
					);
					let link = document.createElement("a");
					link.style.display = "none";
					link.href = url;
					link.setAttribute(
						"download",
						(this.exportFileName
							? this.exportFileName
							: this.name) + ".xlsx"
					);

					document.body.appendChild(link);
					link.click();
				})
				.catch(err => {
					console.error(err);
				});
		},
		//快速查询
		fastquery(fastqueryParams) {
			this.toolBarFast = fastqueryParams;
			this.getData();
		},
		//复选框
		seletionChange(selection) {
			this.$emit("selection", selection);
		},
		setSortObj(sortObj) {
			this.sortObj = sortObj;
			window.localStorage.setItem(
				this.name + "sortObj",
				JSON.stringify(this.sortObj)
			);
		},
		onDragDrop(index1, index2) {
			this.$emit('on-drag-drop', index1, index2);
		},
		//合计
		handleSummary({ columns, data }) {
			let sums = {};
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[column.key] = {
						key: column.key,
						value: this.subtotal
					}
				} else if (column.type === 'selection') {
					sums[column.key] = {
						key: column.key,
						value: ''
					};
				} else if (column.subtotal) {
					sums[column.key] = {
						key: column.key,
						value: lodash.sumBy(data.filter(item => !isNaN(item[column.key])), column.key)
					}
				} else {
					sums[column.key] = {
						key: column.key,
						value: ''
					};
				}
			})
			return sums;
		}
	},
	beforeDestroy() {
		this.pager = null
		this.asyncDicts = null
		this.formatedColumns = null
		this.currentData = null
		this.sortObj = null
		this.photoPath = null
		this.exportObj = null
	},
	props: {
		//表名，全应用必须唯一
		name: {
			type: String,
			default() {
				return "table";
			}
		},
		//是否展示序号
		index: {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.index;
			}
		},
		//是否生成复选框
		selection: {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.selection;
			}
		},
		//下载excel的地址
		exportExcel: {
			type: Boolean | String,
			default() {
				return this.$HqComponents.hongqiTable.exportExcel;
			}
		},
		//列定义
		columns: {
			type: Array,
			default() {
				return [];
			}
		},
		//字典对象
		dicts: {
			type: Object,
			default() {
				return {};
			}
		},
		//异步数据加载地址
		loadURL: {
			type: String,
			default() {
				return null;
			}
		},
		//数据源，优先级高于异步加载
		data: {
			type: Array,
			default() {
				return null;
			}
		},
		//用于使用快速查询参数作为查询条件的场合
		fastQueryParameters: {
			type: Array,
			default() {
				return [];
			}
		},
		//附加上传的参数
		externalParameters: {
			type: Array,
			default() {
				return [];
			}
		},
		//附加上传的参数
		externalObj: {
			type: Object,
			default() {
				return {};
			}
		},
		//加载控制字
		value: {
			type: Boolean,
			default() {
				return false;
			}
		},
		//是否显示分页
		page: {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.page;
			}
		},
		pageSizeOpts: {
			type: Array,
			default() {
				return this.$HqComponents.hongqiTable.pageSizeOpts;
			}
		},
		//是否显示工具栏
		toolbar: {
			type: Boolean | Array,
			default() {
				return this.$HqComponents.hongqiTable.toolbar;
			}
		},
		'toolbarButtonSize': {
			type: 'small' | 'default' | 'large',
			default() {
				return this.$HqComponents.hongqiTable.toolbarButtonSize;
			}
		},
		//导出文件名
		exportFileName: {
			type: String,
			default() {
				return null;
			}
		},
		//表格尺寸
		size: {
			type: String,
			default() {
				return this.$HqComponents.hongqiTable.size;
			}
		},
		//是否显示表头工具
		headerTool: {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.headerTool;
			}
		},
		//表格高度
		height: {
			type: Number,
			default() {
				return this.$HqComponents.hongqiTable.height;
			}
		},
		//表格最大高度，单位 px，设置后，如果表格内容大于此值，会固定表头
		maxHeight: {
			type: Number,
			default() {
				return this.$HqComponents.hongqiTable.maxHeight;
			}
		},
		//是否小计
		subtotal: {
			type: String | Boolean,
			default() {
				return this.$HqComponents.hongqiTable.subtotal;
			}
		},
		//是否显示间隔斑马纹
		stripe: {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.stripe;
			}
		},
		//是否显示纵向边框
		border: {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.border;
			}
		},
		//是否显示表头
		showHeader: {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.showHeader;
			}
		},
		width: {
			type: Number | String,
			default() {
				return this.$HqComponents.hongqiTable.width;
			}
		},
		//禁用鼠标悬停时的高亮
		disabledHover: {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.disabledHover;
			}
		},
		//行的 className 的回调方法，传入参数：,row：当前行数据,index：当前行的索引
		'rowClassName': {
			type: Function,
			default() {
				return this.$HqComponents.hongqiTable.rowClassName;
			}
		},
		//数据为空时显示的提示内容
		'noDataText': {
			type: String,
			default() {
				return this.$HqComponents.hongqiTable.noDataText;
			}
		},
		//是否开启拖拽调整行顺序，需配合 @on-drag-drop 事件使用
		'draggable': {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.draggable;
			}
		},
		//列使用 tooltip 时，配置它的主题，可选值为 dark 或 light
		tooltipTheme: {
			type: String,
			default() {
				return this.$HqComponents.hongqiTable.tooltipTheme;
			}
		},
		//是否强制使用内置的 row-key，开启后可能会影响性能
		rowKey: {
			type: Boolean,
			default() {
				return this.$HqComponents.hongqiTable.rowKey;
			}
		},
		dataLoaded: {
			type: Function,
			default() {
				return () => { }
			}
		}
	}
};
</script>

<style scope>
.table table {
	width: 100% !important;
}
.tools {
	position: relative;
	margin-top: 10px;
	text-align: right;
	height: 40px;
}
.tools #pager,
.tools #toolsContainer {
	display: inline-block;
}
.index-cell div {
	padding: 2px;
	text-align: center;
	width: 100%;
}
.ivu-table th {
	text-overflow: clip !important;
}
.ivu-page-options-sizer .ivu-select-dropdown {
	width: 100px !important;
}
.demo-spin-icon-load {
	animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
	from {
		transform: rotate(0deg);
	}
	50% {
		transform: rotate(180deg);
	}
	to {
		transform: rotate(360deg);
	}
}
</style>