<template>
    <a-drawer
        :title="formData.id ? '编辑出入库管理' : '增加出入库管理'"
        :width="800"
        :visible="visible"
        :destroy-on-close="true"
        :footer-style="{ textAlign: 'right' }"
        @close="onClose"
    >
        <a-form ref="formRef" :model="formData" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol">
			<a-row :gutter="16">
				<a-col :span="12">
					<a-form-item label="车牌号码：" name="licenseNumber">
						<a-input v-model:value="formData.licenseNumber" placeholder="请输入车牌号码" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="司机姓名：" name="driverName">
						<a-input v-model:value="formData.driverName" placeholder="请输入司机姓名" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="手机号：" name="driverPhone">
						<a-input v-model:value="formData.driverPhone" placeholder="请输入手机号" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="证件号：" name="idNumber">
						<a-input v-model:value="formData.idNumber" placeholder="请输入证件号" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="车辆毛重(吨)：" name="grossWeight">
						<a-input-number v-model:value="formData.grossWeight" placeholder="请输入车辆毛重" allow-clear :min="0" :max="99999999" style="width:100%"/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="车辆皮重(吨)：" name="tareWeight">
						<a-input-number v-model:value="formData.tareWeight" placeholder="请输入车辆皮重" allow-clear :min="0" :max="99999999" style="width:100%"/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="出入库类型：" name="inventoryType">
						<a-select v-model:value="formData.inventoryType" placeholder="请选择出入库类型" :options="inventoryTypeOptions" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="品名：" name="productName">
						<a-input v-model:value="formData.productName" placeholder="请输入品名" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="包数量(吨)：" name="inventoryWeight">
						<a-input-number v-model:value="formData.inventoryWeight" placeholder="请输入包数量" allow-clear :min="0" :max="99999999" style="width:100%"/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="出入库时间：" name="inventoryTime">
						<a-date-picker v-model:value="formData.inventoryTime" value-format="YYYY-MM-DD HH:mm:ss" show-time placeholder="请选择出入库时间" style="width: 100%" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<!--<a-form-item
						:label="'上传附件：'"
						:rules="[
									{ required: true, message: '请上传文件' }
								]"
					>
						<a-upload
							:customRequest="data => customRequest(data,index)"
							v-model:file-list="fileUpload"
							:remove="file => removeOtherFile(file,index)"
							:before-upload="beforeUpload"
							:multiple="true"
							:max-count="15"

						>
							<a-button>
								<upload-outlined></upload-outlined>
								上传文件
							</a-button>
							<span style="color:red;margin-left:10px">本次最多上传15个</span>
						</a-upload>
					</a-form-item>-->
					<a-form-item label="上传图片：" name="driverLicense">
						<a-upload
							v-model:file-list="fileList"
							class="avatar-uploader"
							list-type="picture"
							:show-upload-list="true"
							:custom-request="customRequest"
							:remove="file => removeOtherFile(file,index)"
							:before-upload="beforeUpload"
							accept="image/png, image/jpeg, image/jpg"

						>
							<!--accept="image/png, image/jpeg, image/jpg"-->
							<!--<img v-if="imageUrl" :src="imageUrl" alt="avatar" style="max-height: 100px; max-width: 100px"/>
							<div v-else>
								<plus-outlined/>
								<div class="ant-upload-text">上传</div>
							</div>-->
							<a-button>
								<upload-outlined></upload-outlined>
								upload
							</a-button>
						</a-upload>
					</a-form-item>
				</a-col>

			</a-row>

            <!--<a-form-item label="附件名称：" name="fileName">
                <a-input v-model:value="formData.fileName" placeholder="请输入附件名称" allow-clear />
            </a-form-item>
            <a-form-item label="附件地址：" name="filePath">
                <a-input v-model:value="formData.filePath" placeholder="请输入附件地址" allow-clear />
            </a-form-item>-->
        </a-form>
        <template #footer>
            <a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
            <a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
        </template>
    </a-drawer>
</template>

