import DictTd from './tds/dictTd';
import SplitTd from './tds/splitTd';
import BtnInTable from './btnInTable';
import DivideLine from './divideLine';
import ColumnSorter from './column.sorter';
import QrcodeVue from 'qrcode.vue';
import lodash from 'lodash';
import { tools } from 'hq-tools';
const trueIconCofig = {
	color: 'green',
	type: 'md-checkmark'
};
const falseIconCofig = {
	color: 'red',
	type: 'md-close'
};
export default (tableColumns, dicts, asyncDicts, sortObj, clickEvent, vue) => {
	let newColumns = [];
	let flag = false;
	let columns = createColumnListWithTemplate(tableColumns);
	for (let column of columns) {
		//该列可排序
		column.sortable = column.sortable !== undefined && column.sortable !== null ? column.sortable : vue.$HqComponents.hongqiTable.allSortAble;
		flag |= column.fixed ? true : false;
		//如果没有票排列，先生成排列对象
		if (Object.keys(sortObj).length === 0) {
			for (let i in columns) {
				sortObj[columns[i].title] = {
					show: true,
					sortIndex: i
				};
			}
		}
		//列之间排列
		if (sortObj[column.title]) {
			column.sortIndex = sortObj[column.title].sortIndex;
			//显示与隐藏
			if (sortObj[column.title].show) {
				column.show = true;
			} else {
				column.show = false;
			}
		} else {
			column.sortIndex = 0;
			column.show = true;
		}
		if (column.show) {
			newColumns.push(column);
		}
	}
	newColumns = newColumns.sort(function(a, b) {
		return a.sortIndex - b.sortIndex;
	});
	let baseColumns = [];
	if (vue.index) {
		baseColumns.push({
			title: ' ',
			type: 'index',
			key: 'index',
			fixed: flag ? 'left' : null,
			minWidth: 50,
			className: 'index-cell',
			renderHeader: h => {
				if (vue.headerTool) {
					return h(ColumnSorter, {
						props: {
							columns: columns
						},
						on: {
							setSortObj: vue.setSortObj
						}
					});
				}
			}
		});
	}
	if (vue.selection) {
		baseColumns.push({
			title: ' ',
			type: 'selection',
			width: 50,
			fixed: flag ? 'left' : null,
			align: 'center'
		});
	}

	//克隆原列定义
	newColumns = baseColumns.concat(newColumns);
	newColumns = newColumns.filter(item => !item.hide);

	for (let column of newColumns) {
		column.type = column.type ? column.type : 'string';
		column.export = column.export === false ? false : true;
		//如果有render属性，无视其他配置，执行render函数
		if (column.renderFcn) {
			column.render = column.renderFcn;
			continue;
		}
		//根据type不同，渲染不同的内容
		switch (column.type) {
			//字符串
			case 'string':
				//异步翻译
				if (column.asyncTranslate) {
					let dict = asyncDicts[column.key];
					if (!dict) {
						vue.$set(asyncDicts, column.key, {});
						column.codeTable = asyncDicts[column.key];
					} else {
						column.codeTable = dict;
					}
					column.render = (h, params) => {
						return h(DictTd, {
							props: {
								value: params.row[column.key],
								dict: column.key,
								dicts: asyncDicts,
								toggle: column.toggle
							}
						});
					};
				} else if (column.splitRow) {
					//拆分换行
					let dict = dicts[column.dict];
					column.codeTable = dict;
					column.render = (h, params) => {
						return h(SplitTd, {
							props: {
								value: params.row[column.key],
								split: column.split,
								dict: column.dict,
								dicts: dicts,
								link: column.link
							},
							on: {
								onclick: function() {
									clickEvent.onBtnClick(column.key, params);
								}
							}
						});
					};
				} else if (column.dict) {
					//字典翻译
					let dict = dicts[column.dict];
					column.codeTable = dict;
					column.render = (h, params) => {
						return h(DictTd, {
							props: {
								value: params.row[column.key],
								dict: column.dict,
								dicts: dicts,
								toggle: column.toggle,
								split: column.split
							}
						});
					};
				}
				break;
			//数字型
			case 'number':
				column.render = (h, { row, index, column }) => {
					return h(
						'span',
						{
							attrs: {
								title: row[column.key]
							}
						},
						row[column.key] !== null && row[column.key] !== undefined && column.format ? tools.partition(row[column.key], column.format ? column.format : 'yyyy-MM-dd', false) : row[column.key]
					);
				};
				break;
			//布尔型
			case 'boolean':
				column.render = (h, { row, index, column }) => {
					return h('Icon', {
						props: row[column.key] === '1' || row[column.key] === true ? trueIconCofig : falseIconCofig
					});
				};
				break;
			//日期与时间
			case 'date':
				column.render = (h, { row, index, column }) => {
					return h(
						'span',
						{
							attrs: {
								title: row[column.key]
							}
						},
						row[column.key] ? tools.dateFormat(row[column.key], column.format ? column.format : 'yyyy-MM-dd') : row[column.key]
					);
				};
				break;
			//图片
			case 'img':
				column.render = (h, params) => {
					return h(
						'div',
						{
							style: {
								whiteSpace: 'nowrap'
							},
							on: {
								click() {
									clickEvent.showPhoto(params);
								}
							}
						},
						[
							h('img', {
								style: {
									width: '60px',
									cursor: 'pointer'
								},
								attrs: {
									src: params.row[column.key]
								}
							})
						]
					);
				};
				break;
			//二维码
			case 'qrcode':
				column.render = (h, params) => {
					if (params.row[column.key]) {
						return h(
							'div',
							{
								style: {
									whiteSpace: 'nowrap'
								},
								on: {
									click() {
										clickEvent.showQRCode(params.row[column.key]);
									}
								}
							},
							[
								h(QrcodeVue, {
									style: {
										cursor: 'pointer'
									},
									props: {
										value: params.row[column.key],
										size: 60
									},
									attrs: {
										src: params.row[column.key]
									}
								})
							]
						);
					}
				};
				break;
			//按钮
			case 'button':
				column.render = (h, params) => {
					return h(
						'div',
						{
							style: {
								whiteSpace: 'nowrap'
							}
						},
						getBtns(column, h, params, vue)
					);
				};
				break;
			default:
				break;
		}
	}
	//分组存放，用于两级表头
	let arr = [];
	for (let column of newColumns) {
		if (column.group) {
			let group = inArray(column);
			if (!group) {
				arr.push({
					key: column.group,
					title: column.group,
					align: 'center',
					children: [ column ]
				});
			} else {
				group.children.push(column);
				group.fixed = column.fixed;
			}
		} else {
			arr.push(column);
		}
	}

	function inArray(column) {
		for (let item of arr) {
			if (column.group == item.title) {
				return item;
				break;
			}
		}
		return null;
	}
	return arr;
};
// 获取渲染按钮的render函数数列
function getBtns(column, h, params, vue) {
	if (!column.btnOptions) {
		return [];
	}

	let arr = [];
	//如果按钮设置不是数组，转化成数组
	if (Object.prototype.toString.call(column.btnOptions) !== '[object Array]') {
		column.btnOptions = [ column.btnOptions ];
	}
	column.btnOptions.map((option, index) => {
		if (
			option.hide &&
			(function() {
				params.origin = vue.pager.exhibitDatas[params.index];
				params.origin = params.origin ? params.origin : {};
				return option.hide(params);
			})()
		) {
			return;
		}
		arr.push(
			h(
				BtnInTable,
				{
					props: getBtnStyle(option),
					style: option.style,
					nativeOn: {
						click: function() {
							vue.btnOnClick(option.name, params);
						}
					}
				},
				getBtnText(option)
			)
		);
		if (column.btnlength > index + 1) {
			arr.push(h(DivideLine));
		}
	});
	return arr;
}
//获取按钮的text
function getBtnText(option) {
	if (!option) {
		return '按钮';
	}
	return option.text ? option.text : '按钮';
}
//获取按钮的样式
function getBtnStyle(option) {
	if (!option) {
		return {};
	}
	return {
		type: option.type ? option.type : 'default',
		size: option.size ? option.size : 'small',
		icon: option.icon ? option.icon : null,
		text: getBtnText(option)
	};
}
//是否有展开项
function hasExpand(columns) {
	for (let column of columns) {
		if (column.expand) {
			return true;
		}
	}
	return false;
}

