<template>
	<el-dialog v-model="state.dialogVisible" draggable title="平级移动" destroy-on-close append-to-body>
		<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent :disabled="loading">
			<el-form-item label="用户名称" prop="name">
				<el-input v-model="state.queryParams.name" placeholder="用户名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleQuery" :loading="loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="loading">
					<SvgIcon name="ele-Refresh" class="mr5" />重置
				</el-button>
			</el-form-item>
		</el-form>
		<vxe-table
			border
			:loading="loading"
			:data="state.tableData"
			:sort-config="{ remote: true }"
			:column-config="{ resizable: true }"
			:row-config="{ isHover: true, height: 30, useKey: true }"
			ref="tableRef"
			max-height="500px"
			show-overflow
			:scrollY="{ enabled: true, gt: 100 }"
			@radio-change="radioChangeEvent"
			:radio-config="{ labelField: 'username', highlight: true }"
		>
			>
			<vxe-column type="radio" fixed="left" title="请选择"></vxe-column>
			<vxe-column field="orgName" title="任职部门"></vxe-column>
			<vxe-column field="roleNames" title="用户职位" min-width="200"></vxe-column>
		</vxe-table>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="loading" :disabled="!selectRow">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { throttle } from '@/utils/tools';
import {
	migrationOrder,
	migrationOrderChange,
	migrationOrderList,
	migrationOrderPublish,
	migrationOrderVisit,
	migrationOrderVisitList,
} from '@/api/todo/center';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		employee: null, // 当前用户
	},
	queryParams: {
		name: null,
	},
	tableData: [],
});
const queryList = async () => {
	state.dialogVisible = true;
	loading.value = true;
	selectRow.value = null;
	switch (migrationType.value) {
		case 'centerTodo': // 中心待办
			try {
				const { result } = await migrationOrder(dataRow.value.id);
				stepId.value = result.stepId;
				orderId.value = result.orderId;
				state.tableData = result.handlers;
				if (state.queryParams.name) {
					state.tableData = state.tableData.filter((data: any) => {
						return String(data['username']).toLowerCase().indexOf(state.queryParams.name) > -1;
					});
				}
				loading.value = false;
			} catch (e) {
				loading.value = false;
			}
			break;
		case 'publishTodo': // 发布
			try {
				const response = await migrationOrderList();
				state.tableData = response.result;
				if (state.queryParams.name) {
					state.tableData = state.tableData.filter((data: any) => {
						return String(data['username']).toLowerCase().indexOf(state.queryParams.name) > -1;
					});
				}
				loading.value = false;
			} catch (e) {
				loading.value = false;
			}
			break;
		case 'visitTodo': // 回访
			try {
				const responseVisit = await migrationOrderVisitList();
				state.tableData = responseVisit.result;
				if (state.queryParams.name) {
					state.tableData = state.tableData.filter((data: any) => {
						return String(data['username']).toLowerCase().indexOf(state.queryParams.name) > -1;
					});
				}
				loading.value = false;
			} catch (e) {
				loading.value = false;
			}
			break;
		default:
			break;
	}
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
let loading = ref<boolean>(false); // 加载状态
// 打开弹窗
const ruleFormRef = ref<RefType>();
const migrationType = ref<string>(''); // 移动类型
const stepId = ref<string>(''); // 平移ID
const orderId = ref<string>(''); // 工单ID
const dataRow = ref<EmptyObjectType>({}); // 当前数据
const orderIds = ref<string[]>([]); // 工单ID
const openDialog = async (type: string, formData: any) => {
	state.tableData = [];
	migrationType.value = type;
	switch (type) {
		case 'centerTodo':
			dataRow.value = formData;
			break;
		case 'publishTodo':
		case 'visitTodo':
			orderIds.value = formData;
			break;
		default:
			break;
	}
	try {
		await queryList();
	} catch (error) {
		console.log(error);
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const tableRef = ref<RefType>();
const selectRow = ref<any>(null);
const radioChangeEvent = ({ row }) => {
	selectRow.value = row;
};

// 保存
const onSubmit = throttle(async () => {
	loading.value = true;
	switch (migrationType.value) {
		case 'centerTodo': // 中心待办
			const request = {
				stepId: stepId.value,
				orderId: orderId.value,
				handler: selectRow.value,
			};
			migrationOrderChange(request)
				.then(() => {
					ElMessage({
						message: '平级移动成功',
						type: 'success',
					});
					closeDialog();
					emit('updateList');
					loading.value = false;
				})
				.catch((err: any) => {
					console.log(err);
					loading.value = false;
				});
			break;
		case 'publishTodo': // 发布待办
			const publishRequest = {
				orderIds: orderIds.value,
				userId: selectRow.value.userId,
			};
			migrationOrderPublish(publishRequest)
				.then(() => {
					ElMessage({
						message: '平级移动成功',
						type: 'success',
					});
					closeDialog();
					emit('updateList');
					loading.value = false;
				})
				.catch((err: any) => {
					console.log(err);
					loading.value = false;
				});
			break;
		case 'visitTodo': // 回访待办
			const visitRequest = {
				ids: orderIds.value,
				userId: selectRow.value.userId,
			};
			migrationOrderVisit(visitRequest)
				.then(() => {
					ElMessage({
						message: '平级移动成功',
						type: 'success',
					});
					closeDialog();
					emit('updateList');
					loading.value = false;
				})
				.catch((err: any) => {
					console.log(err);
					loading.value = false;
				});
			break;
		default:
			break;
	}
}, 300);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
