import request from '/@/utils/request';

export interface ReserveInvestmentProjectPayload {
	id?: string | number;
	projectName: string;
	projectOwnerUnit: string;
	projectMainEntity: string;
	projectStartTime: string;
	projectEndTime: string;
	investmentCategory: string;
	projectNature: string;
	projectLeaderName: string;
	projectLeaderPhone: string;
	projectSource: string;
	constructionNature: string;
	keyProject: string;
	majorInvestmentProjects: string;
	isMainBusiness: string;
	mainBusinessTypes: string;
	mainBusinessCode: string;
	projectInvestmentDirection: string;
	investmentDirectionSegmentation: string;
	isStrategicEmergingIndustries: string;
	urbanStrategy: string;
	isManufacturingIndustry: string;
	investmentArea: string;
	projectAddress: string;
	projectAddressDetail: string;
	isControllingStake: string;
	shareholdingRatio?: number;
	projectTotalAmount?: number;
	lastYearCompleted?: number;
	ourInvestmentTotalAmount?: number;
	ourLastYearCompleted?: number;
	projectDesc: string;
	attachmentUrl: string;
	enterpriseOwnFunds?: number;
	governmentInvestmentFunds?: number;
	externalRaisedFunds?: number;
	otherFunds?: number;
	decisionType: string;
	isProjectApprovalCompleted: string;
	projectApprovalFileNo: string;
	projectApprovalFileInfo: string;
	isDecisionProcedureCompleted: string;
	decisionProcedureFileNo: string;
	decisionFileInfo: string;
	partnerIds?: Array<string | number>;
	temporaryStorage?: {
		id?: string,
		businessType: number,
		title: string,
	}
}

export const addReserveInvestmentProjectAPI = (data: ReserveInvestmentProjectPayload) => {
	return request({
		url: '/admin/reserveInvestmentProjects/add',
		method: 'post',
		data,
	});
};

export interface ReserveInvestmentProjectItem {
	id: number | string;
	projectName: string;
	projectOwnerUnit?: string;
	projectMainEntity: string;
	projectStartTime?: string;
	projectEndTime?: string;
	investmentCategory?: string;
	projectNature?: string;
	projectInvestmentDirection?: string;
	investmentArea?: string;
	keyProject?: string;
	majorInvestmentProjects?: string;
	lastUpdater?: string;
	updateTime?: string;
	lastPushStatus?: string;
	[key: string]: any;
}

export interface ReserveInvestmentProjectsQuery {
	page?: number;
	size?: number;
	projectName?: string;
	projectMainEntity?: string;
	projectNature?: string;
}

export interface ReserveInvestmentProjectsPageResp {
	records: ReserveInvestmentProjectItem[];
	total: number;
	page?: number;
	size?: number;
}

const parseUploadValue = (value: any) => {
    if (!value) return [];
    if (Array.isArray(value)) return value;
    try {
        return JSON.parse(value);
    } catch {
        return [];
    }
};

