<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="120px" ref="ruleFormRef">
			<el-row :gutter="10">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="任务名称" prop="taskName" :rules="[{ required: true, message: '请填写任务名称', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.taskName" placeholder="请填写任务名称" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="计划发送时间" prop="planSendTime" :rules="[{ required: true, message: '请选择计划发送时间', trigger: 'change' }]">
						<el-date-picker
							v-model="state.ruleForm.planSendTime"
							type="datetime"
							placeholder="请选择计划发送时间"
							class="w100"
							value-format="YYYY-MM-DD[T]HH:mm:ss"
							:disabled-date="disabledDate"
						/>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<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-form-item>
				</el-col>
			</el-row>
			<el-divider />
			<div class="mb10">
				<el-button type="primary" @click="addCitizen"> <SvgIcon name="ele-Plus" class="mr5" />添加市民 </el-button>
				<el-upload
					v-model:file-list="fileList"
					action="#"
					:multiple="false"
					ref="uploadListRef"
					name="file"
					:http-request="importCitizen"
					:show-file-list="false"
					v-loading="state.loading"
					class="upload-demo"
				>
					<el-button type="primary"> <SvgIcon name="ele-Upload" class="mr5" /> 导入市民 </el-button>
				</el-upload>
				<el-button type="primary" @click="temDownload"> <SvgIcon name="ele-Download" class="mr5" />模板下载 </el-button>
				<el-button type="danger" @click="onDelete" :disabled="isChecked"> <SvgIcon name="ele-Delete" class="mr5" />批量删除 </el-button>
				<el-button type="danger" @click="onClear"> <SvgIcon name="ele-CircleClose" class="mr5" /> 清空 </el-button>
			</div>
			<vxe-table
				border
				:loading="state.loading"
				:data="state.tableData"
				:column-config="{ resizable: true }"
				:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
				ref="tableRef"
				show-overflow
				:scrollY="{ enabled: true, gt: 100 }"
				showHeaderOverflow
				@checkbox-all="selectAllChangeEvent"
				@checkbox-change="selectChangeEvent"
				max-height="500"
			>
				<vxe-column type="checkbox" width="60" align="center"></vxe-column>
				<vxe-column field="name" title="市民姓名"></vxe-column>
				<vxe-column field="phoneNum" title="联系电话"></vxe-column>
				<vxe-column title="操作" fixed="right" width="90" align="center">
					<template #default="{ row }">
						<el-button link type="danger" @click="onDel(row)" title="删除"> 删除 </el-button>
					</template>
				</vxe-column>
			</vxe-table>
		</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="loading" :disabled="isChecked">确 定</el-button>
			</span>
		</template>
	</el-dialog>
	<citizen-add ref="addCitizenRef" @selectCitizen="selectCitizen" />
</template>

<script setup lang="ts">
import { computed, defineAsyncComponent, nextTick, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { downloadFileByStream, throttle } from '@/utils/tools';
import { removeDuplicate } from '@/utils/arrayOperation';
import { externalCitizenImport, externalCitizenTemplate } from '@/api/auxiliary/externalCitizen';
import { smartCallOutSmsAdd } from '@/api/auxiliary/smartCallOut';

const CitizenAdd = defineAsyncComponent(() => import('@/views/auxiliary/smsTask/components/Add-citizen.vue')); // 创建任务

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		taskName: null,
		planSendTime: null,
		content: null,
		batchSmsTaskDetail: [],
	},
	tableData: [], // 表格内容
});
const disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 8.64e7; // - 8.64e7是今天可以选
};
let loading = ref<boolean>(false); // 加载状态
// 打开弹窗
const ruleFormRef = ref<RefType>();
const openDialog = async () => {
	ruleFormRef.value?.resetFields();
	try {
		state.dialogVisible = true;
	} catch (error) {
		console.log(error);
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	state.tableData = [];
	checkTable.value = [];
};
// 添加市民
const addCitizenRef = ref<RefType>();
const addCitizen = () => {
	addCitizenRef.value.openDialog();
};
// 导入市民
const fileList = ref<EmptyArrayType>([]);
const uploadListRef = ref<RefType>(); // 上传组件ref
const importCitizen = async (file: any) => {
	state.loading = true;
	let fileObj = file.file; // 相当于input里取得的files
	let fd = new FormData(); // FormData 对象
	fd.append('file', fileObj); // 文件对象
	fd.append('needresult', 'true');
	try {
		const { result } = await externalCitizenImport(fd);
		ElMessage.success('导入完成');
		state.tableData = removeDuplicate([...state.tableData, ...result.resultList], 'phoneNum'); // 添加时去重
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
// 模板下载
const temDownload = () => {
	ElMessageBox.confirm(`您确定下载外部市民导入模板，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			externalCitizenTemplate()
				.then((res: any) => {
					state.loading = false;
					downloadFileByStream(res);
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 单个删除
const onDel = (row: any) => {
	ElMessageBox.confirm('确定要删除？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		autofocus: false,
	})
		.then(() => {
			if (row.id) {
				state.tableData = state.tableData.filter((item: any) => item.id !== row.id);
			} else {
				state.tableData = state.tableData.filter((item: any) => item.phoneNum !== row.phoneNum);
			}
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		})
		.catch(() => {});
};
// 批量删除市民
const onDelete = () => {
	ElMessageBox.confirm(`您确定要删除选中的市民?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		autofocus: false,
	})
		.then(() => {
			state.tableData = state.tableData.filter((item: any) => !checkTable.value.includes(item));
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		})
		.catch(() => {});
};
// 清空选择
const onClear = () => {
	ElMessageBox.confirm('确定要清空？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		autofocus: false,
	})
		.then(() => {
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];

			state.tableData = [];
		})
		.catch(() => {});
};
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
// 添加市民后
const selectCitizen = (data: any) => {
	state.tableData = removeDuplicate([...state.tableData, ...data], 'phoneNum'); // 添加时去重
	// 新添加的数据默认选中
	nextTick(() => {
		if (tableRef.value) {
			tableRef.value.setCheckboxRow(data, true);
			checkTable.value = tableRef.value.getCheckboxRecords();
		}
	});
};
// 保存
const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		loading.value = true;
		const request = {
			...state.ruleForm,
			batchSmsTaskDetail: state.tableData,
		};
		smartCallOutSmsAdd(request)
			.then(() => {
				ElMessage({
					message: '短信任务创建成功',
					type: 'success',
				});
				emit('updateList');
			})
			.catch((error) => {})
			.finally(() => {
				loading.value = false;
				closeDialog();
			});
	});
}, 300);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style scoped lang="scss">
.upload-demo {
	display: inline-flex;
	vertical-align: middle;
	margin-right: 12px;
	margin-left: 12px;
}
</style>
