<template>

	<div class="custom-tree-container">
		<div class="block-l">
			<el-card class="space-vertical" shadow="hover">
				<el-select v-model="deptAttr" class="full" filterable placeholder="组织架构类型" size="small"
									 @change="handleDeptAttrChange"
				>
					<el-option v-for="item in DeptAttrData" :key="item.value" :label="item.label" :value="item.value"/>
				</el-select>
			</el-card>
			<el-card shadow="hover">
				<el-tag :closable="selectDeptNode.level!==0" class="full space-vertical" @close="handleCloseDept()">当前所选：{{
						selectDeptNode.name
					}}
				</el-tag>
				<el-tree
				 ref="selectTree"
				 :data="DeptTree"
				 :default-expanded-keys="expandedDeptKey"
				 :expand-on-click-node="expandDeptClick"
				 :indent="deptTreeIndent"
				 accordion
				 node-key="id"
				 @node-click="handleDeptNodeClick"
				>
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>
                <i v-if="data.level == 0" class="el-icon-s-home"/>
                <i v-else-if="data.level == 1" class="el-icon-menu"/>
                <i v-else class="el-icon-link"/>
                {{ node.label }}
              </span>
              <span v-if="data.level == 0">
                <el-link class="space" type="primary" @click="() => unFoldAll()">展开</el-link>
                <el-link class="space" type="primary" @click="() => collapseAll()">折叠</el-link>
              </span>
            </span>
				</el-tree>
			</el-card>
		</div>
		<div class="block-r">

			<el-row class="handle-box" style="margin-bottom: 10px">
				<el-col :span="24">

					<el-form
					 ref="elForm"
					 :model="search"
					 :rules="rules"
					 label-width="100px"
					 size="medium"
					>
						<el-col :span="6">
							<el-form-item label="姓名" prop="name" style="margin-bottom: 0">
								<el-input
								 v-model="search.name"
								 :style="{ width: '100%' }"
								 clearable
								 placeholder="请输入名称"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="6">

						</el-col>

						<el-col :span="18">
							<div style="width: auto;float: right">
								<el-button class="ch-button-warning" plain size="small" @click="handleReset()"><i
								 class="el-icon-aim"
								/>&nbsp;重置
								</el-button>
								<el-button class="ch-button" size="small" @click="handleSearch()"><i class="el-icon-search"/>&nbsp;搜索
								</el-button>
								<el-button size="small" type="success" @click="confirmOutput()"><i class="el-icon-download"/>&nbsp;导出
								</el-button>
							</div>
						</el-col>
					</el-form>

				</el-col>
			</el-row>
			<el-row class="handle-box">
				<el-col :span="24">
					<el-table
					 v-loading="loading"
					 :cell-style="styleBack"
					 :data="tableData"
					 row-class-name="g_table_row"
					 stripe
					 style="width: 100%"
					>
						<el-table-column label="序号" type="index" width="60"/>
						<el-table-column label="姓名" prop="truename"/>
						<el-table-column label="部门" prop="deptName"/>
						<el-table-column label="入职日期" prop="joinDay"/>
						<el-table-column label="年假核算标准" prop="holidayType">
							<template slot-scope="scope">
								{{
									scope.row.holidayType == 1 ? '社保不满10年' :
									 scope.row.holidayType == 2 ? '社保满10年' :
										scope.row.holidayType == 3 ? '司龄不满1年' :
										 scope.row.holidayType == 4 ? '社保满20年' : ''
								}}
							</template>
						</el-table-column>
						<el-table-column label="年假基数（天）" prop="holidayDayBase"/>
						<!--						<el-table-column label="剩余年假（天）" prop="freezeHolidayTime"/>-->
						<el-table-column label="剩余年假（天）" prop="freezeHolidayTime" width="120">
							<template slot-scope="scope">
								<span>{{
										(scope.row.restHolidayTime != null ? scope.row.restHolidayTime : '') + '' + (scope.row.freezeHolidayTime > 0 ? '(另冻结' + scope.row.freezeHolidayTime + '天)' : '')
									}}</span>
							</template>
						</el-table-column>
						<!--						<el-table-column label="年假有效期" prop="restHolidayDate"/>-->
						<el-table-column label="年假有效期" prop="restHolidayDate">
							<template slot-scope="scope">
								<span>{{ scope.row.holidayDayBase <= 0 ? '' : scope.row.restHolidayDate }}</span>
							</template>
						</el-table-column>
						<el-table-column label="剩余调休假（h）" prop="restExchangeTime"/>
						<el-table-column label="用户状态" prop="status">
							<template slot-scope="scope">
								<el-switch
								 v-model="scope.row.status==2?false:true"
								 active-color="#13ce66"
								 inactive-color="#ff4949"
								 @change="changeStatus(scope.row)"
								>
								</el-switch>
							</template>
						</el-table-column>
						<el-table-column label="禁用时间" prop="noUseDate"/>
						<el-table-column align="center" fixed="right" header-align="center" label="操作" width="250px">
							<template slot-scope="scope">
								<el-button :disabled="scope.row.status!=0" size="small" type="primary"
													 @click="openHolidayDialog(true,scope.row)"
								>编辑
								</el-button>
							</template>
						</el-table-column>
					</el-table>
					<div class="table-page">
						<el-pagination
						 :current-page.sync="currentPage"
						 :page-size="pageSize"
						 :total="allpage"
						 background
						 layout="total, prev, pager, next"
						 @current-change="handleCurrentChange"
						/>
					</div>
				</el-col>
			</el-row>

		</div>
		<add-or-edit-holiiday ref="addOrEditHoliiday" @getData="getData()"/>

	</div>
