<template>
	<fs-page>
		<fs-crud ref="crudRef" v-bind="crudBinding"> </fs-crud>
		<PermissionDrawerCom />
		<!-- 小程序二维码对话框 -->
		<el-dialog v-model="qrCodeVisible" title="小程序二维码" width="400px" align-center>
			<div class="qrcode-container">
				<img v-if="qrCodeUrl" :src="qrCodeUrl" alt="小程序二维码" />
				<div v-else class="loading">生成中...</div>
			</div>
		</el-dialog>
		<BatchTagsDialog ref="batchTagsDialogRef" :crudExpose="crudExpose" />
		<BatchStatusDialog ref="batchStatusDialogRef" :crudExpose="crudExpose" />
	</fs-page>
</template>

<script lang="ts" setup name="role">
import { defineAsyncComponent, onMounted, ref, reactive } from 'vue';
import { useFs } from '@fast-crud/fast-crud';
import { createCrudOptions, useBatchUpdateTags } from './crud';
import { RoleDrawerStores } from './stores/RoleDrawerStores';
import { RoleMenuBtnStores } from './stores/RoleMenuBtnStores';
import { RoleMenuFieldStores } from './stores/RoleMenuFieldStores';
import { RoleUsersStores } from './stores/RoleUsersStores';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { successMessage } from '../../../utils/message';
import BatchTagsDialog from './components/BatchTagsDialog.vue';
import BatchStatusDialog from './components/BatchStatusDialog.vue';
import * as api from './api';
import { ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';
const PermissionDrawerCom = defineAsyncComponent(() => import('./components/RoleDrawer.vue'));

// 小程序二维码相关状态
const qrCodeVisible = ref(false);
const qrCodeUrl = ref('');

const RoleDrawer = RoleDrawerStores(); // 角色-抽屉
const RoleMenuBtn = RoleMenuBtnStores(); // 角色-菜单
const RoleMenuField = RoleMenuFieldStores();// 角色-菜单-字段
const RoleUsers = RoleUsersStores();// 角色-用户

// 获取路由实例
const router = useRouter();

const batchTagsDialogRef = ref();
const batchStatusDialogRef = ref();

const selectedRows = ref([]);

// 生成小程序二维码
async function generateQRCode(row: { id: string | number }) {
	console.log(Session.get('tenant_id'));
	try {
		qrCodeVisible.value = true;
		qrCodeUrl.value = ''; // 清空之前的二维码
		
		// 调用系统API获取二维码
		const response = await axios.post(`${import.meta.env.VITE_API_URL}/api/system/wechat/qrcode`, {
			scene: `${Session.get('tenant_id')}`,//row.id
			page: 'pages/index/index',
			width: 430,
			auto_color: false,
			is_hyaline: false
		}, {
			responseType: 'blob' // 接收二进制数据
		});
		
		// 将二进制数据转换为URL
		const blob = new Blob([response.data], { type: 'image/png' });
		qrCodeUrl.value = URL.createObjectURL(blob);
	} catch (error) {
		console.error('生成小程序码失败:', error);
		ElMessage.error('生成小程序二维码失败，请稍后重试');
		qrCodeVisible.value = false;
	}
}

// 检查职位信息是否完整
function checkPositionComplete(row: any): { isComplete: boolean; missing: string[] } {
	const required = [
		{ field: 'title', name: '职位名称' },
		/* { field: 'job_type', name: '职位类型' },
		{ field: 'salary_range', name: '薪资范围' },
		{ field: 'location', name: '工作地点' },
		{ field: 'department', name: '所属部门' },
		{ field: 'requirements', name: '职位要求' },
		{ field: 'description', name: '职位描述' },
		{ field: 'end_date', name: '截止日期' } */
	];

	const missing = required
		.filter(({ field }) => !row[field] || (typeof row[field] === 'string' && row[field].trim() === ''))
		.map(({ name }) => name);

	return {
		isComplete: missing.length === 0,
		missing
	};
}

// 发布职位功能
async function publishPosition(row: any) {
	try {
		const action = row.status === 2 ? '重新发布' : '发布';
		
		// 检查职位信息是否完整
		const { isComplete, missing } = checkPositionComplete(row);
		if (!isComplete) {
			await ElMessageBox.alert(
				`职位信息不完整，缺少以下必填信息：\n${missing.join('、')}\n\n请先完善职位信息后再发布。`,
				'职位信息不完整',
				{
					confirmButtonText: '去完善',
					type: 'warning',
				}
			);
			// 跳转到编辑页面
			router.push(`/position/detail?id=${row.id}`);
			return;
		}

		// 检查截止日期是否过期
		if (row.end_date && new Date(row.end_date) < new Date()) {
			const result = await ElMessageBox.confirm(
				`职位截止日期已过期（${row.end_date}），是否要更新截止日期后再发布？`,
				'截止日期已过期',
				{
					confirmButtonText: '更新并发布',
					cancelButtonText: '取消',
					distinguishCancelAndClose: true,
					type: 'warning',
				}
			);
			
			if (result === 'confirm') {
				// 跳转到编辑页面更新截止日期
				router.push(`/position/detail?id=${row.id}`);
				return;
			}
		}

		// 检查视频状态
		const videoStatusResponse = await api.CheckQuestionVideosStatus({
			position_id: row.id,
			tenant_id: Session.get('tenant_id')
		});

		if (videoStatusResponse.code === 2000) {
			const { is_all_completed, total_questions } = videoStatusResponse.data;
			
			// 检查视频是否全部完成且存在题目
			if (!is_all_completed || total_questions <= 0) {
				await ElMessageBox.alert(
					`无法${action}职位，原因：\n${total_questions <= 0 ? '当前职位没有设置面试题目' : '面试题目视频未全部生成完成'}`,
					'无法发布',
					{
						confirmButtonText: '确定',
						type: 'warning',
					}
				);
				return;
			}
		} else {
			ElMessage.error('检查视频状态失败，请稍后重试');
			return;
		}

		const confirmText = row.status === 2 
			? `确定要重新发布职位 "${row.title}" 吗？`
			: `确定要发布职位 "${row.title}" 吗？发布后求职者即可看到此职位。`;

		// 确认发布对话框
		await ElMessageBox.confirm(
			confirmText,
			`确认${action}`,
			{
				confirmButtonText: `确定${action}`,
				cancelButtonText: '取消',
				type: 'warning',
			}
		);

		// 调用发布API
		const response = await api.PublishPosition({
			job_id: row.id,
			tenant_id:Session.get('tenant_id')
		});

		if (response.code === 2000) {
			successMessage(`职位${action}成功`);
			// 刷新列表数据
			crudExpose.doRefresh();
		} else {
			ElMessage.error(response.msg || `${action}失败`);
		}
	} catch (error) {
		if (error !== 'cancel' && error !== 'close') {
			console.error('发布职位失败:', error);
			ElMessage.error('操作失败，请稍后重试');
		}
	}
}

// 创建 crud 配置
const { crudBinding, crudRef, crudExpose } = useFs({
	createCrudOptions,
	context: { 
		RoleDrawer, 
		RoleMenuBtn, 
		RoleMenuField,
		generateQRCode,
		publishPosition,
		router,
		$message: {
			warning: (msg: string) => successMessage(msg)
		},
		selectedRows: selectedRows,
		openBatchTagsDialog: (selection: any) => {
			batchTagsDialogRef.value.open(selection);
		},
		openBatchStatusDialog: (selection: any) => {
			batchStatusDialogRef.value.open(selection);
		}
	},
});

// 页面打开后获取列表数据
onMounted(async () => {
	// 刷新
	crudExpose.doRefresh();
	// 获取全部用户
	RoleUsers.get_all_users();
	
	// 获取标签列表
	/* await fetchTags(); */
});
</script>

<style scoped>
.qrcode-container {
	display: flex;
	justify-content: center;
	align-items: center;
	min-height: 300px;
}
.qrcode-container img {
	max-width: 100%;
}
.loading {
	font-size: 16px;
	color: #909399;
}
.dialog-footer {
	margin-top: 20px;
	text-align: right;
}
/* 添加标签选择的样式 */
.el-select-dropdown__item {
	padding: 8px 12px;
}
</style>
