<template>
	<el-dialog v-model="state.dialogVisible" width="60%" draggable title="新增推送" @close="close" append-to-body destroy-on-close>
		<el-form :model="state.ruleForm" label-width="110px" ref="ruleFormRef" :disabled="gridOptions.loading">
			<p class="border-title mb10">基本信息</p>
			<el-form-item label="推送报告名称" prop="earlyWarningPushName" :rules="[{ required: true, message: '请填写推送报告名称', trigger: 'blur' }]">
				<el-input v-model="state.ruleForm.earlyWarningPushName" placeholder="请填写推送报告名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="推送部门" prop="pushOrgs" :rules="[{ required: true, message: '请选择推送部门', trigger: 'change' }]">
				<div class="w100">
					<VTreeDrop
						:data="orgsOptions"
						checkable
						keyField="id"
						titleField="name"
						v-model="state.ruleForm.pushOrgs"
						:dropHeight="250"
						dropPlaceholder="推送部门"
						dropdownWidthFixed
						clearable
						searchPlaceholder="推送部门名称"
						checkedButtonText="查看已选"
						:show-footer="false"
						:cascade="false"
						:drop-disabled="gridOptions.loading"
						@checked-change="selectOrg"
					>
					</VTreeDrop>
				</div>
			</el-form-item>
		</el-form>
		<p class="border-title mb10 mt20">推送工单</p>
		<vxe-grid v-bind="gridOptions">
			<template #toolbar_buttons>
				<el-button type="primary" @click="selectOrders">选择工单</el-button>
			</template>
			<template #order_detail="{ row }">
				<order-detail :order="row.order">{{ row.order?.title }}</order-detail>
			</template>
			<template #statusText="{ row }">
				<el-text type="danger" tag="b" v-if="[1, 2, 3, 9, 101, 102, 103, 104, 105, 200].includes(row.order?.status)">{{
					row.order?.statusText
				}}</el-text>
				<span v-else>{{ row.order?.statusText }}</span>
			</template>
		</vxe-grid>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="warning" @click="onSubmit(ruleFormRef, 1)" :loading="gridOptions.loading">暂存</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef, 3)" :loading="gridOptions.loading">生成报告并推送</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef, 2)" :loading="gridOptions.loading">推 送</el-button>
			</span>
		</template>
		<!-- 选择工单 -->
		<push-select ref="pushSelectRef" @selectOrder="selectOrder" />
	</el-dialog>
</template>

<script setup lang="tsx">
import { defineAsyncComponent, reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { throttle } from '@/utils/tools';
import { VTreeDrop } from '@wsfe/vue-tree';
import { getCanUseOrg } from '@/api/system/user';
import { removeDuplicate } from '@/utils/arrayOperation';
import { addEarlyPush } from '@/api/early/push';

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

const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const PushSelect = defineAsyncComponent(() => import('@/views/early/push/components/Push-select.vue')); // 选择工单

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		earlyWarningPushName: null, // 推送报告名称
		pushOrgs: [], // 推送部门
	},
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 10, // 每页条数
		Keyword: null, // 关键字
	},
	total: 0, // 总条数
});
const gridOptions = reactive<any>({
	loading: false,
	border: true,
	showOverflow: true,
	columnConfig: {
		resizable: true,
	},
	scrollY: {
		enabled: true,
		gt: 100,
	},
	toolbarConfig: {
		slots: {
			buttons: 'toolbar_buttons',
		},
	},
	rowConfig: { isHover: true, height: 30, isCurrent: true, useKey: true, keyField: 'id' },
	minHeight: 300,
	maxHeight: 500,
	columns: [
		{
			field: 'isSendWord',
			title: '是否展示附件',
			width: 110,
			slots: {
				default: ({ row }) => {
					return <el-checkbox v-model={row.isSendWord}></el-checkbox>;
				},
			},
		},
		{
			field: 'order.title',
			title: '工单标题',
			minWidth: 200,
			slots: { default: 'order_detail' },
		},
		{
			field: 'order.no',
			title: '工单编码',
			width: 140,
		},
		{
			field: 'order.hotspotName',
			title: '热点分类',
		},
		{
			field: 'order.currentStepName',
			title: '当前节点',
		},
		{
			field: 'order.statusText',
			title: '工单状态',
			width: 100,
			slots: {
				default: 'statusText',
			},
		},
		{
			field: 'orderPushStatusText',
			title: '推送状态',
			width: 100,
		},
		{
			title: '操作',
			width: 90,
			align: 'center',
			slots: {
				default: ({ row }) => {
					return (
						<el-button link type="danger" onClick={() => onDelete(row)}>
							删除
						</el-button>
					);
				},
			},
		},
	],
	data: [],
});
// 打开弹窗
const ruleFormRef = ref<RefType>();
const openDialog = async () => {
	try {
		state.dialogVisible = true;
		queryBaseInfo();
	} catch (error) {
		console.log(error);
	}
};
const queryList = () => {};
// 获取基础信息
const orgsOptions = ref<EmptyArrayType>([]); // 来源单位
const queryBaseInfo = () => {
	gridOptions.loading = true;
	getCanUseOrg()
		.then((res: any) => {
			orgsOptions.value = res.result ?? [];
			gridOptions.loading = false;
		})
		.catch((err) => {
			console.log(err);
			gridOptions.loading = false;
		});
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	gridOptions.data = [];
};
// 选择工单
const pushSelectRef = ref<RefType>();
const selectOrders = () => {
	pushSelectRef.value.openDialog();
};
// 选择部门
const selectOrg = (data: any) => {
	if (data.length) {
		state.ruleForm.pushOrg = data.map((item: any) => {
			return {
				orgCode: item.id,
				orgName: item.name,
			};
		});
	} else {
		state.ruleForm.pushOrg = [];
	}
};
// 选择了推送工单
const selectOrder = (order: any) => {
	gridOptions.data = removeDuplicate([...gridOptions.data, ...order], 'id'); // 去重
};
// 删除工单
const onDelete = (row: any) => {
	const index = gridOptions.data.findIndex((item: any) => item.no === row.no);
	gridOptions.data.splice(index, 1);
};
// 新增
// operateModel 操作方式 1：暂存 2：推送 3：推送并生成报告
const onSubmit = throttle(async (formEl: FormInstance | undefined, operateModel: number) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		gridOptions.loading = true;
		const earlyWarningPushDetails = gridOptions.data.map((item: any) => {
			return {
				orderId: item.order.id,
				isSendWord: item.isSendWord ?? false,
			};
		});
		const request = {
			...state.ruleForm,
			earlyWarningPushDetails,
			operateModel,
		};
		addEarlyPush(request)
			.then(() => {
				ElMessage({
					message: '新增成功',
					type: 'success',
				});
				emit('updateList');
			})
			.catch((error) => {})
			.finally(() => {
				gridOptions.loading = false;
				closeDialog();
			});
	});
}, 300);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
