<template>
	<div class="table-render-box" v-loading="loading">
		<div class="table-render" v-if="tableConfig && tableList">
			<ace-form-render
				ref="aceFormRender"
				@success="submitFormSuccess"
				:code="formCode"
			></ace-form-render>
			<div class="header">
				<div class="left">
					<h3 class="title">
						{{ config.formName }}
					</h3>
				</div>
				<div class="right">
					<div class="toolbar">
						<div
							v-if="auth.delete"
							v-show="selected.length > 0"
							class="toolbar-btn delete-btn"
						>
							<i class="toolbar-icon el-icon-delete"></i>
							删除所选
						</div>
						<div
							v-if="auth.add"
							class="toolbar-btn create-flow-btn"
							@click="addHandle"
						>
							<i class="toolbar-icon el-icon-plus"></i>
							新增
						</div>
					</div>
				</div>
			</div>
			<div class="body">
				<vxe-table
					ref="table"
					:data="tableList"
					:scroll-y="{ enabled: false }"
					stripe
					row-class-name="table-render-row-style"
					height="100%"
					:align="align"
					:size="size"
					:row-config="{ isHover: true }"
					:column-config="{ resizable: true }"
					@cell-dblclick="viewHandle"
					@checkbox-change="selectionHandle"
					:checkbox-config="{ highlight: true, range: true }"
					:border="border"
				>
					<vxe-column
						type="checkbox"
						title="选择"
						width="80"
						align="center"
					></vxe-column>
					<vxe-column
						v-for="item in tableConfig.cols"
						:key="item.objColName"
						:field="item.objColName"
						show-overflow="tooltip"
						:title="item.caption"
					></vxe-column>
					<vxe-column title="操作">
						<template slot-scope="{ row }">
							<el-link
								v-if="auth.view && isOpenFlow"
								@click="viewFlowHandle({ row: row }, $event)"
							>
								<i class="el-icon-edit-outline"></i> 查看流程
							</el-link>
							<el-link
								v-if="auth.view && !isOpenFlow"
								@click="viewHandle({ row: row })"
								><i class="el-icon-view"></i> 查看</el-link
							>
							<template v-if="auth.edit && !isOpenFlow">
								<span style="padding:0 8px"></span>
								<el-link
									type="warning"
									@click="editHandle(row, $event)">
                                    <i class="el-icon-edit-outline"></i>编辑</el-link>
							</template>
							<template v-if="auth.edit && !isOpenFlow">
								<span style="padding:0 8px"></span>
								<el-popconfirm
									title="您确定要删除此条数据？"
									@confirm="deleteHandle(row, $event)"
								>
									<el-link type="danger" slot="reference">
										<i class="el-icon-delete"></i> 删除
									</el-link>
								</el-popconfirm>
							</template>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<div class="footer">
				<div style="width:100%">
					<vxe-pager
						perfect
						:current-page.sync="queryParams.currentPage"
						:page-size.sync="queryParams.currentSize"
						:total="total"
						:page-sizes="[10, 20, 30, 50, 80, 100]"
						:layouts="[
							'PrevJump',
							'PrevPage',
							'Number',
							'NextPage',
							'NextJump',
							'Sizes',
							'FullJump',
							'Total',
						]"
						@page-change="pageChange"
					>
					</vxe-pager>
				</div>
			</div>
		</div>
		<div v-else v-show="!loading" class="table-message-box">
			<i class="aceicon aceicon-warning-circle"></i>
			<p style="margin-top:20px">
				提示：未找到表格的相关配置，需要联系管理员在【表单设计】对【{{
					config.formName
				}}】进行相关配置后方可使用。
			</p>
		</div>
	</div>
</template>

