<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>
                        <el-button type="primary" icon="Check" :loading="submitLoading"
                            @click="handleInitiateApproval">{{ $t('cooperationUnit.initiateApproval') }}</el-button>
                        <el-button icon="Document" @click="handleSaveDraft">{{ $t('cooperationUnit.saveDraft')
                            }}</el-button>
                        <el-button icon="FolderOpened" @click="handleLoadTemplate">{{ $t('cooperationUnit.loadTemplate')
                            }}</el-button>
                        <el-button icon="FolderAdd" @click="handleSaveTemplate">{{ $t('cooperationUnit.saveTemplate')
                            }}</el-button>
                    </div>
                    <div style="margin-left:auto;">
                        <el-button icon="View" :disabled="!singleSelected" @click="handleViewWorkflow">{{
                            $t('cooperationUnit.viewWorkflow') }}</el-button>
                    </div>
                </div>
            </el-row>

            <!-- 标题、描述、上传附件 -->
            <el-row class="mb10">
                <el-form :model="headerForm" label-width="60px" class="w-full" :rules="headerRequiredRule" ref="headerFormRef">
                    <el-form-item :label="$t('cooperationUnit.formTitle')" prop="title">
                        <el-input maxlength="255" v-model="headerForm.title" :placeholder="$t('cooperationUnit.inputTitleTip')" />
                    </el-form-item>
                    <el-form-item :label="$t('cooperationUnit.description')">
                        <el-input v-model="headerForm.description" maxlength="255"
                            :placeholder="$t('cooperationUnit.inputDescriptionTip')" />
                    </el-form-item>
                    <el-form-item :label="$t('cooperationUnit.attachments')">
                        <UploadFile :fileSize="20" type="simple" :limit="10" @change="handleFlowFormFileChange" />
                    </el-form-item>
                </el-form>
            </el-row>

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

            <!-- 动态明细表 -->
            <el-row class="mb10">
                <div style="width: 100%; display: flex; gap: 1px;">
                    <el-button type="primary" icon="Plus" @click="handleAddRow">{{ $t('cooperationUnit.add')
                        }}</el-button>
                    <el-button icon="DocumentCopy" :disabled="selectedRowIndex === -1" @click="handleCopyRow">{{
                        $t('cooperationUnit.copy') }}</el-button>
                    <el-button type="danger" icon="Delete" :disabled="selectedRowIndex === -1"
                        @click="handleDeleteRow">{{ $t('cooperationUnit.delete') }}</el-button>
                    <el-button type="danger" icon="Delete" :disabled="expertForm.experts.length === 0"
                        @click="handleDeleteAll">{{ $t('cooperationUnit.deleteAll') }}</el-button>
                </div>
            </el-row>

            <el-table :data="expertForm.experts" border style="width: 100%;" highlight-current-row
                @current-change="handleCurrentChange">
                <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('expertApply.table.index')" width="60" />
                <el-table-column prop="name" min-width="200">
                    <template #header>
                        <span class="required-star">*</span>{{ t('expertApply.table.name') }}
                    </template>
                    <template #default="scope">
                        <div style="display:flex; gap:6px; align-items:center;">
                            <el-input maxlength="255" v-model="scope.row.name" :placeholder="t('expertApply.table.inputPlaceholder')" />
                            <el-button v-if="isUpdate" size="small" icon="Search" @click="openExpertDialog(scope.$index)"></el-button>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="contactMethod" min-width="160">
                    <template #header>
                        <span class="required-star">*</span>{{ t('expertApply.table.contact') }}
                    </template>
                    <template #default="scope">
                        <el-input maxlength="255" v-model="scope.row.contactMethod"
                            :placeholder="t('expertApply.table.inputPlaceholder')" />
                    </template>
                </el-table-column>

                <el-table-column prop="techField" min-width="160">
                    <template #header>
                        <span class="required-star">*</span>{{ t('expertApply.table.field') }}
                    </template>
                    <template #default="scope">
                        <el-input maxlength="255" v-model="scope.row.techField"
                            :placeholder="t('expertApply.table.inputPlaceholder')" />
                    </template>
                </el-table-column>

                <el-table-column prop="professionalTitle" min-width="160">
                    <template #header>
                        <span class="required-star">*</span>{{ t('expertApply.table.title') }}
                    </template>
                    <template #default="scope">
                        <el-input maxlength="255" v-model="scope.row.professionalTitle"
                            :placeholder="t('expertApply.table.inputPlaceholder')" />
                    </template>
                </el-table-column>

                <el-table-column prop="workUnit" min-width="200">
                    <template #header>
                        <span class="required-star">*</span>{{ t('expertApply.table.company') }}
                    </template>
                    <template #default="scope">
                        <el-input maxlength="255" v-model="scope.row.workUnit" :placeholder="t('expertApply.table.inputPlaceholder')" />
                    </template>
                </el-table-column>

                <el-table-column prop="attachments" min-width="180">
                    <template #header>
                        <span class="required-star">*</span>{{ t('expertApply.table.attachments') }}
                    </template>
                    <template #default="scope">
                        <UploadFile :modelValue="scope.row.attachments" :fileSize="20" type="simple" :isShowTip=false
                            :limit="3" @change="(url: string, files: FileItemInterface[]) => scope.row.attachments = files?.map(item => ({ name: item.name, url: item.url })) || []" />
                    </template>
                </el-table-column>

                <el-table-column prop="evidences" min-width="200">
                    <template #header>
                        <span class="required-star">*</span>{{ t('expertApply.table.evidences') }}
                    </template>
                    <template #default="scope">
                        <UploadFile :modelValue="scope.row.evidences" :fileSize="20" type="simple" :isShowTip=false
                            :limit="5" @change="(url: string, files: FileItemInterface[]) => scope.row.evidences = files?.map(item => ({ name: item.name, url: item.url })) || []" />
                    </template>
                </el-table-column>

                <el-table-column prop="level" min-width="120" :label="t('expertApply.table.level')">
                    <template #default="scope">
                        <el-select v-model="scope.row.level" :placeholder="t('expertApply.table.selectPlaceholder')"
                            style="width: 100%;">
                            <el-option v-for="item in level" :label="item.label" :value="item.value" :key="item.value" />
                        </el-select>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 选择专家弹窗 -->
            <SelectExpertDialog v-model:visible="expertDialogVisible" @confirm="onExpertSelected" />
            <!-- <UserSelect v-model:visible="userSelectVisible" @ok="handleUserSelectOk" /> -->
					<template-table-common />

        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted,watch,computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { formatDate } from '/@/utils/formatTime';