<script setup name="bizInventoryForm">
    import tool from '@/utils/tool'
    import { cloneDeep } from 'lodash-es'
    import { required } from '@/utils/formRules'
    import bizInventoryApi from '@/api/biz/bizInventoryApi'
	import fileApi from "@/api/dev/fileApi"
	import sysConfig from "@/config";
	import {message, Modal, Upload } from 'ant-design-vue';
    // 抽屉状态
    const visible = ref(false)
    const emit = defineEmits({ successful: null })
    const formRef = ref()
    // 表单数据
    const formData = ref({fileIdList:[]})
    const submitLoading = ref(false)
    const inventoryTypeOptions = ref([])

	const labelCol = ref({ span: 6 })
	const wrapperCol = ref({ span: 18 })

	const fileList = ref([])
	const imageUrl = ref('')

	const beforeUpload = (file) => {
    	console.log("file:"+JSON.stringify(file))
		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
		if (!isJpgOrPng) {
			message.error('请上传JPG/PNG格式的图片！')
		}
		return isJpgOrPng || Upload.LIST_IGNORE
	}

    // 打开抽屉
    const onOpen = (record) => {
        visible.value = true
        if (record) {
            let recordData = cloneDeep(record)
            formData.value = Object.assign({}, recordData)
			formData.value.fileIdList = []
			if(formData.value.filePath!=null){
				for (var i=0;i<formData.value.filePath.split(',').length;i++){
					fileList.value.push({
						name: formData.value.fileName.split(',')[i],
						url:sysConfig.API_URL + formData.value.filePath.split(',')[i]
					})
					formData.value.fileIdList.push(formData.value.fileId.split(",")[i])
					console.log("fileList:"+JSON.stringify(fileList.value))
					console.log("formData.value.fileIdList:"+formData.value.fileIdList)
				}
			}
        }
        inventoryTypeOptions.value = tool.dictList('出入库')
    }
    // 关闭抽屉
    const onClose = () => {
        formRef.value.resetFields()
        formData.value = {fileIdList:[]}
        visible.value = false
		fileList.value = []
    }
    // 默认要校验的
    const formRules = {
        licenseNumber: [required('请输入车牌号码')],
        productName: [required('请输入品名')],
        driverName: [required('请输入司机姓名')],
        driverPhone: [required('请输入手机号')],
        idNumber: [required('请输入证件号')],
        grossWeight: [required('请输入车辆毛重')],
        tareWeight: [required('请输入车辆皮重')],
        inventoryType: [required('请输入出入库类型')],
        inventoryWeight: [required('请输入包数量')],
        inventoryTime: [required('请输入出入库时间')],
    }
    // 验证并提交数据
    const onSubmit = () => {
        formRef.value
            .validate()
            .then(() => {
                submitLoading.value = true
                const formDataParam = cloneDeep(formData.value)
                bizInventoryApi
                    .bizInventorySubmitForm(formDataParam, !formDataParam.id)
                    .then(() => {
                        onClose()
                        emit('successful')
                    })
                    .finally(() => {
                        submitLoading.value = false
                    })
            })
    }
	const customRequest = (data) => {
		//保存图片
		const fileData = new FormData()
		fileData.append('file', data.file)
		fileApi
			.fileUploadReturnId(fileData)
			.then((result) => {
				console.log("result:"+result)
				formData.value.fileIdList.push(result)
			}).finally(()=>{
				data.onSuccess()
			})

	}
	// 文件转base64，用于显示图片
	const getBase64 = (file) => {
		return new Promise((resolve, reject) => {
			// FileReader类就是专门用来读文件的
			const reader = new FileReader()
			reader.readAsDataURL(file)
			// 成功和失败返回对应的信息，reader.result一个base64，可以直接使用
			reader.onload = () => resolve(reader.result)
			// 失败返回失败的信息
			reader.onerror = (error) => reject(error)
		})
	}
	//文件删除
	const removeOtherFile = (file) => {
		console.log('remove file', file);
		console.log("formData.filePathList:"+formData.value.fileIdList)
		fileList.value.forEach((item,index)=>{
			console.log(item.name+"======="+file.name)
			if(item.name === file.name){

				fileList.value.splice(index, 1);
				formData.value.fileIdList.splice(index,1)
				console.log("formData.filePathList:"+formData.value.fileIdList)
			}
		})
	}
    // 抛出函数
    defineExpose({
        onOpen
    })
</script>