<script>
import { isAuth } from '../../../../src/utils'
export default {
	name: 'AceTableRender',
	data() {
		return {
			loading: false,
			config: {},
			tableConfig: null, //表格配置
			total: 200,
			tableList: null, //表格数据
			formConfig: null, //表单配置
			//拥有的权限
			auth: {
				add: false, //新增权限
				delete: false, //删除权限
				edit: false, //编辑权限
				view: false, //查看权限
			},
			//表格查询参数
			queryParams: {
				tableName: '',
				currentPage: 1,
				currentSize: 10,
				cols: [
					// {
					//     colName: 'NAME',
					// }
				],
			},
			selected: [], //表格已选
		}
	},
	props: {
		code: {
			type: String,
			default: '',
		},
	},
	computed: {
		formCode() {
			return this.code ? this.code : this.$route.params.code
		},
		flowCode() {
			return this.config.flowCode ? this.config.flowCode : ''
		},
		//所有的列对齐方式 	left（左对齐）, center（居中对齐）, right（右对齐）
		align() {
			return typeof this.tableConfig.config != 'undefined' &&
				this.tableConfig.config.allAlign
				? this.tableConfig.config.allAlign
				: 'left'
		},
		//表格的尺寸 medium, small, mini
		size() {
			return typeof this.tableConfig.config != 'undefined' &&
				this.tableConfig.config.size
				? this.tableConfig.config.size
				: 'small'
		},
		//是否带有边框 default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
		border() {
			return 'inner'
		},
		//是否已开启工作流
		isOpenFlow() {
			return (
				typeof this.config.flowCode != 'undefined' && this.config.flowCode != ''
			)
		},
	},
	mounted() {},
	created() {
		this.getTableConfig()
	},
	methods: {
		//提交表单成功
		submitFormSuccess() {
			//重新加载列表
			this.getTableList()
		},
		//分页发生改变
		pageChange({ type, currentPage, pageSize }) {
			if (type === 'current') {
				//当前页码发生改变
				this.queryParams.currentPage = currentPage
				//重新请求列表
				this.getTableList()
			} else {
				//每页条数发生改变
				this.queryParams.currentSize = pageSize
				//页码归1
				this.queryParams.currentPage = 1
				//重新请求列表
				this.getTableList()
			}
		},
		//查看流程
		viewFlowHandle({ row }) {
			if (!this.auth.view) {
				this.$message({
					message: '对不起，您没有查看权限！',
					type: 'warning',
				})
				return
			}
			this.$router.openTaskWindow({
				flowCode: this.flowCode,
				formId: row.id,
				params: {
					tableName: this.config.tableName,
				},
			})
		},
		//查看
		viewHandle({ row }) {
			if (!this.auth.view) {
				this.$message({
					message: '对不起，您没有查看权限！',
					type: 'warning',
				})
				return
			}
			this.$refs.aceFormRender.open('view', row.id)
		},
		//新增
		addHandle() {
			if (!this.auth.add) {
				this.$message({
					message: '对不起，您没有新增权限！',
					type: 'warning',
				})
				return
			}
			if (this.config.flowCode) {
				//判断是否开启了工作流
				//如果开启了工作流
				this.$router.openTaskWindow({
					flowCode: this.config.flowCode,
					parmas: {
						code: this.config.code,
					},
				})
			} else {
				//没有开启工作流
				this.$refs.aceFormRender.open()
			}
		},
		//编辑
		editHandle(data) {
			if (!this.auth.edit) {
				this.$message({
					message: '对不起，您没有编辑权限！',
					type: 'warning',
				})
				return
			}
			//判断是否开启了工作流
			if (this.isOpenFlow) {
				this.$router.openTaskWindow({
					flowCode: this.config.flowCode,
					formId: data.id,
				})
			} else {
				this.$refs.aceFormRender.open('edit', data.id)
			}
		},
		//删除单条
		deleteHandle(data) {
			if (!this.auth.delete) {
				this.$message({
					message: '对不起，您没有删除权限！',
					type: 'warning',
				})
				return
			}

			this.deleteTable([data.id])
		},
		//表格checkbox选择事件处理
		selectionHandle() {
			this.selected = this.$refs.table.getCheckboxRecords()
		},
		//获取表格配置
		async getTableConfig() {
			this.loading = true
			let res = await this.$http({
				url: this.$http.adornUrl(
					`/sysModelForms/query/tableFilterRule/byCode`
				),
				method: 'get',
				params: {
					code: this.formCode,
				},
			})
			let { data } = res
			if (data.code === 40000) {
				this.config = data.instance //赋值整体配置
				//判断返回的数据里是否有 tableFilterRule 属性
				if (typeof data.instance.tableFilterRule != 'undefined') {
					this.authHandle() //设置权限
					this.tableConfig = data.instance.tableFilterRule
						? JSON.parse(data.instance.tableFilterRule)
						: {} //赋值表格配置
					this.formConfig = data.instance.formChart
						? JSON.parse(data.instance.formChart)
						: {} //赋值表单配置

					this.tableConfig.cols.forEach((item, index, arr) => {
						if (item.isShow !== true) {
							arr.splice(index, 1)
						}
					})
					this.tableParamsResolver()
				} else {
					//如果tableFilterRule 为undefined 说明没有配置过表格，需要提示用户联系管理员配置表单表格
					this.loading = false
				}
			} else {
				this.$notify({
					title: '错误提示',
					message: data.msg,
					type: 'error',
				})
			}
		},
		//处理权限
		authHandle() {
			//如果权限为空则不受权限控制，设置为true
			this.auth = {
				add:
					this.config.addAuthId == '' ||
					isAuth(this.config.addAuthId),
				delete:
					this.config.delAuthId == '' ||
					isAuth(this.config.delAuthId),
				edit:
					this.config.editAuthId == '' ||
					isAuth(this.config.editAuthId),
				view:
					this.config.viewAuthId == '' ||
					isAuth(this.config.viewAuthId),
			}
		},
		//获取到表格配置后进行查询参数处理，再去请求列表数据
		tableParamsResolver() {
			//赋值查询条件
			this.queryParams.tableName = this.config.tableName
			// this.queryParams.tableName  = 'SYS_TEST_HU'
			//列条件
			this.queryParams.cols = this.tableConfig.cols.map((item) => ({
				colName: item.tabColName,
			}))

			this.getTableList()
		},

		//请求列表数据
		async getTableList() {
			this.loading = true
			let res = await this.$http({
				url: this.$http.adornWorkFlowUrl('modelData/getDataByPage'),
				method: 'post',
				data: this.queryParams,
			})
			let { data } = res
			if (data.code === 40000) {
				this.tableList = data.list
				this.total = data.total
			} else {
				this.$notify({
					title: '错误提示',
					message: data.msg,
					type: 'error',
				})
			}
			this.loading = false
		},
		async deleteTable(ids) {
			//modelData/deleteData
			this.loading = true
			let res = await this.$http({
				url: this.$http.adornWorkFlowUrl('modelData/deleteData'),
				method: 'post',
				data: {
					tableName: this.config.tableName,
					ids: ids,
				},
			})
			let { data } = res
			if (data.code === 40000) {
				this.$notify({
					title: '成功提示',
					message: '数据删除成功',
					type: 'success',
				})
				this.getTableList()
			} else {
				this.$notify({
					title: '失败提示',
					message: data.msg,
					type: 'error',
				})
			}
		},
	},
}
</script>