import { useUserInfo } from '/@/stores/userInfo';
import { useMessage } from '/@/hooks/message';
import SelectExpertDialog from '/@/components/investment/SelectExpertDialog.vue';
import {addExpertInformationAPI, getExpertInformationByTemplateIdAPI} from '/@/api/investment/cooperationUnit';
import {flowFn} from "/@/utils/flowFn";
import { addFlowForm } from '/@/api/flow/flow';
import {flowNameOptions, level} from '/@/hooks/enums';
import {FormInstance} from "element-plus";
import {addTemplate} from "/@/api/common";
// import UserSelect from '/@/components/UserSelect/index.vue'
import templateTableCommon from "/@/components/templetTableComom/index.vue"
import {templateStore} from "/@/stores/template"

const temp = templateStore()
const props = defineProps({
    isUpdate: {
        type: Boolean,
        default: false
    }
})

const { t } = useI18n();
const singleSelected = ref(false);
const submitLoading = ref(false);

interface FileItemInterface {
    name: string;
    url: string;
} 
const headerForm = reactive({
    title: '',
    description: '',
    attachments: [] as FileItemInterface[],
});
const handleFlowFormFileChange = (url: string, files: FileItemInterface[]) => {
    headerForm.attachments = files.map(item => ({ name: item.name, url: item.url }))
}
const headerRequiredRule = ref({
    title: [{ required: true, message: '该选项必填', trigger: 'blur' },]
})
const headerFormRef = ref<FormInstance>();
const userInfoStore = useUserInfo();
const displayReporter = userInfoStore.userInfos.user?.username || '';
const displayUnit = userInfoStore.userInfos.user?.deptName || '';
const displayDate = formatDate(new Date(), 'YYYY-mm-dd');