export const normalizeDetailData = (detail: ReserveInvestmentProjectItem) => {
    const attachments = parseUploadValue(detail.attachmentUrl);
    return {
        applicant: detail.createBy || '',
        applicationUnit: detail.projectOwnerUnit || '',
        applicationDate: detail.createTime ? detail.createTime.split(' ')[0] : '',
        projectName: detail.projectName || '',
        projectMainUnit: detail.projectMainEntity || '',
        projectOwnerUnit: detail.projectOwnerUnit || '',
        projectStartDate: detail.projectStartTime || '',
        projectEndDate: detail.projectEndTime || '',
        investmentCategory: detail.investmentCategory || '',
        projectNature: detail.projectNature || '',
        projectManagerName: detail.projectLeaderName || '',
        contactNumber: detail.projectLeaderPhone || '',
        projectSource: detail.projectSource || '',
        constructionNature: detail.constructionNature || '',
        keyProject: detail.keyProject || '',
        majorInvestmentProject: detail.majorInvestmentProjects || '',
        withinMainBusiness: detail.isMainBusiness || '',
        mainBusinessType: detail.mainBusinessTypes || '',
        mainBusinessCode: detail.mainBusinessCode || '',
        projectDirection: detail.projectInvestmentDirection || '',
        directionSubdivision: detail.investmentDirectionSegmentation || '',
        strategicEmergingIndustry: detail.isStrategicEmergingIndustries || '',
        urbanStrategy: detail.urbanStrategy || '',
        isManufacturing: detail.isManufacturingIndustry || '',
        investmentRegion: detail.investmentArea || '',
        projectAddress: detail.projectAddress || '',
        projectDetailedAddress: detail.projectAddressDetail || '',
        isControllingShareholder: detail.isControllingStake || '',
        ourShareholdingRatio: detail.shareholdingRatio ? String(detail.shareholdingRatio) : '',
        totalInvestmentAmount: detail.projectTotalAmount ? String(detail.projectTotalAmount) : '',
        cumulativeInvestmentLastYear: detail.lastYearCompleted ? String(detail.lastYearCompleted) : '',
        ourTotalInvestmentAmount: detail.ourInvestmentTotalAmount ? String(detail.ourInvestmentTotalAmount) : '',
        ourCumulativeInvestmentLastYear: detail.ourLastYearCompleted ? String(detail.ourLastYearCompleted) : '',
        projectDesc: detail.projectDesc || '',
        projectProposal: attachments,
        enterpriseSelfFund: detail.enterpriseOwnFunds ? String(detail.enterpriseOwnFunds) : '',
        externalRaisedFund: detail.externalRaisedFunds ? String(detail.externalRaisedFunds) : '',
        governmentInvestmentFund: detail.governmentInvestmentFunds ? String(detail.governmentInvestmentFunds) : '',
        otherFunds: detail.otherFunds ? String(detail.otherFunds) : '',
        decisionType: detail.decisionType || '',
        isCompleteEstablishmentProcedures: detail.isProjectApprovalCompleted || '',
        establishmentDocumentNumber: detail.projectApprovalFileNo || '',
        establishmentDocumentInfo: detail.projectApprovalFileInfo || '',
        isCompleteDecisionProcedures: detail.isDecisionProcedureCompleted || '',
        decisionProgramDocumentNumber: detail.decisionProcedureFileNo || '',
        decisionDocumentInfo: detail.decisionFileInfo || '',
        progressDesc: detail.progressDesc || '',
        cooperationUnits: detail.cooperationUnits || []
    }
};

export const getReserveInvestmentProjectsPageAPI = (data: ReserveInvestmentProjectsQuery) => {
	return request<ReserveInvestmentProjectsPageResp>({
		url: '/admin/reserveInvestmentProjects/page',
		method: 'post',
		data,
	});
};

export const getReserveInvestmentProjectDetailAPI = (id: string | number) => {
	return request<ReserveInvestmentProjectItem>({
		url: '/admin/reserveInvestmentProjects/view',
		method: 'get',
		params: { id },
	});
};

export const deleteReserveInvestmentProjectsAPI = (ids: Array<string | number>) => {
	return request({
		url: '/admin/reserveInvestmentProjects/delete',
		method: 'put',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Enc-Flag': true,
		},
		data: new URLSearchParams({
			ids: ids.join(','),
		}).toString(),
	});
};

// 报送国资
export const submitReserveInvestmentProjectsAPI = (id: string | number) => {
	return request({
		url: '/admin/reserveInvestmentProjects/submit',
		method: 'get',
		params: { id },
	});
};

