<template>
	<div class="dingtalk-config-container">
		<el-card>
			<template #header>
				<div class="card-header">
					<span>钉钉应用配置</span>
					<el-button type="primary" @click="saveConfig">保存配置</el-button>
				</div>
			</template>

			<el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
				<el-form-item label="应用AppKey" prop="appKey">
					<el-input
						v-model="form.appKey"
						placeholder="请输入钉钉应用的AppKey"
						clearable
					/>
				</el-form-item>

				<el-form-item label="应用AppSecret" prop="appSecret">
					<el-input
						v-model="form.appSecret"
						type="password"
						placeholder="请输入钉钉应用的AppSecret"
						clearable
						show-password
					/>
				</el-form-item>

				<el-form-item label="企业ID" prop="corpId">
					<el-input
						v-model="form.corpId"
						placeholder="请输入企业CorpId"
						clearable
					/>
				</el-form-item>

				<el-form-item label="自动同步">
					<el-switch
						v-model="form.autoSync"
						:active-value="1"
						:inactive-value="0"
						active-text="启用"
						inactive-text="禁用"
					/>
				</el-form-item>

				<el-form-item
					label="同步时间"
					prop="syncCron"
					v-if="form.autoSync === 1"
				>
					<el-input
						v-model="form.syncCron"
						placeholder="Cron表达式，如：0 0 2 * * ?（每天凌晨2点）"
						clearable
					>
						<template #append>
							<el-button @click="showCronHelp">帮助</el-button>
						</template>
					</el-input>
					<div class="form-tip">
						默认：0 0 2 * * ?（每天凌晨2点执行同步）
					</div>
				</el-form-item>

				<el-form-item label="配置状态">
					<el-radio-group v-model="form.status">
						<el-radio :label="0">禁用</el-radio>
						<el-radio :label="1">启用</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="validateConfig" :loading="validating">
						验证配置
					</el-button>
					<el-button @click="loadConfig">重新加载</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<!-- Cron表达式帮助对话框 -->
		<el-dialog v-model="cronHelpVisible" title="Cron表达式帮助" width="600px">
			<div class="cron-help">
				<p><strong>格式：</strong>秒 分 时 日 月 周</p>
				<p><strong>示例：</strong></p>
				<ul>
					<li>0 0 2 * * ? - 每天凌晨2点执行</li>
					<li>0 0 */6 * * ? - 每6小时执行一次</li>
					<li>0 0 0 * * 1 - 每周一凌晨执行</li>
					<li>0 30 8 1 * ? - 每月1号早上8:30执行</li>
				</ul>
				<p><strong>特殊字符：</strong></p>
				<ul>
					<li>* : 匹配任意值</li>
					<li>? : 不指定值（仅日和周使用）</li>
					<li>- : 范围，如1-5</li>
					<li>/ : 递增，如0/15表示每15分钟</li>
				</ul>
			</div>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'dingtalk-config'
});

import { ref, reactive, onMounted } from 'vue';
import { useCool } from '/@/cool';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

const { service } = useCool();

// 表单引用
const formRef = ref<FormInstance>();

// 表单数据
const form = reactive({
	id: null as number | null,
	appKey: '',
	appSecret: '',
	corpId: '',
	syncCron: '0 0 2 * * ?',
	autoSync: 1,
	status: 1
});

// 表单验证规则
const rules = reactive<FormRules>({
	appKey: [{ required: true, message: '请输入AppKey', trigger: 'blur' }],
	appSecret: [{ required: true, message: '请输入AppSecret', trigger: 'blur' }],
	corpId: [{ required: true, message: '请输入企业ID', trigger: 'blur' }],
	syncCron: [{ required: true, message: '请输入Cron表达式', trigger: 'blur' }]
});

// 验证中状态
const validating = ref(false);

// Cron帮助对话框
const cronHelpVisible = ref(false);

// 加载配置
async function loadConfig() {
	try {
		const res = await service.dingtalk.config.getConfig();
		if (res) {
			Object.assign(form, res);
		}
	} catch (err: any) {
		console.error('加载配置失败:', err);
	}
}

// 验证配置
async function validateConfig() {
	if (!formRef.value) return;

	await formRef.value.validate(async (valid) => {
		if (valid) {
			try {
				validating.value = true;
				const res = await service.dingtalk.config.validate(form);
				if (res) {
					ElMessage.success('配置验证成功，可以正常连接钉钉API');
				} else {
					ElMessage.error('配置验证失败，请检查配置信息');
				}
			} catch (err: any) {
				ElMessage.error(err.message || '配置验证失败');
			} finally {
				validating.value = false;
			}
		} else {
			ElMessage.warning('请先完善配置信息');
		}
	});
}

// 保存配置
async function saveConfig() {
	if (!formRef.value) return;

	await formRef.value.validate(async (valid) => {
		if (valid) {
			try {
				await service.dingtalk.config.saveOrUpdate(form);
				ElMessage.success('配置保存成功');
				loadConfig();
			} catch (err: any) {
				ElMessage.error(err.message || '配置保存失败');
			}
		} else {
			ElMessage.warning('请先完善配置信息');
		}
	});
}

// 显示Cron帮助
function showCronHelp() {
	cronHelpVisible.value = true;
}

// 组件挂载时加载配置
onMounted(() => {
	loadConfig();
});
</script>

<style lang="scss" scoped>
.dingtalk-config-container {
	padding: 20px;

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.form-tip {
		color: #909399;
		font-size: 12px;
		margin-top: 5px;
	}

	.cron-help {
		p {
			margin: 10px 0;
		}

		ul {
			margin: 10px 0;
			padding-left: 20px;

			li {
				margin: 5px 0;
				color: #606266;
			}
		}

		strong {
			color: #303133;
		}
	}
}
</style>
