<template>
	<el-dialog top="5vh" :title="title" :visible.sync="visible" :before-close="handleClose" width="70%"
		:close-on-click-modal="false" v-if="visible">
		<div class="header">
			<span class="title" :class="tip ? 'tip-color' : ''">{{ $t('reportManagement.authType') }}：</span>
			<el-checkbox-group v-model="checkAuthorityList" @change="handleCheck">
				<el-checkbox v-for="item in checkedHeaders" :label="item.value" :key="item.name"
					:class="tip ? 'tip-color' : ''">
					{{ item.name }}
				</el-checkbox>
			</el-checkbox-group>
		</div>
		<div class="innerDialog">
			<div class="left">
				<el-tabs @tab-click="handleTabClick" v-model="activeName" type="card">
					<el-tab-pane v-for="item in tabPaneList" :key="item.value" :label="item.name" :name="item.value">
						<div class="innerDialog-tabs">
							<div class="tabs-left" v-if="item.value !== 'role'">
								<!-- 树形控件 -->
								<tree v-if="item.value === 'org'" :data="treeData" @node-click="handleNodeClick"
									@loadTree="loadDataTree" />
								<tree v-if="item.value === 'user'" :data="treeData" @node-click="handleNodeClickUser"
									@loadTree="loadDataTree" />
							</div>
							<div class="tabs-right" :style="{width:item.value === 'role'?'100%':'calc(100% - 300px)'}">
								<div class="dialog-header" v-if="item.value !== 'org'">
									<el-form ref="form" :model="searchForm" label-width="70px">
										<el-form-item :label="$t('overseasEnterpriseInfo.name')">
											<el-input v-model="searchForm.name" clearable
												:placeholder="$t('navigator.searchTip')">
											</el-input>
										</el-form-item>
									</el-form>
									<el-divider direction="vertical" class="line"></el-divider>
									<div>
										<el-button icon="el-icon-search" type="primary" class="btn btn-plus"
											@click="handleSearch">
											{{ $t('common.search') }}
										</el-button>
									</div>
								</div>
								<el-table ref="multipleTable" tooltip-effect="dark" :data="tableData" :max-height="450"
									style="width: 100%" @select="handleSelectionChange">
									<el-table-column type="selection" width="55" align="center"></el-table-column>
									<template v-if="item.value === 'org'">
										<el-table-column show-overflow-tooltip prop="code" width="200" align="center">
											<template slot="header">
												{{ $t('reportManagement.code') }}
											</template>
										</el-table-column>
										<el-table-column show-overflow-tooltip prop="name" min-width="150"
											align="center">
											<template slot="header">
												{{ $t('reportManagement.name') }}
											</template>
										</el-table-column>
									</template>
									<template v-if="item.value === 'role'">
										<el-table-column show-overflow-tooltip prop="code" width="200" align="center">
											<template slot="header">
												{{ $t('reportManagement.code') }}
											</template>
										</el-table-column>
										<el-table-column show-overflow-tooltip prop="name" min-width="150"
											align="center">
											<template slot="header">
												{{ $t('reportManagement.name') }}
											</template>
										</el-table-column>
									</template>
									<template v-if="item.value === 'user'">
										<el-table-column show-overflow-tooltip prop="account" width="200"
											align="center">
											<template slot="header">
												{{ $t('reportManagement.account') }}
											</template>
										</el-table-column>
										<el-table-column show-overflow-tooltip prop="name" min-width="150"
											align="center">
											<template slot="header">
												{{ $t('reportManagement.name') }}
											</template>
										</el-table-column>
									</template>
								</el-table>
								<pagination v-if="item.value !== 'org'" :pageResult="pageResult"
									@size-change="handleSizeChange" @current-change="handleCurrentChange" />
							</div>
						</div>
					</el-tab-pane>
				</el-tabs>
			</div>
			<div class="right">
				<div class="text">{{ $t('reportManagement.selected') }}</div>
				<template v-if="selectUser.length !== 0">
					<div class="item" v-for="item in selectUser" :key="item.name">
						<span>{{ item.name }}</span>
						<span>{{ getDictName('sqdxlx', item.objectType)}}</span>
						<el-link icon="el-icon-delete" :underline="false" type="danger"
							@click="handleRightDelete(item)">
							{{ $t('common.delete') }}
						</el-link>
					</div>
				</template>
				<span style="padding: 10px; display: inline-block" v-else>{{
          $t('common.empty')
        }}</span>
			</div>
		</div>
		<span slot="footer" class="dialog-footer">
			<!-- <el-button type="primary" @click="submit">
				{{ $t('common.save') }}
			</el-button> -->
			<el-button @click="handleClose">
				{{ $t('common.cancel') }}
			</el-button>
		</span>
	</el-dialog>
