<template>
  <div class="page-container">
	<!--工具栏-->
	<div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
		<el-form :inline="true" :model="filters" :size="size">
			<el-form-item>
				<el-input v-model="filters.name" placeholder="用户名"></el-input>
			</el-form-item>
			<el-form-item>
				<kt-button icon="fa fa-search" :label="$t('action.search')" perms="sys:role:view" type="primary" @click="findPage(null)"/>
			</el-form-item>
			<el-form-item>
				<kt-button icon="fa fa-plus" :label="$t('action.add')" perms="sys:user:add" type="primary" @click="handleAdd" />
			</el-form-item>
		</el-form>
	</div>
	<div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
		<el-form :inline="true" :size="size">
			<el-form-item>
				<el-button-group>
				<el-tooltip content="刷新" placement="top">
					<el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
				</el-tooltip>
				<el-tooltip content="列显示" placement="top">
					<el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
				</el-tooltip>
				<el-tooltip content="导出" placement="top">
					<el-button icon="fa fa-file-excel-o"></el-button>
				</el-tooltip>
				</el-button-group>
			</el-form-item>
		</el-form>
		<!--表格显示列界面-->
		<table-column-filter-dialog ref="tableColumnFilterDialog" :columns="columns"
			@handleFilterColumns="handleFilterColumns">
		</table-column-filter-dialog>
	</div>
	<!--表格内容栏-->
	<kt-table :height="550" permsEdit="sys:user:edit" permsDelete="sys:user:delete"
		:data="pageResult" :columns="filterColumns"
		@findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete">
	</kt-table>
	<!--新增编辑界面-->
	<el-dialog :title="operation?'新增':'编辑'" width="40%" :visible.sync="dialogVisible" :close-on-click-modal="false">
		<el-form :model="dataForm" label-width="80px" :rules="dataFormRules" ref="dataForm" :size="size"
			label-position="right">
			<el-form-item label="ID" prop="id" v-if="false">
				<el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
			</el-form-item>
			<el-form-item label="用户名" prop="name">
        <el-input v-if="!operation" v-model="dataForm.name" auto-complete="off" readonly="true"></el-input>
        <el-input v-if="operation" v-model="dataForm.name" auto-complete="off"></el-input>
			</el-form-item>
			<el-form-item label="真实姓名" prop="truename">
        <el-input v-model="dataForm.truename" auto-complete="off"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input v-model="dataForm.password" type="password" auto-complete="off"></el-input>
			</el-form-item>
      <el-form-item label="身份证" prop="bangIdcard">
        <el-input v-model="dataForm.bangIdcard" auto-complete="off"></el-input>
      </el-form-item>
			<el-form-item label="机构" prop="deptId">
				<el-cascader
          ref="deptTree"
				v-model="dataForm.deptId"
    			size="medium"
    			:options="list"
    			:props="{ checkStrictly: true }"
				style="width:100%"
    			clearable
        @change="deptTreeCurrentChangeHandle"
        ></el-cascader>
				<!-- <popup-tree-input
					:data="deptData"
					:props="deptTreeProps"
					:prop="dataForm.deptName"
					:nodeKey="''+dataForm.deptId"
					:currentChangeHandle="deptTreeCurrentChangeHandle">
				</popup-tree-input> -->
			</el-form-item>
			<!-- <el-form-item label="邮箱" prop="email">
				<el-input v-model="dataForm.email" auto-complete="off"></el-input>
			</el-form-item> -->
			<el-form-item label="手机" prop="mobile">
				<el-input v-model="dataForm.mobile" auto-complete="off"></el-input>
			</el-form-item>
			<el-form-item label="角色" prop="userRoles">
				<el-select v-model="dataForm.userRoles" multiple placeholder="请选择"
					 style="width: 100%;">
					<el-option v-for="item in roles" :key="item.id"
						:label="item.remark" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
      <el-form-item label="职务" prop="job">
        <el-input v-model="dataForm.job" auto-complete="off"></el-input>
      </el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button :size="size" @click.native="dialogVisible = false" @click="cancelRules('dataForm')">{{$t('action.cancel')}}</el-button>
			<el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">{{$t('action.submit')}}</el-button>
		</div>
	</el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput"
