<template>
	<div class="page-container row-container">
		<!-- 左侧区域 -->
		<section class="list-part-container" style="flex: 2">
			<!-- 搜索区 -->
			<el-form class="list-search-container" :model="queryDeptParams" ref="queryRef" :inline="true">
				<el-form-item class="section-title" label="部门管理" />
				<el-form-item >
					<el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['business:department:add']">新增</el-button>
				</el-form-item>
				<el-form-item label="部门编码：" prop="deptCode">
					<el-input v-model.trim="queryDeptParams.deptCode" placeholder="请输入部门编码" @keydown.enter.prevent @keyup.enter="handleSearch" clearable style="width: 130px" />
				</el-form-item>
				<el-form-item>
					<el-button type="info" icon="Search" @click="handleSearch">搜索</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="success"  @click="handleCentralizedTurnover"  v-hasPermi="['business:department:innerTurnover']">集中周转</el-button>
				</el-form-item>
			</el-form>
			<!-- 列表区 -->
			<div class="el-table-container">
				<div class="el-table-inner-container">
					<!-- 列表区 -->
					<el-table ref="departmentTable" v-loading="deptLoading" :data="deptList" row-key="id" height="100%" :indent="20" default-expand-all highlight-current-row @current-change="handleGetUser">
						<el-table-column label="行号" type="index" width="50" align="center" />
						<el-table-column label="部门名称" prop="label" align="center" />
						<el-table-column label="部门编码" prop="deptCode" align="center" />
						<!-- <el-table-column label="是否企业" prop="deptType" width="70" align="center">
              <template #default="scope">
                <dict-tag :options="dept_type" :value="scope.row.deptType" />
              </template>
            </el-table-column> -->
						<el-table-column label="是否工段" prop="isWorkSection" width="70" align="center">
							<template #default="scope">
								<dict-tag :options="work_section_status" :value="scope.row.isWorkSection" />
							</template>
						</el-table-column>
						<el-table-column label="是否分选" prop="isSortPackaging" width="70" align="center">
							<template #default="scope">
								<dict-tag :options="yes_no" :value="scope.row.isSortPackaging" />
							</template>
						</el-table-column>
						<el-table-column label="操作" width="150" align="center" v-hasPermi="['business:department:edit']">
							<template #default="scope">
								<el-button link type="warning" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:department:edit']">编辑</el-button>
								<el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:department:remove']">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
		</section>

		<!-- 右侧区域 -->
		<section class="list-part-container" style="flex: 3">
			<!-- 搜索区 -->
			<el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
				<el-form-item class="section-title" label="员工" />
				<el-form-item>
					<el-button type="primary" icon="Plus" :disabled="deptList.length == 0" @click="openUser">新增</el-button>
					<el-button type="danger" icon="Delete" :disabled="ids.length == 0" @click="handleUserDelete"> 删除</el-button>
				</el-form-item>
			</el-form>

			<!-- 列表区 -->
			<div class="el-table-container">
				<div class="el-table-inner-container">
					<el-table v-loading="userLoading" :data="userList" row-key="id" height="100%" @selection-change="handleSelectionChange">
						<el-table-column type="selection" width="40" align="center" />
						<el-table-column type="index" label="行号" width="50" align="center" />
						<el-table-column label="员工编码" width="100" prop="user.userName" align="center" />
						<el-table-column label="员工姓名" width="100" prop="user.nickName" align="center" />
						<el-table-column label="性别" width="50" prop="user.sex" align="center" />
						<el-table-column label="手机号码" width="120" prop="user.phoneNumber" align="center" />
						<el-table-column label="部门负责人" width="90" align="center">
							<template #default="scope">
								<dict-tag :options="yesOrNo" :value="scope.row.isLeader" />
							</template>
						</el-table-column>
						<el-table-column label="调度人员" width="90" align="center">
							<template #default="scope">
								<dict-tag :options="yesOrNo" :value="scope.row.isDispatcher" />
							</template>
						</el-table-column>
						<el-table-column label="工段长" width="90" align="center">
							<template #default="scope">
								<dict-tag :options="yesOrNo" :value="scope.row.isFormman" />
							</template>
						</el-table-column>
						<el-table-column label="调机班长" width="90" align="center">
							<template #default="scope">
								<dict-tag :options="yesOrNo" :value="scope.row.isYardman" />
							</template>
						</el-table-column>
						<el-table-column label="操作" prop="phoneNumber" align="center">
							<template #default="scope">
								<el-button link type="warning" icon="Edit" @click="handleUpdateUser(scope.row)" v-hasPermi="['business:department:edit']">编辑</el-button>
							</template>
						</el-table-column>
						<el-table-column />
					</el-table>
				</div>
			</div>
			<!-- 分页 -->
			<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getUserList" />
		</section>
		<!-- 部门管理表单 -->
		<dept-form ref="deptRef" @handleSaveSuccess="getList" />
		<!-- 员工选择弹窗 -->
		<person ref="personRef" :multiple="multiple" :multiple-selected="handleMultipleSelected" />
		<!-- 员工编辑表单 -->
		<user-form ref="updateUser" @handleSaveSuccess="getUserList" />
		<!-- 内部周转人员弹窗 -->
		<inner-turnover-dialog ref="innerTurnoverRef" @handleSaveSuccess="getList" />
	</div>
</template>