</template>
<script>
	import tree from '@/components/tree'
	import pagination from '@/components/pagination'
	import req from '@/request.js'
	import org from '@/api/org.js'
	import uc from '@/api/uc.js'
	import utils from '@/utils.js'
	const portal = window.context.portal
	export default {
		name: 'authDailog',
		components: {
			pagination,
			tree
		},
		data() {
			return {
				reportId: '',
				treeData: [],
				title: '',
				visible: false,
				searchForm: {},
				tableData: [],
				tableDataUser: [],
				pageResult: {
					page: 1,
					pageSize: 20,
					total: 0
				},
				params: {
					pageBean: {
						page: 1,
						pageSize: 20
					}
				},
				treeParams: {
					demId: '1258608622670319616'
				},
				activeName: '',
				tabKey: 'org',
				checkAuthorityList: [],
				checkedHeaders: [],
				multipleSelection: [], // 已选中的列表
				tabPaneList: [],
				tip: false, // 未选择授权类型给出提示
				selectUser: [],
			}
		},
		created() {
			this.loadDataTree(this.treeParams)
			if (this.$i18n.locale === 'zh-CN') {
				this.checkedHeaders = utils.getDictItemsFromCache('bbqx')
				this.tabPaneList = utils.getDictItemsFromCache('sqdxlx')
			} else {
				this.checkedHeaders = utils.getDictItemsFromCache('bbqx_en')
				this.tabPaneList = utils.getDictItemsFromCache('sqdxlx_en')
			}
			this.activeName = this.tabPaneList[0].value
			this.getOrgData()
		},
		methods: {
			open(reportId, list) {
				this.selectUser = []
				this.checkAuthorityList = []
				this.reportId = reportId
				this.title = this.$t('reportManagement.auth')
				this.getselectUser()
				this.visible = true
			},
			getselectUser() {
				req.get(
					portal +
					`/qfReportAuthority/v1/getList?pageNum=1&pageSize=-1&reportId=${this.reportId}`
				).then((res) => {
					console.log(res.data.value.rows);
					if (res) {
						this.selectUser = res.data.value.rows
						this.checkAuthorityList = this.selectUser.length > 0 ? ["qurey", "edited", "del"] : []
					}
				})
			},
			getDictName(code, value) {
				return utils.getDictName(code, value)
			},
			getOrgData() {
				org.getByParentAndDemToTree().then(res => {
					this.tableData = res || []
					this.$nextTick(() => {
						this.selectUser.forEach(s => {
							this.tableData.forEach(u => {
								if (s.objectId == u.id) {
									console.log(u);
									this.$refs.multipleTable[0].toggleRowSelection(
										u, true)
								}
							})
						})
					})
				})
			},
			getUserData(params) {
				uc.getOrgUserQuery(params).then(res => {
					let data = (res && res.rows) || []
					this.tableData = data.map(item => {
						return {
							name: item.fullname,
							...item
						}
					})

					this.pageResult = {
						page: res.page,
						pageSize: res.pageSize,
						total: res.total
					}
				})
			},
			getRolerData(params) {
				req.post(portal + '/api/role/v1/roles/getRolePage', params).then(res => {
					let resp = res.data
					this.tableData = (resp && resp.rows) || []
					this.pageResult = {
						page: resp.page,
						pageSize: resp.pageSize,
						total: resp.total
					}
				})
			},
			handleClose() {
				this.visible = false
			},
			handleTabClick(tab) {
				this.tabKey = tab.name
				this.params = {
					pageBean: {
						page: 1,
						pageSize: 20
					}
				}
				if (tab.name == 'org') {
					this.getOrgData()
				} else if (tab.name == 'user') {
					this.getUserData(this.params)
				} else {
					this.getRolerData(this.params)
				}
			},
			loadDataTree(params) {
				org.getByParentAndDemToTree(params).then(res => {
					let data = res || []
					this.treeData = utils.tile2nest(data)
				})
			},
			handleNodeClick(item) {
				if (item.id == '0') {
					this.getOrgData()
				} else {
					this.tableData = []
					this.tableData.push(item)
				}
			},
			handleNodeClickUser(item) {
				if (item.id == '0') {
					this.params.querys = [{
						property: 'DEM_ID_',
						value: item.demId,
						group: 'orgTree',
						relation: 'AND',
						operation: 'EQUAL'
					}]
				} else {
					this.params.querys = [{
						property: 'ORG_ID_',
						value: item.id,
						group: 'orgTree',
						relation: 'AND',
						operation: 'IN'
					}]
				}
				this.getUserData(this.params)
			},
			handleSearch() {
				let obj = this.searchForm
				let querys = []
				for (let i in obj) {
					if (obj[i]) {
						querys.push({
							group: 'main',
							operation: 'LIKE',
							parentGroup: '',
							property: i,
							relation: 'AND',
							value: obj[i]
						})
					}
				}
				this.params.querys = querys
				if (this.tabKey == 'user') {
					this.getUserData(this.params)
				} else {
					this.getRolerData(this.params)
				}
			},
			handleSelectionChange(selection, row) {
				let flag = selection.some((item) => {
					if (row.id == item.id) return true;
				})
				let userFlag = true
				this.selectUser.forEach((s, si) => {
					if (s.objectId == row.id) {
						userFlag = false
					}
				})
				if (flag && userFlag) {
					let params = {
						key: this.tabKey,
						authority: this.checkAuthorityList.join(','),
						name: row.name,
						objectId: row.id,
						objectType: this.tabKey,
						reportId: this.reportId
					}
					// this.selectUser.push(params)
					req
						.post(portal + '/qfReportAuthority/v1/insertInfo', [params])
						.then(res => {
							this.getselectUser()
						})
				} else if (flag && !userFlag) {

				} else {
					// this.selectUser.forEach((s, si) => {
					// 	if (s.objectId == row.id) {
					// 		this.handleRightDelete(row)

					// 	}
					// })
				}
			},
			// 去重
			uniqueFunc(arr, uniId) {
				const res = new Map()
				return arr.filter(
					item => !res.has(item[uniId]) && res.set(item[uniId], 1)
				)
			},
			handleSizeChange(pageSize) {
				this.params.pageBean.pageSize = pageSize
				if (this.tabKey == 'user') {
					this.getUserData(this.params)
				} else {
					this.getRolerData(this.params)
				}
			},
			handleCurrentChange(page) {
				this.params.pageBean.page = page
				if (this.tabKey == 'user') {
					this.getUserData(this.params)
				} else {
					this.getRolerData(this.params)
				}
			},
			handleRightDelete(val) {
				req.remove(portal + '/qfReportAuthority/v1/deleteByIds' + '?ids=' + val.id).then(
					(res) => {
						this.getselectUser()
					}
				)
			},
			submit() {
				let data = this.selectUser
				// console.log(data);
				// let params = []
				if (this.checkAuthorityList.length === 0)
					return this.$confirm(
						this.$t('common.selectAuthType'),
						this.$t('common.tips'), {
							confirmButtonText: this.$t('common.confirm'),
							cancelButtonText: this.$t('common.cancel'),
							type: 'warning'
						}
					).then(() => {
						this.tip = true
					})
				// data.forEach(item => {
				// 	params.push({
				// 		authority: this.checkAuthorityList.join(','),
				// 		name: item.name,
				// 		objectId: item.id,
				// 		objectType: item.key,
				// 		reportId: this.reportId
				// 	})
				// })
				req
					.post(portal + '/qfReportAuthority/v1/insertInfo', data)
					.then(res => {
						this.visible = false
						this.$emit('upDataAuth')
					})
			},
			handleCheck(rows) {
				if (rows.length !== 0) {
					this.tip = false
				} else {
					this.tip = true
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.header {
		height: 60px;
		line-height: 60px;
		display: flex;

		.title {
			margin-right: 10px;
			font-size: 16px;
		}

		.tip-color {
			color: #f40;
		}
	}

	.innerDialog {
		display: flex;
		max-height: 500px;

		.left {
			width: 80%;
		}

		.right {
			width: 20%;
			border: 1px solid #eee;
			margin-left: 10px;
			margin-top: 40px;

			/deep/ .el-checkbox__label {
				max-width: 120px;
				text-overflow: ellipsis;
				/*让截断的文字显示为点点。还有一个值是clip意截断不显示点点*/
				white-space: nowrap;
				/*让文字不换行*/
				overflow: hidden;
				/*超出要隐藏*/
			}

			.text {
				height: 50px;
				line-height: 50px;
				padding-left: 20px;
				font-size: 14px;
				border-bottom: 1px solid #eee;
			}

			.item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 10px;

				span {
					display: inline-block;
				}

				span:nth-child(1) {
					width: 50%;
				}

				&:nth-child(n + 1) {
					padding-bottom: 0;
				}
			}

			.grop {
				padding-left: 20px;
				padding-top: 10px;
				display: flex;
				flex-direction: column;
				border: 1px solid #eee;
				padding-right: 10px;
			}

			/deep/ .el-checkbox {
				margin-right: 0;
				height: 24px;
				display: flex;
				align-items: center;
			}
		}

		/deep/ .el-tabs__nav {
			padding-top: 0;
		}

		/deep/ .el-tabs,
		/deep/ .el-tabs__header,
		/deep/ .el-tabs__nav-wrap,
		/deep/ .el-tabs__nav-scroll,
		/deep/ .el-tabs__nav {
			height: inherit;
		}

		.innerDialog-tabs {
			display: flex;

			.tabs-left {
				width: 300px;
				height: 450px;
				border: 1px solid #eee;
				padding: 10px;
				margin-right: 10px;
				overflow: auto;

			}

			// .tabs-right {
			// 	width: 80%;
			// }
		}
	}

	.dialog-header {
		display: flex;
		align-items: center;
		margin-bottom: 10px;

		.line {
			margin: 0 30px;
		}

		.btn-plus {
			margin-right: 10px;
		}

		/deep/ .el-form-item--small.el-form-item {
			margin-bottom: 0;
		}

		/deep/ .el-form {
			height: 40px;
		}
	}
</style>
<style lang="scss" scoped>
	.el-dialog__wrapper {
		/deep/ .el-dialog {
			height: 750px;

			.el-dialog__body {
				height: 610px;
			}
		}
	}

	/deep/.el-table__header-wrapper .el-checkbox {
		//找到表头那一行，然后把里面的复选框隐藏掉
		display: none
	}
</style>