<style lang="scss" scoped>
.table-render-box {
	width: 100%;
	height: 100%;
	.table-message-box {
		display: flex;
		height: 100%;
		font-size: 18px;
		color: rgb(146, 146, 146);
		flex-direction: column;
		justify-content: center;
		align-items: center;
		.aceicon {
			font-size: 140px;
			color: rgb(207, 207, 207);
		}
	}
}
.table-render {
	display: flex;
	height: 100%;
	width: 100%;
	background-color: #fff;
	flex-direction: column;
	.header {
		display: flex;
		height: 48px;
		line-height: 48px;

		border-bottom: 1px solid rgba(0, 0, 0, 0.1);

		.title {
			font-size: 18px;
		}
		.left {
			margin: 0 10px;
		}
		.right {
			flex: 1;
			display: flex;
			flex-direction: row-reverse;
			.toolbar {
				display: flex;
				flex-direction: row-reverse;
				.create-flow-btn,
				.add-btn {
					color: #51aa24;
				}
				.delete-btn {
					color: #f56c6c;
				}
				> div {
					cursor: pointer;
					font-weight: bold;
					padding: 0 12px;
					height: 100%;
					font-size: 14px;
					border-left: 1px solid rgba(0, 0, 0, 0.1);
					&:hover {
						background-color: rgba(0, 0, 0, 0.05);
					}
				}
			}
		}
	}
	.body {
		height: calc(100% - 88px);
	}
	.footer {
		display: flex;
		align-items: center;
		height: 40px;
	}
}
</style>