import KtTable from "@/views/Core/KtTable"
import KtButton from "@/views/Core/KtButton"
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog"
import { format } from "@/utils/datetime"
export default {
	components:{
		PopupTreeInput,
		KtTable,
		KtButton,
		TableColumnFilterDialog
	},
	data() {
		return {
			list:[],
			address:"",
			size: 'small',
			filters: {
				name: '',
			},
			columns: [],
			filterColumns: [],
			pageRequest: { pageNum: 1, pageSize: 10 },
			pageResult: {},

			operation: false, // true:新增, false:编辑
			dialogVisible: false, // 新增编辑界面是否显示
			editLoading: false,
			dataFormRules: {
				name: [
					{ required: true, message: '请输入用户名', trigger: 'blur' }
				],
        truename: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        deptId: [
          { type: 'array', required: true, message: '请选择机构', trigger: 'change'}
        ]
			},
			// 新增编辑界面数据
			dataForm: {
				id: 0,
				name: '',
				truename:'',
				password: '',
        bangIdcard: '',
				deptId: '',
				deptName: '',
				email: '',
				mobile: '',
        job: '',
				status: 1,
				userRoles: []
			},
			deptData: [],
			deptTreeProps: {
				label: 'name',
				children: 'children'
			},
			roles: []
		}
	},
	methods: {
		// 获取分页数据
		findPage: function (data) {
			if(data !== null) {
				this.pageRequest = data.pageRequest
			}
			this.pageRequest.columnFilters = {name: {name:'name', value:this.filters.name}}
			this.$api.user.findPage(this.pageRequest).then((res) => {
				console.log(res.data)
				this.pageResult = res.data
				this.findUserRoles()
			}).then(data!=null?data.callback:'')
		},
		// 加载用户角色信息
		findUserRoles: function () {
			this.$api.role.findAll().then((res) => {
				// 加载角色集合
				this.roles = res.data
			})
		},
		// 批量删除
		handleDelete: function (data) {
			this.$api.user.batchDelete(data.params).then(data!=null?data.callback:'')
		},
		// 显示新增界面
		handleAdd: function () {
			this.dialogVisible = true
			this.operation = true
			this.dataForm = {
				id: 0,
				name: '',
				password: '',
        bangIdcard: '',
				deptId: '',
				deptName: '',
				email: '',
				mobile: '',
        job: '',
				status: 1,
				userRoles: []
			}
		},
		// 显示编辑界面
		handleEdit: function (params) {
			this.dialogVisible = true
			this.operation = false
			this.dataForm = Object.assign({}, params.row)
			let userRoles = []
			for(let i=0,len=params.row.userRoles.length; i<len; i++) {
				userRoles.push(params.row.userRoles[i].roleId)
			}
			this.dataForm.userRoles = userRoles
		},
		// 编辑
		submitForm: function () {
			this.$refs.dataForm.validate((valid) => {
				if (valid) {
					this.$confirm('确认提交吗？', '提示', {}).then(() => {
						this.dataForm.deptId = this.dataForm.deptId[this.dataForm.deptId.length-1];
						this.dataForm.deptName = "";
						let params = Object.assign({}, this.dataForm)
						let userRoles = []
						for(let i=0,len=params.userRoles.length; i<len; i++) {
							let userRole = {
								userId: params.id,
								roleId: params.userRoles[i]
							}
							userRoles.push(userRole)
						}
						params.userRoles = userRoles
						this.$api.user.save(params).then((res) => {
							this.editLoading = false
							if(res.code == 200) {
								this.$message({ message: '操作成功', type: 'success' })
								this.dialogVisible = false
								this.$refs['dataForm'].resetFields()
							} else {
								this.$message({message: '操作失败, ' + res.msg, type: 'error'})
							}
							this.findPage(null)
						})
					})
				}
			})
		},
		// 获取部门列表
		findDeptTree: function () {
			this.$api.dept.findDeptTree().then((res) => {
				for(var i in res.data){
					res.data[i].value=res.data[i].id
					res.data[i].label=res.data[i].name
					for(var j in res.data[i].children){
						res.data[i].children[j].value=res.data[i].children[j].id
						res.data[i].children[j].label=res.data[i].children[j].name
						for(var n in res.data[i].children[j].children){
							res.data[i].children[j].children[n].value=res.data[i].children[j].children[n].id
						res.data[i].children[j].children[n].label=res.data[i].children[j].children[n].name
						}
					}
				}

				this.list=res.data
				//this.deptData = res.data
			})
		},
		// 菜单树选中
      	deptTreeCurrentChangeHandle (data) {
          console.log(data);
          console.log(data.Id);
		  console.log(this.$refs['deptTree'].currentLabels);
          // this.dataForm.deptId = data.id
			//this.dataForm.deptName = data.name
			// this.dataForm.deptName = data.name
		},
		// 时间格式化
      	dateFormat: function (row, column, cellValue, index){
          	return format(row[column.property])
      	},
		// 处理表格列过滤显示
      	displayFilterColumnsDialog: function () {
			this.$refs.tableColumnFilterDialog.setDialogVisible(true)
      	},
		// 处理表格列过滤显示
      	handleFilterColumns: function (data) {
			this.filterColumns = data.filterColumns
			this.$refs.tableColumnFilterDialog.setDialogVisible(false)
      	},
		// 处理表格列过滤显示
      	initColumns: function () {
			this.columns = [
				{prop:"id", label:"ID", minWidth:50},
				{prop:"name", label:"用户名", minWidth:100},
        {prop:"truename", label:"真实姓名", minWidth:80},
        {prop:"idCard", label:"身份证", minWidth:100},
				{prop:"deptName", label:"机构", minWidth:100},
        {prop:"roleNames", label:"角色", minWidth:80},
        {prop:"job", label:"职务", minWidth:80},

				{prop:"mobile", label:"手机", minWidth:80},

				// {prop:"createBy", label:"创建人", minWidth:120},
				// {prop:"createTime", label:"创建时间", minWidth:120, formatter:this.dateFormat}
				// {prop:"lastUpdateBy", label:"更新人", minWidth:100},
				// {prop:"lastUpdateTime", label:"更新时间", minWidth:120, formatter:this.dateFormat}
			]
			this.filterColumns = JSON.parse(JSON.stringify(this.columns));
      	},
    // 清空验证的提示信息
    cancelRules: function (formName) {
      this.$refs[formName].resetFields();
    }
	},
	mounted() {
		this.findDeptTree()
		this.initColumns()
	}
}
</script>

<style scoped>
.el-tree-node__children{
	overflow: scroll
}
</style>
