<template>
	<el-dialog title="新增短信" v-model="state.dialogVisible" draggable @close="close">
		<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="110px">
			<el-form-item label="接收者来源" prop="type">
				<el-radio-group v-model="state.ruleForm.type" @change="change">
					<el-radio :value="1">手动录入</el-radio>
					<el-radio :value="2">联系人选择</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item
				label="接收者"
				prop="telNumbers"
				:rules="[{ required: true, message: '请填写接收者', trigger: 'blur' }]"
				v-if="state.ruleForm.type === 1"
			>
				<template #label>
					<div style="height: 34px; display: flex; align-items: center">
						接收者
						<el-tooltip placement="top-start">
							<SvgIcon name="ele-QuestionFilled" size="18px" class="ml3" />
							<template #content> 多个号码请以英文,分隔 </template>
						</el-tooltip>
					</div>
				</template>
				<el-input v-model="state.ruleForm.telNumbers" placeholder="多个号码请以英文,分隔" clearable></el-input>
			</el-form-item>
			<el-form-item label="接收者" prop="userIds" :rules="[{ required: true, message: '请选择接收者', trigger: 'blur' }]" v-else>
				<el-transfer
					v-model="state.ruleForm.userIds"
					filterable
					:filter-method="filterMethod"
					filter-placeholder="姓名/手机号码"
					:data="contacts"
					:props="{
						key: 'id',
						label: 'name',
					}"
					:titles="['待选','已选']"
				>
					<template #default="{ option }">
						<div class="flex-center-align">{{ option.name }} - {{ option.phoneNo }}</div>
					</template>
					<template #left-footer>
						<el-text type="danger">温馨提示：没有电话号码的不显示。</el-text>
					</template>
				</el-transfer>
			</el-form-item>
			<el-form-item label="短信内容" prop="content" :rules="[{ required: true, message: '请填写短信内容', trigger: 'blur' }]">
				<el-input v-model="state.ruleForm.content" placeholder="请填写短信内容" type="textarea" :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
				<el-text type="danger">默认会增加短信提示语！</el-text>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">确 定 </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, ElNotification, FormInstance } from 'element-plus';
import { addKnowledgeHotWords } from '@/api/knowledge/hotWords';
import { messageAdd, messageAddBase } from '@/api/auxiliary/message';
import { removeDuplicate } from '@/utils/arrayOperation';

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

// 定义变量内容
const ruleFormRef = ref<FormInstance>();
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		type: 1, // 热词名称
		sort: 1, // 排序
	},
	loading: false, // 确定按钮loading
});

// 打开弹窗
const openDialog = async () => {
	await getBaseData();
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
const contacts = ref<EmptyArrayType>([]); // 用户列表
const filterMethod = (query: any, item: any) => {
	// 模糊查询条件
	const nameMatch = item.name.toLowerCase().includes(query.toLowerCase());
	const phoneMatch = item.phoneNo.toLowerCase().includes(query.toLowerCase());
	// 返回满足任意一个条件的项目
	return nameMatch || phoneMatch;
};
// 新增
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let request:EmptyObjectType;
		if (state.ruleForm.type === 1) {
			request = {
				telNumbers: state.ruleForm.telNumbers,
				content: state.ruleForm.content,
			};
		} else {
			request = {
				userIds: state.ruleForm.userIds,
				content: state.ruleForm.content,
			};
		}
		messageAdd(request)
			.then((res: any) => {
				emit('updateList');
				closeDialog(); // 关闭弹窗
				state.loading = false;
				ElNotification({
					title: '短信发送完成',
					message: res.result,
					type: 'success',
				});
			})
			.catch(() => {
				emit('updateList');
				state.loading = false;
			});
	});
};
// 获取基础信息
const getBaseData = async () => {
	state.loading = true;
	state.dialogVisible = true;
	try {
		const { result } = await messageAddBase();
		contacts.value = result.contacts ?? [];
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
const change = () => {
	state.ruleForm.telNumbers = '';
	state.ruleForm.array = [];
	ruleFormRef.value?.resetFields('telNumbers');
	ruleFormRef.value?.resetFields('array');
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