const getMinWidthByName = column => {
	return (column.title ? column.title.length : column.key.length) * 14 + 36 + 20;
};
const stringColumn = column => {
	return Object.assign(
		{
			title: column.key,
			type: 'string',
			fastqueryType: 'lk',
			align: 'center',
			minWidth: getMinWidthByName(column)
		},
		column
	);
};
const dictColumn = column => {
	return Object.assign(
		{
			title: column.key,
			type: 'string',
			fastqueryType: 'eq',
			align: 'center',
			dict: column.key,
			minWidth: getMinWidthByName(column)
		},
		column
	);
};
const numberColumn = column => {
	return Object.assign(
		{
			title: column.key,
			type: 'number',
			fastqueryType: 'range',
			align: 'right',
			format: '###,###,###,##0.00',
			minWidth: getMinWidthByName(column)
		},
		column
	);
};
const dateColumn = column => {
	return Object.assign(
		{
			title: column.key,
			type: 'date',
			fastqueryType: 'datetimerange',
			align: 'center',
			format: 'yyyy-MM-dd',
			minWidth: getMinWidthByName(column)
		},
		column
	);
};

const booleanColumn = column => {
	return Object.assign(
		{
			title: column.key,
			type: 'boolean',
			fastqueryType: 'eq',
			align: 'center',
			minWidth: getMinWidthByName(column)
		},
		column
	);
};

