<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <!-- 顶部操作按钮 -->
            <el-row class="mb10">
                <div class="form-header-actions" style="width: 100%;">
                    <div></div>
                    <div style="margin-left:auto;">
                        <el-button icon="View" @click="handleViewWorkflow">
                            {{ t('workbench.approval.viewWorkflow') }}
                        </el-button>
                    </div>
                </div>
            </el-row>

            <!-- 标题、描述、附件 -->
            <el-row class="mb10">
                <el-form :model="headerForm" label-width="60px" class="w-full">
                    <el-form-item :label="t('workbench.approval.formTitle')">
                        <el-input v-model="headerForm.title" :placeholder="t('workbench.approval.inputTitleTip')"
                            readonly />
                    </el-form-item>
                    <el-form-item :label="t('workbench.approval.description')">
                        <el-input v-model="headerForm.description"
                            :placeholder="t('workbench.approval.inputDescriptionTip')" readonly />
                    </el-form-item>
                    <el-form-item :label="t('workbench.approval.attachments')">
                        <div class="attachment-list">
                            <template v-if="headerForm.attachments && headerForm.attachments.length">
                                <a v-for="(file, index) in headerForm.attachments" :key="index" :href="file.url"
                                    target="_blank" class="attachment-item">
                                    <el-icon class="attachment-icon">
                                        <Document />
                                    </el-icon>
                                    <span>{{ file.name }}</span>
                                    <span v-if="file.size" class="file-size">（{{ file.size }}）</span>
                                </a>
                            </template>
                            <span v-else>-</span>
                        </div>
                    </el-form-item>
                </el-form>
            </el-row>

            <!-- 居中标题 + 基本信息 -->
            <el-row class="mb10 header-summary">
                <div class="title">{{ t('workbench.approval.title') }}</div>
            </el-row>
            <el-row class="mb10 header-meta">
                <div class="meta-item">{{ t('workbench.approval.reporter') }}：{{ displayReporter }}</div>
                <div class="meta-item">{{ t('workbench.approval.reportingUnit') }}：{{ displayUnit }}</div>
                <div class="meta-item">{{ t('workbench.approval.date') }}：{{ displayDate }}</div>
                <div class="meta-item">{{ t('workbench.approval.serialNumber') }}：{{ serialNumber }}</div>
            </el-row>

            <!-- 专家信息表格 -->
            <el-table :data="expertList" border style="width: 100%;" highlight-current-row>
                <el-table-column width="60">
                    <template #default="scope">
                        <el-radio v-model="selectedRowIndex" :label="scope.$index"
                            @change="handleRowSelect(scope.$index)">&nbsp;</el-radio>
                    </template>
                </el-table-column>
                <el-table-column type="index" :label="t('workbench.approval.table.index')" width="60" />
                <el-table-column prop="name" :label="t('workbench.approval.table.name')" min-width="200">
                    <template #default="scope">
                        <el-input v-model="scope.row.name" :placeholder="t('workbench.approval.table.inputPlaceholder')"
                            readonly />
                    </template>
                </el-table-column>
                <el-table-column prop="contactMethod" :label="t('workbench.approval.table.contact')" min-width="160">
                    <template #default="scope">
                        <el-input v-model="scope.row.contactMethod"
                            :placeholder="t('workbench.approval.table.inputPlaceholder')" readonly />
                    </template>
                </el-table-column>
                <el-table-column prop="techField" :label="t('workbench.approval.table.field')" min-width="160">
                    <template #default="scope">
                        <el-input v-model="scope.row.techField"
                            :placeholder="t('workbench.approval.table.inputPlaceholder')" readonly />
                    </template>
                </el-table-column>
                <el-table-column prop="professionalTitle" :label="t('workbench.approval.table.title')" min-width="160">
                    <template #default="scope">
                        <el-input v-model="scope.row.professionalTitle"
                            :placeholder="t('workbench.approval.table.inputPlaceholder')" readonly />
                    </template>
                </el-table-column>
                <el-table-column prop="workUnit" :label="t('workbench.approval.table.company')" min-width="200">
                    <template #default="scope">
                        <el-input v-model="scope.row.workUnit"
                            :placeholder="t('workbench.approval.table.inputPlaceholder')" readonly />
                    </template>
                </el-table-column>
                <el-table-column prop="level" :label="t('workbench.approval.table.level')" min-width="120">
                    <template #default="scope">
                        <el-input :value="levelLabel(scope.row.level)"
                            :placeholder="t('workbench.approval.table.inputPlaceholder')" readonly />
                    </template>
                </el-table-column>
                <el-table-column prop="status" :label="t('workbench.approval.table.status')" min-width="140">
                    <template #default="scope">
                        <el-input v-model="scope.row.status"
                            :placeholder="t('workbench.approval.table.inputPlaceholder')" readonly />
                    </template>
                </el-table-column>
                <el-table-column :label="t('workbench.approval.table.action')" width="100" fixed="right">
                    <template #default="{ row }">
                        <el-button link type="primary" @click="handleViewDetail(row)">
                            {{ t('common.viewBtn') || '查看' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <!-- 审批操作组件 -->
        <ApprovalAction class="approval-action" :status="approvalStatus" :approval-records="approvalRecords"
            @approve="(opinion, attachments) => handleApprove(opinion, attachments)"
            @reject="(opinion, attachments) => handleReject(opinion, attachments)"
            @withdraw="(opinion) => handleWithdraw(opinion)" @add-attachment="handleAddAttachment" />

        <!-- 专家详情弹窗 -->
        <ExpertDetailDialog v-model:visible="detailDialogVisible" :detail="currentDetail" :meta="detailMeta" />
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { formatDate } from '/@/utils/formatTime';
import { useUserInfo } from '/@/stores/userInfo';
import { useMessage } from '/@/hooks/message';
import ExpertDetailDialog from '/@/components/investment/ExpertDetailDialog.vue';
import ApprovalAction from '/@/components/workbench/common/ApprovalAction.vue';
import type { ApprovalRecord } from '/@/components/workbench/common/ApprovalAction.vue';
import { Document } from '@element-plus/icons-vue';

const { t } = useI18n();

const headerForm = reactive({
    title: '',
    description: '',
    attachments: [] as any[],
});

const userInfoStore = useUserInfo();
const displayReporter = ref(userInfoStore.userInfos.user?.username || '王小明');
const displayUnit = ref(userInfoStore.userInfos.user?.deptName || 'xxx公司');
const displayDate = ref(formatDate(new Date(), 'YYYY-mm-dd'));
const serialNumber = ref('-');

const expertList = ref<any[]>([]);
const selectedRowIndex = ref(-1);

// 详情弹窗
const detailDialogVisible = ref(false);
const currentDetail = ref<any>({});
const detailMeta = reactive({
    reporter: displayReporter.value,
    unit: displayUnit.value,
    date: displayDate.value,
});

// 审批状态和记录
const approvalStatus = ref<'pending' | 'reviewed' | 'withdrawable'>('pending');
const approvalRecords = ref<ApprovalRecord[]>([]);

/**
 * 加载审核数据
 */
const loadApprovalData = async () => {
    // TODO: 根据 taskId 调用API获取审核数据
    // const res = await getExpertApprovalDetailAPI(taskId.value);

    // 模拟数据
    headerForm.title = `${displayReporter.value}-专家信息申报-${displayUnit.value}-${serialNumber.value}`;
    headerForm.description = 'xxx';
    headerForm.attachments = [
        { name: 'xxx.pdf', size: '200kB', url: '#' },
        { name: 'xxx.pdf', size: '200kB', url: '#' },
    ];

    expertList.value = [
        {
            id: 1,
            name: 'xxx',
            contactMethod: 'xxx',
            techField: 'xxx',
            professionalTitle: 'xxx',
            workUnit: 'xxx',
            level: 'national',
            status: 'xxx',
            attachments: [{ name: 'xxx.pdf', size: '200kB', url: '#' }],
            evidences: [{ name: 'xxx.pdf', size: '200kB', url: '#' }],
        },
        {
            id: 2,
            name: 'xxx',
            contactMethod: 'xxx',
            techField: 'xxx',
            professionalTitle: 'xxx',
            workUnit: 'xxx',
            level: 'provincial',
            status: 'xxx',
            attachments: [{ name: 'xxx.pdf', size: '200kB', url: '#' }],
            evidences: [{ name: 'xxx.pdf', size: '200kB', url: '#' }],
        },
    ];

    // 加载审批记录
    // TODO: 根据 taskId 调用API获取审批记录
    approvalRecords.value = [
        {
            nodeName: 'xxxx节点',
            office: 'XX办公室',
            personName: '王小明',
            time: '2025-07-01 10:00:00',
            action: '发起审批',
            isActive: false,
        },
        {
            nodeName: 'xxx节点',
            office: 'XX办公室',
            personName: '张XX',
            time: '2025-07-01 11:00:00',
            status: 'approved',
            opinion: '请给XXX审核',
            isActive: true,
        },
    ];

    // TODO: 根据实际状态设置 approvalStatus
    // approvalStatus.value = 'pending'; // 待审核
    // approvalStatus.value = 'reviewed'; // 已审核
    // approvalStatus.value = 'withdrawable'; // 可撤回
};

const handleRowSelect = (index: number) => {
    selectedRowIndex.value = index;
};

const handleViewWorkflow = () => {
    useMessage().info(t('workbench.approval.viewWorkflowClicked'));
    // TODO: 跳转到流程查看页面
};

const handleViewDetail = (row: any) => {
    currentDetail.value = {
        ...row,
        attachments: row.attachments || [],
        evidences: row.evidences || [],
    };
    detailMeta.reporter = displayReporter.value;
    detailMeta.unit = displayUnit.value;
    detailMeta.date = displayDate.value;
    detailDialogVisible.value = true;
};

const levelLabel = (val: string) => {
    if (val === 'national') return t('expertApply.level.national');
    if (val === 'provincial') return t('expertApply.level.provincial');
    if (val === 'city') return t('expertApply.level.city');
    return val || '-';
};

// 审批操作处理
const handleApprove = (opinion: string, attachments: any[]) => {
    useMessage().success(t('workbench.approval.opinion.approve') + '成功');
    // TODO: 调用审批通过API
    // const res = await approveAPI(taskId.value, { opinion, attachments });
    void opinion; // 避免 lint 错误，实际使用时将移除
    void attachments; // 避免 lint 错误，实际使用时将移除
    // 重新加载数据
    loadApprovalData();
};

const handleReject = (opinion: string, attachments: any[]) => {
    useMessage().success(t('workbench.approval.opinion.reject') + '成功');
    // TODO: 调用审批驳回API
    // const res = await rejectAPI(taskId.value, { opinion, attachments });
    void opinion; // 避免 lint 错误，实际使用时将移除
    void attachments; // 避免 lint 错误，实际使用时将移除
    // 重新加载数据
    loadApprovalData();
};

const handleWithdraw = (opinion: string) => {
    useMessage().success(t('workbench.approval.opinion.withdraw') + '成功');
    // TODO: 调用撤回API
    // const res = await withdrawAPI(taskId.value, { opinion });
    void opinion; // 避免 lint 错误，实际使用时将移除
    // 重新加载数据
    loadApprovalData();
};

const handleAddAttachment = () => {
    useMessage().info('添加附件功能待实现');
    // TODO: 打开文件选择对话框
};

onMounted(() => {
    loadApprovalData();
});
</script>

<style scoped>
.layout-padding {
    display: flex;
    flex-direction: row;
}

.layout-padding-auto {
    width: 70%;
}

.approval-action {
    width: 30%;
    margin-left: 20px;
    margin-top: 0px;
}

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

.header-summary .title {
    margin: 0 auto;
    font-size: 18px;
    font-weight: 600;
    text-align: center;
}

.header-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 0 20px;
}

.header-meta .meta-item {
    color: var(--el-text-color-regular);
}

.attachment-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.attachment-item {
    display: flex;
    align-items: center;
    color: var(--el-color-primary);
    text-decoration: none;
    cursor: pointer;
}

.attachment-item:hover {
    text-decoration: underline;
}

.attachment-icon {
    margin-right: 5px;
}

.file-size {
    margin-left: 5px;
    color: var(--el-text-color-secondary);
}
</style>
