<template>
	<splitpanes class="default-theme">
		<pane size="20">
			<el-container class="jp-container">
				<el-header class="m-p-13-15">
					<el-input placeholder="请输入关键字过滤" clearable v-model="filterText">
					</el-input>
				</el-header>
				<el-main class="nopadding">
					<el-tree class="filter-tree" :data="officeTreeData" :props="{
						value: 'id', // ID字段名
						label: 'name', // 显示名称
						children: 'children', // 子级字段名
					}" node-key="id" default-expand-all :filter-node-method="filterNode" :expand-on-click-node="false"
						highlight-current @node-click="handleNodeClick" ref="officeTree">
						<template #default="{ node, data }">
							<span class="custom-tree-node el-tree-node__label">
								<span class="label">
									<el-icon class="m-r-5">
										<qiye v-if="data.type === '1'" :style="{
											color:
												$TOOL.data.get(
													'IS_PRIMARY_TENANT'
												) &&
												data.tenantDTO &&
												$utils.getTenantColorById(
													data.tenantDTO.id
												),
										}"></qiye>
										<bumen v-else :style="{
											color:
												$TOOL.data.get(
													'IS_PRIMARY_TENANT'
												) &&
												data.tenantDTO &&
												$utils.getTenantColorById(
													data.tenantDTO.id
												),
										}"></bumen>
									</el-icon>
									{{ node.label }}
								</span>
							</span>
						</template>
					</el-tree>
				</el-main>
			</el-container>
		</pane>
		<pane size="80">
			<el-container class="jp-container">
				<el-header v-if="searchVisible">
					<div class="left-panel">
						<el-form :inline="true" class="query-form m-b-10" ref="searchForm" :model="searchForm"
							@keyup.enter.native="refreshList()" @submit.native.prevent>
							<!-- 搜索框-->
							<el-form-item label="姓名" prop="name">
								<el-input v-model="searchForm.name" placeholder="请输入姓名" clearable></el-input>
							</el-form-item>
							<!--							<el-form-item label="所属部门" prop="department">-->
							<!--								<SelectTree-->
							<!--									ref="officeTree"-->
							<!--									:props="{-->
							<!--										value: 'id',             // ID字段名-->
							<!--										label: 'name',         // 显示名称-->
							<!--										children: 'children'    // 子级字段名-->
							<!--									  }"-->
							<!--									:url="`/system-server/sys/office/treeData?type=2`"-->
							<!--									:value="searchForm.department"-->
							<!--									:clearable="true"-->
							<!--									:accordion="true"-->
							<!--									size="default"-->
							<!--									@getValue="(value,label) => {searchForm.department=value}"/>-->
							<!--							</el-form-item>-->
							<el-form-item label="联系电话" prop="mobilePhone">
								<el-input v-model="searchForm.mobilePhone" placeholder="请输入联系电话" clearable></el-input>
							</el-form-item>
							<el-form-item label="政治面貌" prop="politicalOutlook" :rules="[]">
								<el-select v-model="searchForm.politicalOutlook" placeholder="请选择政治面貌"
									style="width:100%;" clearable>
									<el-option v-for="item in $dictUtils.getDictList('political_outlook')"
										:key="item.value" :label="item.label" :value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="账号状态" prop="loginFlag" :rules="[]">
								<el-select v-model="searchForm.loginFlag" placeholder="请选择账号状态" style="width:100%;"
									clearable>
									<el-option v-for="item in $dictUtils.getDictList('login_flag')" :key="item.value"
										:label="item.label" :value="item.value">
									</el-option>
								</el-select>
							</el-form-item>

							<el-form-item label="进所日期" prop="createDates">
								<el-date-picker style="width: 300px" placement="bottom-start" format="YYYY-MM-DD"
									value-format="YYYY-MM-DD" v-model="searchForm.createDates" type="daterange"
									range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
								</el-date-picker>
							</el-form-item>

						</el-form>
					</div>
					<div class="right-panel">
						<el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
						<el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
					</div>
				</el-header>
				<el-main class="nopadding page2">
					<div class="jp-table top" style="">
						<vxe-toolbar :refresh="{ query: resetSearch }" ref="toolbarRef" import export custom>
							<template #buttons>
								<el-button type="primary" icon="el-icon-plus" @click="start()">新建</el-button>
								<!-- <el-button type="primary" icon="el-icon-plus" @click="selectAllEvent()">全选</el-button> -->
								<el-button type="primary" icon="el-icon-plus"
									@click="downloadAttachments()">批量下载附件</el-button>

							</template>
							<template #tools>
								<vxe-button type="text" :title="searchVisible ? '收起检索' : '展开检索'
									" icon="vxe-icon-search" class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
								<vxe-button type="text" title="下载导入模板" icon="vxe-icon-copy" class="tool-btn m-l-0"
									@click="downloadTpl()">
								</vxe-button>
							</template>
						</vxe-toolbar>
						<div style="height: calc(100% - 90px)">
							<vxe-table border="inner" auto-resize resizable height="auto" :loading="loading"
								ref="clientTable" show-header-overflow show-overflow highlight-hover-row
								:print-config="{}" :import-config="{
									importMethod: importMethod,
									types: ['csv', 'xls', 'xlsx'],
									remote: true,
								}" :export-config="{
									remote: true,
									filename: `入职登记信息${moment(new Date()).format('YYYY-MM-DD')}`,
									sheetName: '入职登记信息',
									exportMethod: exportMethod,
									types: ['xlsx'],
									modes: ['current', 'selected', 'all']
								}" :menu-config="{}" @sort-change="sortChangeHandle" :sort-config="{ remote: true }" :data="dataList"
								:checkbox-config="{}" @checkbox-all="selectAllChangeEvent"
								@checkbox-change="selectChangeEvent">
								<vxe-column type="checkbox" width="60"></vxe-column>
								<vxe-column type="seq" width="60" title="序号"></vxe-column>
								<vxe-column min-width="160" align="center" title="姓名" field="name">
									<template #default="scope">
										<el-link type="primary" :underline="false" @click="view(scope.row.id)">{{
											scope.row.name }}</el-link>
									</template>
								</vxe-column>
								<vxe-column min-width="160" align="center" title="政治面貌" field="politicalOutlook">
									<template #default="scope">
										{{ $dictUtils.getDictLabel('political_outlook', scope.row.politicalOutlook, '')
										}}
									</template>
								</vxe-column>

								<vxe-column min-width="160" align="center" title="民族" field="nation">
									<template #default="scope">
										{{ $dictUtils.getDictLabel('sys_nation', scope.row.nation, '')
										}}
									</template>
								</vxe-column>
								<vxe-column min-width="160" align="center" title="所属部门"
									field="departmentName"></vxe-column>
								<vxe-column min-width="160" align="center" title="联系电话"
									field="mobilePhone"></vxe-column>
								<vxe-column min-width="160" align="center" title="进所日期" field="entryDate"></vxe-column>
								<!--								<vxe-column min-width="160" fixed="right" align="center" title="是否已加入钉钉" field="ddType">
									<template #default="scope">
										<el-button v-if="scope.row.ddType === '1'" @click="detail(scope.row)"
											type="success" effect="dark">{{ $dictUtils.getDictLabel("dd_type",
												scope.row.ddType, '已加入')
											}}
										</el-button>
										<el-button v-else @click="detail(scope.row)" type="warning" effect="dark">{{
											$dictUtils.getDictLabel("dd_type", scope.row.ddType,
												'未加入') }} </el-button>
									</template>
								</vxe-column>-->
								<vxe-column min-width="100" title="状态" fixed="right" align="center" field="type">
									<template #default="scope">
										<el-button v-if="scope.row.processType === '1'" @click="detail(scope.row)"
											:type="$dictUtils.getDictLabel('status_info', scope.row.type, '')"
											effect="dark">{{ $dictUtils.getDictLabel("status", scope.row.type, '未开始') }}
										</el-button>
										<el-button v-else @click="detail(scope.row)"
											:type="$dictUtils.getDictLabel('human_status_info', scope.row.type, '')"
											effect="dark">{{ $dictUtils.getDictLabel("human_status", scope.row.type,
												'未开始') }} </el-button>
									</template>
								</vxe-column>
								<vxe-column min-width="100" title="账号状态" fixed="right" align="center" field="loginFlag">
									<template #default="scope">
										<el-button v-if="scope.row.loginFlag == '1'" type="primary"
											effect="dark">正常</el-button>
										<el-button v-else type="danger" effect="dark">禁用</el-button>
									</template>
								</vxe-column>

								<vxe-column title="操作" width="350px" fixed="right" align="center">
									<template #default="scope">
										<el-button
											v-if="hasPermission('enrollmentRegistration:edit') && (scope.row.type === '2')"
											text type="primary" @click="reback(scope.row)">撤回</el-button>

										<el-button v-if="(hasPermission('enrollmentRegistration:editPw')) &&
											(scope.row.type === '5' || scope.row.type === '4' || scope.row.type === '3')" text type="primary" @click="
												editPw(scope.row)">修改密码</el-button>
										<el-button v-if="(hasPermission('enrollmentRegistration:edit')) && (scope.row.type === '5' || scope.row.type === '4' || scope.row.type === '3')
										" text type="primary" @click="edit(scope.row.id)">修改</el-button>

										<el-button
											v-if="
												(hasPermission('enrollmentRegistration:edit')) && (scope.row.type === '5' || scope.row.type === '4' || scope.row.type === '3')"
											text type="danger" @click="del(scope.row.id)">删除</el-button>
										<el-button text type="danger"
											v-if="(hasPermission('enrollmentRegistration:edit')) && (scope.row.loginFlag == '1')"
											@click=" updateLoginFlag(scope.row.userId, '0')">禁用</el-button>
										<el-button text type="primary"
											v-if="(hasPermission('enrollmentRegistration:edit')) && (scope.row.loginFlag == '0')"
											@click="updateLoginFlag(scope.row.userId, '1')">启用</el-button>
										<el-button text type="primary"
											v-if="(hasPermission('enrollmentRegistration:edit'))"
											@click="resetPwd(scope.row.userId)">重置密码</el-button>
										<el-button text type="primary"
											v-if="(hasPermission('enrollmentRegistration:edit'))"
											@click="removeRedis(scope.row.userId)">清除登录缓存</el-button>

									</template>
								</vxe-column>
							</vxe-table>
							<vxe-pager background :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
								:total="tablePage.total"
								:page-sizes="[10, 20, 100, 1000, { label: '全量数据', value: 1000000 }]"
								:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
								@page-change="currentChangeHandle">
							</vxe-pager>
						</div>
					</div>
				</el-main>
			</el-container>
		</pane>
	</splitpanes>

	<EnrollmentRegistrationEditForm ref="enrollmentRegistrationEditForm" @refreshDataList="refreshList">
	</EnrollmentRegistrationEditForm>

	<!-- 修改密码 -->
	<EditPassword ref="userPwForm" @refreshDataList="refreshList"></EditPassword>
	<!-- 批量下载附件 -->
	<DownloadAttachment ref="downloadAttachment" @refreshDataList="refreshList" />

