import {
	audit,
	save,
	submit
} from '../api/production_replenishment.js';
import modal from '../plugins/modal.js';
import {
	audioUrls,
	playVoice
} from './audio2.js';
import {
	getSaveParam,
	getSubmitParam,
	getAuditParam,
	get2SaveParam
} from './newparams.js';


export default {
	async submit(FormId,FID, indexList,fbillType) {
		try {
			modal.loading("提交中，请耐心等待...");
			let saveParam; 
			if(fbillType == "B"){
				 saveParam = get2SaveParam(FormId,FID, indexList);
			}else{
				 saveParam = getSaveParam(FormId,FID, indexList);
			}
			console.log(saveParam)
			const saveRes = await this.saveData(saveParam);
			if (!saveRes.IsSuccess) {
				throw new Error(saveRes.Errors[0].Message);
			}

			const submitParam = getSubmitParam(FormId,FID);
			const submitRes = await this.submitData(submitParam);
			if (!submitRes.IsSuccess) {
				throw new Error(submitRes.Errors[0].Message);
			}

			const auditParam = getAuditParam(FormId,submitRes.SuccessEntitys[0].Id);
			const auditRes = await this.auditData(auditParam);
			if (!auditRes.IsSuccess) {
				throw new Error(auditRes.Errors[0].Message);
			}

			this.handleSuccess(FID, indexList);

		} catch (error) {
			// this.handleError(error);
			throw new Error(error);
		} finally {
			modal.closeLoading();
		}
	},

	saveData(params) {
		return save(JSON.stringify(params))
			.then(res => res.Result.ResponseStatus);
	},

	submitData(params) {
		return submit(JSON.stringify(params))
			.then(res => res.Result.ResponseStatus);
	},

	auditData(params) {
		return audit(JSON.stringify(params))
			.then(res => res.Result.ResponseStatus);
	},

	handleSuccess(FID, indexList) {

		// Assuming that you pass indexList back to where it's needed
		uni.showModal({
			title: "提示",
			content: "提交成功",
			showCancel: true,
			success: (res) => {
				if (res.confirm) {
					// 用户点击确定
				} else {
					// 用户点击取消
				}
			}
		});
		playVoice(audioUrls.warningSuccessUrl);
	},

	handleError(error) {
		uni.showToast({
			title: error.message || '操作失败',
			duration: 3000,
			icon: "error"
		});
		playVoice(audioUrls.successVoiceUrl)
		console.error('操作失败:', error);
	}
};