<script setup name="Process">
import { saveDeptUser, deptTreeSelect, delDeptUser, getDeptUser } from '@/api/system/user'
import { delDept } from '@/api/system/dept'
import { deleteGroupDetail } from '@/api/business/resourceGroupDetail'
import deptForm from './form'
import userForm from './formUser'
import person from '@/views/dialog/person.vue'
import innerTurnoverDialog from './DialogInnerTurnover.vue'

const { proxy } = getCurrentInstance()
/**字典 */
const { work_section_status } = proxy.useDict('work_section_status')
const { yes_no } = proxy.useDict("yes_no");
//部门
const currentDept = ref({})
const deptList = ref([])
const deptLoading = ref(true)
//员工
const userList = ref([])
const userLoading = ref(false)
const total = ref(0)
const ids = ref([])

const single = ref(true)
const multiple = ref(true)
/** 查询对象 */
const queryParams = ref({
	deptId: 0,
	pageNum: 1,
	pageSize: 10,
	code: '',
	name: '',
})
const queryDeptParams = ref({
	deptCode: '',
})

const yesOrNo = [
	{ label: '是', value: '1', elTagType: 'primary', elTagClass: '' },
	{ label: '否', value: '0', elTagType: 'danger', elTagClass: '' },
]

/***********************  方法区  ****************************/
/***********************  部门管理相关事件  ****************************/
/** 查询工段列表 */
function getList() {
	deptLoading.value = true
	deptTreeSelect(queryDeptParams.value).then((response) => {
		deptList.value = response.data.filter((item) => {
			return item.deptType == '0'
		})
		if (deptList.value.length > 0) {
			currentDept.value = deptList.value[0]
			proxy.$refs.departmentTable.setCurrentRow(deptList.value[0])
		} else {
			userList.value = []
		}
		deptLoading.value = false
	})
}
/**部门查询 */
function handleSearch() {
	getList()
}
/** 部门新增按钮操作 */
function handleAdd() {
	proxy.$refs.deptRef.open()
}
/** 部门修改按钮操作 */
function handleUpdate(row) {
	proxy.$refs.deptRef.open(row)
}
/**部门名称表点击事件 */
function handleGetUser(row) {
	if (row) {
		currentDept.value = row
		getUserList()
	} else {
		userList.value = []
		total.value = 0
	}
}
/*********************** 集中周转相关事件  ****************************/
function handleCentralizedTurnover() {
	console.log(currentDept.value)
	proxy.$refs.innerTurnoverRef.open(currentDept.value)
}

/***********************  员工相关事件  ****************************/

//打开添加人员
const openUser = () => {
	handleAddBatchUsers()
}
/** 新增员工 */
function handleAddBatchUsers() {
	multiple.value = true
	const userInfo = {}
	userInfo.identifying = true
	userInfo.deptId = currentDept.value.id
	proxy.$refs.personRef.open(userInfo)
}
/**员工多选带回 */
function handleMultipleSelected(selection) {
	var newList = []
	for (var i = 0; i < selection.length; ++i) {
		var newPerson = {}
		newPerson.userId = selection[i].userId
		newPerson.deptId = currentDept.value.id
		newList.push(newPerson)
	}
	saveDeptUser(newList).then((response) => {
		if (response.code == 200) {
			proxy.$modal.msgSuccess('操作成功')
			handleGetUser(currentDept.value)
		}
	})
}

// 多选框选中数据
function handleSelectionChange(selection) {
	ids.value = selection.map((item) => {
		return { userId: item.userId, deptId: currentDept.value.id }
	})
	single.value = selection.length != 1
	multiple.value = !selection.length
}

/** 获取员工列表 */
function getUserList() {
	userLoading.value = true
	queryParams.value.deptId = currentDept.value.id
	getDeptUser(queryParams.value).then((response) => {
		if (response.code == 200) {
			userList.value = response.rows
			userLoading.value = false
			total.value = response.total
		}
	})
}

/** 员工修改按钮操作 */
function handleUpdateUser(row) {
	const userData = row
	userData.deptId = queryParams.value.deptId
	userData.sysDept = currentDept.value
	proxy.$refs.updateUser.open(userData)
}

/** 员工删除按钮操作 */
function handleDelete(row) {
	var showErrorMessage = false
	const _ids = row.id || ids.value
	proxy.$modal
		.confirm('是否确认删除选中的数据项？')
		.then(function () {
			if (row.children) {
				showErrorMessage = true
				return Promise.reject(new Error('HasChildrenError'))
			}
			return delDept(_ids)
		})
		.then(() => {
			getList()
			proxy.$modal.msgSuccess('删除成功！')
		})
		.catch(() => {})
		.finally(() => {
			if (showErrorMessage) {
				proxy.$modal.msgError('该部门下有子部门，不能删除！')
			}
		})
}
/** 人员删除按钮操作 */
function handleUserDelete(row) {
	proxy.$modal
		.confirm('是否确认删除选中的人员,资源组明细也将同步删除该人员？')
		.then(function () {
			return delDeptUser(ids.value)
		})
		.then(function () {
			deleteGroupDetail(ids.value)
		})
		.then(() => {
			handleGetUser(currentDept.value)
			proxy.$modal.msgSuccess('删除成功！')
		})
		.catch(() => {})
}
onMounted(() => {
	getList()
})
</script>