</template>

<script>
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import SelectTree from '@/components/treeSelect/treeSelect.vue'
import EnrollmentRegistrationEditForm from './EnrollmentRegistrationEditForm'
import enrollmentRegistrationService from '@/api/human/enrollment/EnrollmentRegistrationService'
import processService from '@/api/flowable/ProcessService'
import userService from '@/api/sys/UserService'
import taskService from '@/api/flowable/TaskService'
import pick from "lodash.pick";
import officeService from "@/api/sys/officeService";
import EditPassword from "./EditPassword.vue"
import DownloadAttachment from "./components/DownloadAttachment.vue";
export default {
	data() {
		return {
			num: 0,
			searchForm: {
				name: '',
				mobilePhone: '',
				politicalOutlook: '',
				loginFlag: '',
				department: '',
				companyId: '',
				createDates: [],
			},
			dataList: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: []
			},
			tableKey: '',
			loading: false,
			processDefinitionAuditId: '',
			procDefAuditKey: '',
			processDefinitionAuditId2: '',
			procDefAuditKey2: '',
			isAdmin: false,
			create: '',
			haveProjectIds: '',
			searchVisible: true,
			officeTreeData: [],
			filterText: "",
			selectChangeList: []
		}
	},
	created() {
	},
	components: {
		SelectTree,
		EnrollmentRegistrationEditForm,
		Splitpanes,
		Pane,
		EditPassword,
		DownloadAttachment
	},
	watch: {
		filterText(val) {
			this.$refs.officeTree.filter(val);
		},
	},
	computed: {
		userName() {
			return this.$store.state.user.name
		},
		user() {
			this.createName = this.$store.state.user.name
			return this.$store.state.user
		}
	},
	mounted() {
		this.$nextTick(() => {
			//将表格和工具栏进行关联
			const $table = this.$refs.clientTable;
			const $toolbar = this.$refs.toolbarRef;
			$table.connect($toolbar);
		})
		this.refreshList()
		this.refreshTree();
	},
	activated() {
		this.refreshList()
	},
	methods: {
		// 修改密码
		editPw(row) {
			this.$refs.userPwForm.init("edit", row.userId, row.tenantId);
		},
		filterNode(value, data) {
			if (!value) return true;
			return data.name.indexOf(value) !== -1;
		},
		handleNodeClick(data) {
			if (data.type === "1") {
				this.searchForm.companyId = data.id;
				this.searchForm.department = "";
			} else {
				this.searchForm.companyId = "";
				this.searchForm.department = data.id;
			}
			this.refreshList();
		},
		// 新增
		add() {
		},
		// 查看
		view(id) {
			this.$refs.enrollmentRegistrationEditForm.init('view', id)
		},
		// 修改
		edit(id) {
			id = id || this.$refs.clientTable.getCheckboxRecords().map(item => {
				return item.id
			})[0]
			this.$refs.enrollmentRegistrationEditForm.init('edit', id)
		},
		// 查询当前用户是否是管理员用户
		checkIsAdmin() {
			userService.is().then((data) => {
				this.isAdmin = data
			})
		},
		// 获取数据列表
		refreshList() {
			this.loading = true
			enrollmentRegistrationService.list({
				'current': this.tablePage.currentPage,
				'size': this.tablePage.pageSize,
				'orders': this.tablePage.orders,
				...this.searchForm
			}).then((data) => {
				this.dataList = data.records
				this.tablePage.total = data.total
				this.tableKey = Math.random()
				this.loading = false
			})
			this.checkIsAdmin()
			processService.getByName('员工入职').then((data) => {
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionAuditId = data.id
					this.procDefAuditKey = data.key
				}
			})
			processService.getByName('完善个人信息').then((data) => {
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionAuditId2 = data.id
					this.procDefAuditKey2 = data.key
				}
			})
		},
		refreshTree() {
			officeService.treeData().then((data) => {
				this.officeTreeData = data;
			});
		},
		// 当前页
		currentChangeHandle({ currentPage, pageSize }) {
			this.tablePage.currentPage = currentPage
			this.tablePage.pageSize = pageSize
			this.refreshList()
		},
		// 排序
		sortChangeHandle(column) {
			this.tablePage.orders = []
			if (column.order != null) {
				this.tablePage.orders.push({ column: this.$utils.toLine(column.property), asc: column.order === 'asc' })
			}
			this.refreshList()
		},
		resetSearch() {
			this.searchForm.department = "";
			this.searchForm.companyId = "";
			this.filterText = "";
			this.$refs.officeTree.setCurrentKey(null);
			this.$refs.searchForm.resetFields()
			this.refreshList()
		},
		start() {
			// 读取流程表单
			let tabTitle = `发起流程【员工入职】`
			let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [员工入职]`
			taskService.getTaskDef({
				procDefId: this.processDefinitionAuditId,
				status: 'startAndHold'
			}).then((data) => {
				this.$router.push({
					path: '/flowable/task/TaskForm',
					query: {
						...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
						procDefId: this.processDefinitionAuditId,
						procDefKey: this.procDefKey,
						status: 'startAndHold',
						title: tabTitle,
						formType: data.formType,
						formUrl: data.formUrl,
						formTitle: processTitle,
						businessId: 'false',
						isShow: false,
						routePath: '/human/enrollment/registration/EnrollmentRegistrationList'
					}
				})
			})
		},
		// 查看员工入职流程结果
		detail(row) {
			if (row.reviewStatus !== '0' && row.reviewStatus !== '1') {

				if (this.commonJS.isNotEmpty(row.processType) && row.processType == '1') {
					//信息完善流程
					taskService.getTaskDef({
						procInsId: row.procInsId,
						procDefId: this.processDefinitionAuditId2
					}).then((data) => {
						this.$router.push({
							path: '/flowable/task/TaskFormDetail',
							query: {
								...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
								isShow: 'false',
								readOnly: true,
								title: '个人信息完善' + '流程详情',
								formTitle: '个人信息完善' + '流程详情',
								businessId: row.id,
								status: 'reback'
							}
						})
					})
				} else {
					// eslint-disable-next-line eqeqeq
					taskService.getTaskDef({
						procInsId: row.procInsId,
						procDefId: this.processDefinitionAuditId
					}).then((data) => {
						this.$router.push({
							path: '/flowable/task/TaskFormDetail',
							query: {
								...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
								isShow: 'false',
								readOnly: true,
								title: '员工入职' + '流程详情',
								formTitle: '员工入职' + '流程详情',
								businessId: row.id,
								status: 'reback'
							}
						})
					})
				}


			}
		},
		// 下载模板
		downloadTpl() {
			// this.$utils.downloadExcel('/sys/user/import/template')
			enrollmentRegistrationService
				.exportTemplate()
				.then((data) => {
					// 将二进制流文件写入excel表，以下为重要步骤
					this.$utils.downloadExcel(data, "用户导入模板");
				})
				.catch(function (err) {
					if (err.response) {
						console.log(err.response);
					}
				});
		},
		// 自定义服务端导入
		importMethod({ file }) {
			// 处理表单
			const formBody = new FormData();
			formBody.append("file", file);
			enrollmentRegistrationService.importExcel(formBody).then((result) => {
				this.$message.success({
					dangerouslyUseHTMLString: true,
					message: result,
				});
				this.refreshList();
			});
		},


		// 自定义服务端导出
		exportMethod({ options }) {
			// 传给服务端的参数
			const params = {
				'current': this.tablePage.currentPage,
				'size': this.tablePage.pageSize,
				'orders': this.tablePage.orders,
				...this.searchForm,
				filename: options.filename,
				sheetName: options.sheetName,
				isHeader: options.isHeader,
				original: options.original,
				mode: options.mode,
				selectIds: options.mode === 'selected' ? options.map(item => item.id) : [],
				exportFields: options.columns.map(column => column.property)
			}
			return enrollmentRegistrationService.exportExcel(params).then((res) => {
				// 将二进制流文件写入excel表，以下为重要步骤
				this.$utils.downloadExcel(res, options.filename)
			}).catch(function (err) {
				if (err.response) {
					// console.log(err.response)
				}
			})
		},
		// 删除
		del(id) {
			let ids = id || this.$refs.clientTable.getCheckboxRecords().map(item => {
				return item.id
			}).join(',')
			this.$confirm(`确定删除所选项吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				enrollmentRegistrationService.remove(ids).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				})
			})
		},
		removeRedis(userId) {
			this.$confirm(`确定清除该用户的登录缓存吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				userService.removeRedis(userId).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				})
			})
		},
		resetPwd(userId) {
			this.$confirm(`确定重置该用户的登录密码吗？重置后，密码为:123456`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				userService.resetPwd({
					id: userId
				}).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				})
			})
		},

		//修改用户是否允许登录
		updateLoginFlag(id, loginFlag) {
			let msg = loginFlag == "1" ? "确定允许该用户登录吗？" : "确定禁止该用户登录吗？"
			this.$confirm(msg, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				userService.updateLoginFlag({ id: id, loginFlag: loginFlag }).then(res => {
					this.$message.success("修改成功")
					this.refreshList()
					this.loading = false
				})
			})
		},
		// 撤回流程
		reback(row) {
			this.$confirm(`确定撤回流程吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				processService.deleteProcIns(row.procInsId).then(async () => {
					let param = { type: '3', id: row.id }
					await enrollmentRegistrationService.updateStatusById(param)
					this.$message.success('撤回成功')
					this.refreshList()
				})
			})
		},
		downloadAttachments() {
			if (!this.selectChangeList || !this.selectChangeList.length) {
				this.$message.warning("未选择任何用户，无法下载附件")
				return
			}
			let ids = this.selectChangeList.map(item => {
				return item.id
			})
			this.$refs.downloadAttachment.visible = true
			this.$refs.downloadAttachment.ids = ids.join(',');
		},
		selectAllChangeEvent({ checked }) {
			const $table = this.$refs.clientTable
			if ($table) {
				const records = $table.getCheckboxRecords()
				this.selectChangeList = [...records]
			}
		},
		selectChangeEvent({ checked }) {
			const $table = this.$refs.clientTable
			if ($table) {
				const records = $table.getCheckboxRecords()
				this.selectChangeList = [...records]
			}
		},
	}
}
</script>