</template>
<script>
import addOrEditHoliiday from '@/views/workflow/components/holidayQuota/addOrEditHoliiday.vue'
import common from '@/static/utils/common'
import Base from '../base/base'
import BaseData from '../base/baseData'
import BaseDept from '../base/baseDept'

export default {
	components: { addOrEditHoliiday },
	mixins: [Base, BaseData, BaseDept],
	data() {
		return {
			// 查询数据的内容
			search: {},
			departmentIds: '',
			deptAttr: '',
			// 通用字典项
			AUDIT_TYPE: [],
			dc_map: {},
			// 列表相关
			cusName: '',
			auditStatus: '',
			auditType: '',
			proName: '',
			applyBy: '',
			tableData: [],
			loading: false,
			UserMap: {},
			// 分页
			currentPage: 1,
			allpage: 0,
			pageSize: 12,
			// 弹框相关
			currAuditId: '',
			dialogVisible: false,
			dialogTitle: '新增',
			isAdd: true,
			detailList: [],
			rules: {},
			OutData: []
		}
	},
	mounted() {
		const _this = this
		_this.getData()
		this.initDeptAttr().then(() => {
			if (this.DeptAttrData.length > 0) {
				this.deptAttr = this.DeptAttrData[0].value
				this.initDepartment({ deptAttr: this.deptAttr })
			}
		})
	},
	methods: {

		styleBack({ row, column, rowIndex, columnIndex }) {
			if (row.isFirst == 1) return { backgroundColor: '#FDBABB' }
		},
		addAttrDept: function() {
			if (!this.form.selectDepts) this.form.selectDepts = []
			this.form.selectDepts.push({
				userId: this.form.id,
				attrId: '',
				deptAttrs: this.DeptAttrData,
				deptId: '',
				depts: [],
				postIds: []
			})
		},

		dlgOpen: function() {
			const _this = this
			if (this.form.id) {
				this.baseRequest('getById', {
					id: this.form.id
				}).then((res) => {
					if (res.data) {
						_this.form.groupId = res.data.groupId
						_this.form.username = res.data.username
						_this.form.truename = res.data.truename
						_this.form.staffCode = res.data.staffCode
						_this.form.gender = res.data.gender
						_this.form.leader = res.data.leader
						_this.form.position = res.data.position
						_this.form.posts = res.data.posts ? res.data.posts.split(',') : []
						if (_this.form.posts.length) {
							_this.initPosition2(_this.form.posts)
						}
						_this.form.sequenceNo = res.data.sequenceNo
						_this.form.phone = res.data.phone
						_this.form.secretKey = res.data.secretKey
						_this.form.comment = res.data.comment

						_this.form.selectDepartment = res.data.department

						_this.form.selectDepts = []
						_this.userDeptRequest('listByUserId', {
							userId: _this.form.id
						}).then(resDept => {
							if (resDept.data) {
								resDept.data.forEach(dept => {
									dept.postIds = dept.posts ? dept.posts.split(',') : []
									dept.deptAttrs = _this.DeptAttrData
									if (dept.attrId) {
										dept.depts = _this.TempDepts.filter(tempDept => {
											return tempDept.deptAttr === dept.attrId
										})
									}
									_this.form.selectDepts.push(dept)
								})
							}
							// console.log('listByUserId', _this.form.selectDepts)
						})
					}
				}).catch(() => {
				})
			}
		},
		handleDeptAttrChange: function(val) {
			this.selectDeptNode = this.getDeptDefaultTopNode()
			this.deptAttr = val
			this.initDepartment({ deptAttr: val })
			this.handleSearch()

		},
		handleDeptNodeClick(data, node, ocx) {
			this.departmentIds = data.id
			this.getData()

		},
		handleCloseDept: function() {
			this.selectDeptNode = this.getDeptDefaultTopNode()
			this.handleSearch()

		},
		confirmOutput() {
			const OutSize = [
				{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 },
				{ wch: 15 }, { wch: 15 }, { wch: 25 }, { wch: 25 }, { wch: 15 }, { wch: 15 }, { wch: 15 }]
			const fileName = '假期额度导出' + new Date().Format('yyyy-MM-dd')
			this.$outputXlsxFile(this.OutData, OutSize, fileName)
		},
		getPostData: function() {
			const postData = {
				departmentIds: this.departmentIds,
				name: this.search.name,
				pageNum: this.currentPage,
				pageSize: this.pageSize
			}
			const currUser = this.$common.currUser()
			if (currUser && currUser.groupId) {
				postData.groupId = common.currUser().groupId
			}
			if (!this.$common.isAdmin()) {
				postData.chargedby = this.$common.currUser().id
			}

			return postData
		},
		initOutData: function() {
			const _this = this
			this.OutData = [[
				'姓名', '部门', '入职日期', '年假核算标准', '年假基数（天）', '剩余年假(天)',
				'年假有效期', '剩余调休假', '用户状态', '禁用时间']]
			const postData = this.getPostData()
			this.baseRequest1('listAll', postData).then((res) => {
				try {
					if (res.data) {
						res.data.forEach(function(item) {
							item.joinDay = !item.joinDay ? '' : _this.$common.transDate(item.joinDay)
							item.restHolidayDate = !item.restHolidayDate ? '' : _this.$common.transDate(item.restHolidayDate)
							item.zhuangtai = item.status == 2 ? '禁用' : '启用'
							item.noUseDate = !item.noUseDate ? '状态非禁用' : _this.$common.transDate(item.noUseDate)
							item.holidayType = item.holidayType == 1 ? '社保不满10年' : item.holidayType == 2 ? '社保满10年' : item.holidayType == 3 ? '司龄不满一年' : ''
							const jsonMap = _this.getItemJson(item)

							const jsonArray = [
								jsonMap.truename,//姓名
								jsonMap.deptName,//部门
								jsonMap.joinDay,//入职日期
								jsonMap.holidayType,//年假核算标准
								jsonMap.holidayDayBase,//年假基数
								(jsonMap.restHolidayTime != null ? jsonMap.restHolidayTime : '') + '' + (jsonMap.freezeHolidayTime > 0 ? '(另冻结' + jsonMap.freezeHolidayTime + '天)' : '')
								,//剩余调休假
								jsonMap.restHolidayDate,//年假有效期

								jsonMap.restExchangeTime,//剩余调休假
								jsonMap.zhuangtai,
								jsonMap.noUseDate
							]
							console.log(jsonArray)

							_this.OutData.push(jsonArray)
						})
					}
				} catch (e) {
				}
			}).catch(() => {
			})
		},
		async changeStatus(row) {
			let status = row.status == 0 ? 2 : row.status == 2 ? 0 : null
			this.loading = true
			let { data } = await this.baseRequest1('noOrUse', { id: row.id, status })
			if (data.code == 200) {
				this.loading = false
				this.getData()
				this.$message.success('状态修改成功')
			}

		},
		async openHolidayDialog(status, row) {
			this.$refs.addOrEditHoliiday.setVisible(status, row)

		},
		handleCurrentChange: function(val) {
			this.currentPage = val
			this.getData()

		},
		recallApply: function(row, type) {
			const _this = this
			_this.$confirm('该流程已经在审核中，撤回后原审核内容将作废确认撤回吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				const deleting = _this.$notify({
					title: '正在撤回,请稍等',
					type: 'warning'
				})
				const postData = {
					flowMainid: row.id
				}
				_this.baseRequest2(
				 'FlowMainController',
				 'recallApply',
				 postData).then(res => {
					if (res.data.code === 200) {
						_this.getData()
						deleting.close()
						_this.$notify({
							title: '撤回成功',
							type: 'info'
						})
					} else {
						deleting.close()
						_this.dialogVisible = false
						_this.$notify({
							title: '撤回失败',
							type: 'info'
						})
					}
				}).catch((err) => {
					deleting.close()
					_this.$alert(err)
				})
			}).catch(function(error) {
				console.error(error)
			})
		},
		// 初始化获取数据
		getData() {
			const _this = this
			const postData = {
				applyUserName: _this.search.field103, // 申请人名称
				applyTheme: _this.search.field102, // 主题名称
				flowName: _this.search.name, // 流程名称
				auditUser: this.$common.currUser()
				 ? this.$common.currUser().id
				 : '',
				departmentIds: this.departmentIds,
				name: this.search.name,
				pageNum: _this.currentPage,
				pageSize: _this.pageSize
			}
			this.loading = true
			_this.baseRequest1('list', postData).then(res => {
				if (res.data) {
					this.loading = false
					_this.tableData = []
					res.data.rows.forEach(item => {
						item.noUseDate = item.noUseDate ? this.$common.transDate(item.noUseDate) : null
						item.restHolidayDate = item.restHolidayDate ? this.$common.transDate(item.restHolidayDate) : null
						item.joinDay = item.joinDay ? this.$common.transDate(item.joinDay) : null
						item.socialPayDay = item.socialPayDay ? this.$common.transDate(item.socialPayDay) : null
						_this.tableData.push(_this.getItemJson(item))
					})
					_this.allpage = res.data.total
				} else {
					_this.tableData = []
				}
			})
			this.initOutData()
		},
		getItemJson(item) {
			item.xxx = '111'
			return item
		},
		handleSearch: function() {
			this.getData()
		},
		handleReset: function() {
			for (const i in this.search) {
				if (i !== 'pageNum' && i !== 'pageSize') {
					this.search[i] = ''
				}
			}
			this.handleSearch()

		},
		// 打开流程发起菜单
		handleClick(tab, event) {
			this.getData()
		},
		// 请求封装，继承类中调用，必须存在
		baseRequest1(opUrl, postData) {
			return this.$channel.globleRequest(
			 'HolidayManagementController',
			 opUrl,
			 postData,
			 'project task'
			)
		},
		baseRequest2(controller, opUrl, postData) {
			return this.$channel.globleRequest(
			 controller,
			 opUrl,
			 postData,
			 'project task'
			)
		}

	}
}
</script>

<style lang="scss">
.custom-tree-container .block-l {
	/*flex-grow: 2 ;*/
	float: left;
	width: 20%;
	padding: 0 8px 0 0;
}

.custom-tree-container .block-r {
	/*flex-grow: 10;*/
	float: left;
	width: 80%;
	/*padding: 0 0 0 8px;*/
}

.holidayRow {
	.el-select {
		width: 100%;
	}
}

.el-dropdown-link {
	cursor: pointer;
	color: rgba(39, 78, 219, 1);
}

.demonstration {
	display: block;
	color: #8492a6;
	font-size: 14px;
	margin-bottom: 20px;
}

.labeldom {
	.el-tabs__nav-wrap::after {
		background: none;
	}
}

.w200px {
	width: 200px;
}
</style>
<style scoped>
.ch-input .el-input__inner {
	border-radius: 0px;
	border-color: #32323a;
}

.ch-input-size {
	width: 150px;
}

.ch-button {
	borderund-color: #32323a;
	color: #fff;
}

.ch-button-warning {
	margin-left: 10px;
	border-radius: 0px;
	border-color: #E75B5B;
	background-color: #E75B5B;
	color: #fff;
}
</style>