const imageColumn = column => {
	return Object.assign(
		{
			title: column.key,
			type: 'img',
			align: 'center',
			minWidth: getMinWidthByName(column) > 80 ? getMinWidthByName(column) : 80
		},
		column
	);
};

const qrColumn = column => {
	return Object.assign(
		{
			title: column.key,
			type: 'qrcode',
			align: 'center',
			minWidth: getMinWidthByName(column) > 80 ? getMinWidthByName(column) : 80
		},
		column
	);
};

const buttonColumn = column => {
	let result = {
		title: column.key,
		type: 'button',
		align: 'center',
		btnOptions: column.btnTempldate.map((opt, index) => {
			const tbnCofigs = {
				编辑: {
					icon: 'md-create',
					text: '编辑',
					name: 'editBtn'
				},
				删除: {
					icon: 'md-trash',
					name: 'deleteBtn',
					text: '删除'
				}
			};
			let config;
			if (typeof opt === 'string') {
				config = tbnCofigs[opt];
			} else {
				config = opt;
			}
			return {
				type: 'default',
				size: 'small',
				icon: config.icon,
				text: config.text,
				name: config.name,
				style: {
					marginRight: index + 1 === column.btnTempldate.length ? 0 : '5px'
				}
			};
		}),
		width: getMinWidthByName(column)
	};
	let width = lodash.sumBy(result.btnOptions, 'text').length * 14 + 36 + (result.btnOptions.length - 1) * 5 + result.btnOptions.length * 14 + result.btnOptions.filter(item => item.icon).length * 14;
	result.width = result.width > width ? result.width : width;
	return Object.assign(result, column);
};

export const createColumnListWithTemplate = tableColumns => {
	return tableColumns.map(column => {
		let result = column;
		switch (column.template) {
			case 'string':
				result = stringColumn(column);
				break;
			case 'dict':
				result = dictColumn(column);
				break;
			case 'number':
				result = numberColumn(column);
				break;
			case 'date':
				result = dateColumn(column);
				break;
			case 'boolean':
				result = booleanColumn(column);
				break;
			case 'img':
				result = imageColumn(column);
				break;
			case 'qrcode':
				result = qrColumn(column);
				break;
			case 'button':
				result = buttonColumn(column);
				break;
			default:
				result = column;
				break;
		}
		return result;
	});
};