const createEmptyExpert = () => ({
    id: 0,
    parentId: 0,
    name: '',
    contactMethod: '',
    techField: '',
    professionalTitle: '',
    workUnit: '',
    attachments: '',
    evidences: '',
    level: '',
    externalStatus: '',
    attachmentUrl: '',
    testimonyMaterials: '',
    createBy: '',
    createTime: '',
    updateBy: '',
    updateTime: '',
    delFlag: '',
    processInstanceId: '',
    status: 1,
		flowType:0,
		templateId:0,
});

const expertForm = reactive({
    experts: [] as ReturnType<typeof createEmptyExpert>[],
});
const selectedRowIndex = ref(-1);

// 专家选择弹窗
const expertDialogVisible = ref(false);
const editingExpertRowIndex = ref(-1);
const openExpertDialog = (rowIndex: number) => {
    editingExpertRowIndex.value = rowIndex;
    expertDialogVisible.value = true;
};
const onExpertSelected = (row: any) => {
    if (editingExpertRowIndex.value === -1) return;
    const target = expertForm.experts[editingExpertRowIndex.value];
    target.parentId = row?.id ?? target.id
    target.name = row?.expertName ?? target.name;
    target.contactMethod = row?.contactInformation ?? target.contactMethod;
    target.techField = row?.technologyField ?? target.techField;
    target.professionalTitle = row?.professionalTitle ?? target.professionalTitle;
    target.workUnit = row?.workUnit ?? target.workUnit;
    target.level = row?.level ?? target.level;
    target.attachments = row?.attachmentUrl ? JSON.parse(row.attachmentUrl) : []
    target.evidences = row?.testimonyMaterials ? JSON.parse(row.testimonyMaterials) : []
};

const handleAddRow = () => {
    expertForm.experts.push(createEmptyExpert());
    selectedRowIndex.value = expertForm.experts.length - 1;
};
const handleCopyRow = () => {
    if (selectedRowIndex.value === -1) return;
    const row = expertForm.experts[selectedRowIndex.value];
    expertForm.experts.push(JSON.parse(JSON.stringify(row)));
    selectedRowIndex.value = expertForm.experts.length - 1;
};
const handleDeleteRow = () => {
    if (selectedRowIndex.value === -1) return;
    expertForm.experts.splice(selectedRowIndex.value, 1);
    selectedRowIndex.value = -1;
};
const handleDeleteAll = () => {
    expertForm.experts = [];
    selectedRowIndex.value = -1;
};
const handleRowSelect = (index: number) => {
    selectedRowIndex.value = index;
    singleSelected.value = index !== -1;
};
const handleCurrentChange = (row: any) => {
    if (!row) return;
    selectedRowIndex.value = expertForm.experts.indexOf(row);
    singleSelected.value = selectedRowIndex.value !== -1;
};

const toSubmitExpert = (expert: ReturnType<typeof createEmptyExpert>) => ({
    id: expert.id || null,
    parentId: expert.parentId || null,
    expertName: expert.name || '',
    contactInformation: expert.contactMethod || '',
    technologyField: expert.techField || '',
    professionalTitle: expert.professionalTitle || '',
    workUnit: expert.workUnit || '',
    attachmentUrl: JSON.stringify(expert.attachments),
    testimonyMaterials: JSON.stringify(expert.evidences),
    level: expert.level || '',
    externalStatus: expert.externalStatus || '',
    createBy: expert.createBy || '',
    createTime: expert.createTime || '',
    updateBy: expert.updateBy || '',
    updateTime: expert.updateTime || '',
    delFlag: expert.delFlag || '',
    processInstanceId: expert.processInstanceId || '',
    status: expert.status || 0,
		flowType:expert.flowType || 0,
		templateId: expert.templateId || 0,
});

const requiredFields = [
    'name',
    'contactMethod',
    'techField',
    'professionalTitle',
    'workUnit',
    'attachments',
    'evidences'
]
const verifyTableFields = () => {
    const isVaild = !expertForm.experts.some((item: any) => {
        for (const key of requiredFields) {
            if (!item[key]) {
                return true
            }
        }
        return false
    })
    return isVaild
}

// const userSelectVisible = ref(false)
// const handleApprovalUserSelect = () => {
//     userSelectVisible.value = true
// }
// const handleUserSelectOk = (user: any) => {
//     console.log(user)
// }