export const convertTemplateDataToFormData = (templateData: any) => {
	return {
		// 基本信息
		applicant: '', // 从用户信息获取
		applicationUnit: '', // 从用户信息获取
		projectName: templateData.projectName || '',
		projectMainUnit: templateData.projectMainEntity || '',
		projectStartDate: templateData.projectStartTime || '',
		investmentCategory: templateData.investmentCategory || '',
		projectManagerName: templateData.projectLeaderName || '',
		projectSource: templateData.projectSource || '',
		keyProject: templateData.keyProject === 'yes' ? 'yes' : 'no',
		withinMainBusiness: templateData.isMainBusiness || '',
		mainBusinessType: templateData.mainBusinessTypes || '',
		projectDirection: templateData.projectInvestmentDirection || '',
		strategicEmergingIndustry: templateData.isStrategicEmergingIndustries || '',
		isManufacturing: templateData.isManufacturingIndustry || '',
		projectAddress: templateData.projectAddress || '',
		isControllingShareholder: templateData.isControllingStake || '',
		totalInvestmentAmount: templateData.projectTotalAmount?.toString() || '',
		ourTotalInvestmentAmount: templateData.ourInvestmentTotalAmount?.toString() || '',
		projectDesc: templateData.projectDesc || '',
		progressDesc: templateData.progressDesc || '',
		projectProposal: templateData.attachmentUrl ? JSON.parse(templateData.attachmentUrl) : [],
		applicationDate: '', // 从当前日期获取
		projectOwnerUnit: templateData.projectOwnerUnit || '',
		projectEndDate: templateData.projectEndTime || '',
		projectNature: templateData.projectNature || '',
		contactNumber: templateData.projectLeaderPhone || '',
		constructionNature: templateData.constructionNature || '',
		majorInvestmentProject: templateData.majorInvestmentProjects || '',
		mainBusinessCode: templateData.mainBusinessCode || '',
		directionSubdivision: templateData.investmentDirectionSegmentation || '',
		urbanStrategy: templateData.urbanStrategy || '',
		investmentRegion: templateData.investmentArea || '',
		projectDetailedAddress: templateData.projectAddressDetail || '',
		ourShareholdingRatio: templateData.shareholdingRatio?.toString() || '',
		cumulativeInvestmentLastYear: templateData.lastYearCompleted?.toString() || '',
		ourCumulativeInvestmentLastYear: templateData.ourLastYearCompleted?.toString() || '',
		enterpriseSelfFund: templateData.enterpriseOwnFunds?.toString() || '',
		externalRaisedFund: templateData.externalRaisedFunds?.toString() || '',
		governmentInvestmentFund: templateData.governmentInvestmentFunds?.toString() || '',
		otherFunds: templateData.otherFunds?.toString() || '',

		// 合作伙伴信息
		partnerInfos: Array.isArray(templateData.cooperationUnits) ?
				templateData.cooperationUnits.map((unit: any) => ({
					id: unit.id || '',
					name: unit.cooperationName || '',
					nature: unit.cooperationNature || '',
					controller: unit.cooperationController || '',
					share: unit.shareholdingRatio?.toString() || ''
				})) : [],

		// 决策信息
		decisionType: templateData.decisionType || '',
		isCompleteEstablishmentProcedures: templateData.isProjectApprovalCompleted === 'yes' ? 'yes' : 'no',
		establishmentDocumentNumber: templateData.projectApprovalFileNo || '',
		establishmentDocumentInfo: templateData.projectApprovalFileInfo || '',
		decisionProgramDocumentNumber: templateData.decisionProcedureFileNo || '',
		decisionDocumentInfo: templateData.decisionFileInfo || '',
		isCompleteDecisionProcedures: templateData.isDecisionProcedureCompleted === 'yes' ? 'yes' : 'no',

		// 审核意见
		reviewOpinions: {
			submitUnitOpinion: '',
			groupInvestmentDeptOpinion: '',
			submitUnitLeadershipOpinion: '',
			submitUnitMainLeadershipOpinion: ''
		},

		// 其他
		processInstanceId: templateData.processInstanceId || ''
	};
};

// /admin/reserveInvestmentProjects/getByTemplateId
export const getReserveInvestmentProjectsByTemplateIdAPI = async (templateId: string | number) => {
    const res = await request<ReserveInvestmentProjectItem>({
        url: '/admin/reserveInvestmentProjects/getByTemplateId',
        method: 'get',
        params: { templateId },
    });
		return convertTemplateDataToFormData(res.data || {})
}