const handleInitiateApproval = async () => {
    if (submitLoading.value) return;
		const r = await headerFormRef.value?.validate();
		if (!r) return;
    if (!expertForm.experts.length) {
        useMessage().warning('请先新增专家信息');
        return;
    }
    if (!verifyTableFields()) {
        useMessage().warning('请完成表格必填项');
        return
    }
    submitLoading.value = true;
    try {
        const flowIdKey = props.isUpdate ? 'VITE_FLOWID_14' : 'VITE_FLOWID_13'
        const { processInstanceId } = await flowFn(flowIdKey, { paramMap:{} });
        const flowName = props.isUpdate ? 'informationUpdates' : 'informationRegistration'
	    const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0]
        await addFlowForm({
            title: headerForm.title,
            description: headerForm.description,
            attachments: JSON.stringify(headerForm.attachments),
            processInstanceId,
            flowType: flowNameObj.value
        })
        const payload = {
            entities: expertForm.experts.map((item) => toSubmitExpert({ ...item, processInstanceId,flowType:flowNameObj.value }))
        };
        await addExpertInformationAPI(payload);
        useMessage().success('成功');
    } catch (error: any) {
        useMessage().error(error?.msg || error?.message || '操作失败');
    } finally {
        submitLoading.value = false;
    }
};
const handleSaveDraft = async () => {
	if (submitLoading.value) return;
	const r = await headerFormRef.value?.validate();
	if (!r) return;
	if (!expertForm.experts.length) {
		useMessage().warning('请先新增专家信息');
		return;
	}
	if (!verifyTableFields()) {
		useMessage().warning('请完成表格必填项');
		return
	}
	submitLoading.value = true;
	const flowName = props.isUpdate ? 'informationUpdates' : 'informationRegistration'
	const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0];
	 const payload = {
		 entities: expertForm.experts.map((item) => toSubmitExpert({ ...item, status: 0,flowType:flowNameObj.value })),
		 temporaryStorage:{
			 id:'',
			 businessType:flowNameObj.value,
			 title:headerForm.title,
		 }
	 };
	try {
		await addExpertInformationAPI(payload)
		useMessage().success('保存代发成功');
	}catch(error: any) {
		useMessage().error(error?.msg || error?.message || '操作失败');
	}finally {
		submitLoading.value = false;
	}
};
const tempId = computed(()=>temp.temp_id)
const handleLoadTemplate = () => {
	const flowName = props.isUpdate ? 'informationUpdates' : 'informationRegistration'
	const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0];
	temp.changeTempShow(true,flowNameObj.value)
}
const handleSaveTemplate = async () => {
	if (submitLoading.value) return;
	const r = await headerFormRef.value?.validate();
	if (!verifyTableFields()) {
		useMessage().warning('请完成表格必填项');
		return
	}
	const flowName = props.isUpdate ? 'informationUpdates' : 'informationRegistration'
	const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0];
	try {
		const {data:templateId} = await addTemplate({templateName:headerForm.title,templateType:flowNameObj.value,})
		const payload = {
			entities: expertForm.experts.map((item) => toSubmitExpert({ ...item, status: 0,templateId,flowType:flowNameObj.value })),
		};
		await addExpertInformationAPI(payload)
		useMessage().success('模板保存成功');
	}catch(error: any) {
		useMessage().error(error?.msg || error?.message || '操作失败');
	}
}
const handleViewWorkflow = () => useMessage().info('查看流程功能待实现');
watch(()=>tempId.value,()=>{
	getExpertInformationByTemplateIdAPI(tempId.value).then(data => {
		expertForm.experts = data.data.map((item:any) => {
			return {
				parentId: item.id ,
				name: item.expertName,
				contactMethod: item.contactInformation,
				techField: item.technologyField ,
				professionalTitle: item.professionalTitle,
				workUnit: item.workUnit,
				level: item.level,
				attachments: item.attachmentUrl ? JSON.parse(item.attachmentUrl) : [],
				evidences: item.testimonyMaterials ? JSON.parse(item.testimonyMaterials) : []
			}
		})
	})
})
onMounted(() => {
    if (!expertForm.experts.length) {
        handleAddRow();
    }
});
</script>

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

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

.header-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 50%;
    align-self: center;
}

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

.required-star {
    color: var(--el-color-danger);
    margin-right: 2px;
}
</style>
