<template>
	<a-drawer
		:title="'编辑出库还款'"
		:width="1200"
		:visible="visible"
		:destroy-on-close="true"
		:footer-style="{ textAlign: 'right' }"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-card title="粮食信息" :bordered="false">
						<a-form-item label="企业客户：" name="depotGrainName">
							<a-input v-model:value="formData.depotGrainName" disabled/>
						</a-form-item>
						<a-form-item label="库位：" name="shedName">
							<a-select v-model:value="formData.shedName" disabled/>
						</a-form-item>
						<a-form-item label="粮食种类：" name="grainGroup">
							<a-input v-model:value="formData.grainGroup" disabled/>
						</a-form-item>
						<a-form-item label="贷款合同号：" name="contractCode">
							<a-input v-model:value="formData.contractCode" disabled/>
						</a-form-item>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card title="还款信息" :bordered="false">
						<a-form-item label="本单出库量(吨)：" name="repayTonThis">
							<a-input-number v-model:value="formData.repayTonThis" placeholder="请输入总提货量" :min="0.001" style="width: 100%"
											@change="putRepayCount"/>
						</a-form-item>
						<a-form-item label="出库单价(元/吨)：" name="repayPrice">
							<a-input-number v-model:value="formData.repayPrice" placeholder="请输入还款单价" :min="0.01" style="width: 100%"
											@change="putRepayCount"/>
						</a-form-item>
						<a-form-item label="利息(元)：" name="repayInterest">
							<a-input-number v-model:value="formData.repayInterest" placeholder="请输入利息" :min="0.01" style="width: 100%" @change="putRepayCount"/>
						</a-form-item>
						<a-form-item label="还款本金(元)：" name="repayPrincipal">
							<a-input v-model:value="formData.repayPrincipal" disabled/>
						</a-form-item>
						<a-form-item label="还款总额(元)：" name="repayAmount">
							<a-input v-model:value="formData.repayAmount" placeholder="还款总额" disabled/>
						</a-form-item>
						<a-form-item label="上单扭转余量(吨)：" name="repayBeforeTonSurplus">
							<a-input v-model:value="formData.repayBeforeTonSurplus" disabled/>
						</a-form-item>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card title="提货经办人" :bordered="false">
						<a-form-item label="提货经办人：" name="keeperName">
							<a-input v-model:value="formData.keeperName" placeholder="请输入提货经办人" allow-clear/>
						</a-form-item>
						<a-form-item label="提货经办人身份证号：" name="keeperCitizenId">
							<a-input v-model:value="formData.keeperCitizenId" placeholder="请输入提货经办人身份证号" allow-clear/>
						</a-form-item>
						<a-form-item label="提货经办人联系方式：" name="keeperMobile">
							<a-input v-model:value="formData.keeperMobile" placeholder="请输提货经办人联系方式" allow-clear/>
						</a-form-item>
						<a-form-item label="身份证照片：" name="keeperCitizenPic">
							<a-upload
								v-model:file-list="formData.imageUrls"
								class="avatar-uploader"
								list-type="picture-card"
								:show-upload-list="false"
								:custom-request="customRequest"
								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-upload>
						</a-form-item>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card title="车牌信息" :bordered="false">
						<a-form-item name="positionJson">
							<a-button type="primary" class="childAddButton" @click="addLicensePlates()" disabled>
								<PlusOutlined/>
								增加车牌
							</a-button>
							<a-row :gutter="10" class="form-row">
								<a-col :span="7" class="form-row-con"><br></a-col>
							</a-row>
							<div v-for="(licensePlateInfo, index) in formData.licensePlates" class="form-div">
								<a-row :gutter="24">
									<a-col :span="16">
										<a-input v-model:value="licensePlateInfo.licensePlate" placeholder="请输入车牌" style="margin:1px" allow-clear disabled/>
									</a-col>
									<a-col :span="8" style="margin-top: 4px">
										<a-button size="small" type="primary" danger ghost @click="delLicensePlates(index)" disabled>移除</a-button>
									</a-col>
								</a-row>
							</div>
						</a-form-item>
					</a-card>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading" v-if="formData.bankOpApprovalState !== '已审批'">保存</a-button>
		</template>
	</a-drawer>
</template>

<script setup name="depotRepayOrderForm">
import {message} from 'ant-design-vue'
import tool from '@/utils/tool'
import {cloneDeep} from 'lodash-es'
import {required, rules} from '@/utils/formRules'
import depotRepayOrderApi from '@/api/biz/depotRepayOrderApi'
import dictOptionsApi from "@/api/biz/dictOptionsApi";
import depotGrainInfoApi from "@/api/biz/depotGrainInfoApi";
import router from "@/router";
import sysConfig from "@/config";
import fileApi from "@/api/dev/fileApi";
import {all, create} from "mathjs";

// 抽屉状态
const visible = ref(false)
const emit = defineEmits({successful: null})
const formRef = ref()
// 表单数据
const formData = ref({})
const submitLoading = ref(false)
const imageUrl = ref('')
const mathjs = create(all, {
	number: "BigNumber",
	precision: 20,
})
const add = (num1, num2) => +mathjs.format(mathjs.add(num1, num2), {
	precision: 16,
})
// multiply
const multiply = (num1, num2) => +mathjs.format(mathjs.multiply(num1, num2), {
	precision: 16,
})

// 打开抽屉
const onOpen = (record) => {
	visible.value = true
	if (record) {
		let recordData = cloneDeep(record)
		formData.value = Object.assign({}, recordData)
		if (formData.value.licensePlate)
			formData.value.licensePlates = formData.value.licensePlate.split(',').map(function (key) {
				return {
					licensePlate: key
				}
			})
		if (formData.value.keeperCitizenPic) {
			// 让其回显
			imageUrl.value = sysConfig.API_URL + formData.value.keeperCitizenPic
			formData.value.imageUrls = [imageUrl.value]
		}
	}
}
// 计算总金额
const putRepayCount = () => {
	if (formData.value.repayTonThis && formData.value.repayPrice && formData.value.repayInterest && formData.value.depotId && formData.value.grainGroup) {
		formData.value.repayPrincipal = multiply(formData.value.repayTonThis, formData.value.repayPrice).toFixed(2)
		//formData.value.repayAmount = add(formData.value.repayPrincipal, formData.value.repayInterest)
		formData.value.repayAmount = (formData.value.repayPrincipal * 100 + formData.value.repayInterest * 100) / 100
	}
}
// 关闭抽屉
const onClose = () => {
	formRef.value.resetFields()
	formData.value = {}
	imageUrl.value = ''
	visible.value = false
}
// 默认要校验的
const formRules = {
	depotGrainName: [required('请输入')],
	contractCode: [required('请输入')],
	repayPrincipal: [required('请输入'), rules.amountCheck],
	repayInterest: [required('请输入'), rules.amountCheck],
	repayPrice: [required('请输入'), rules.amountCheck],
	repayAmount: [required('请输入'), rules.amountCheck],
	shedName: [required('请输入')],
	grainGroup: [required('请输入')],
	repayTonThis: [required('请输入')],
	licensePlate: [required('请输入')],
	keeperName: [required('请输入')],
	keeperCitizenId: [required('请输入'), rules.idCard],
}
// 验证并提交数据
const onSubmit = () => {
	formData.value.licensePlate = ''
	if (formData.value.licensePlates)
		formData.value.licensePlate = formData.value.licensePlates.map(item => {
			return item.licensePlate
		}).filter(function (s) {
			return s && s.trim()
		}).toString()
	if (!formData.value.licensePlate) {
		message.warning('请录入车牌')
		return false
	}
	if (formData.value.repayPrice < formData.value.loanPrice) {
		message.warning('出库单价必须大于质押价格!')
		return false
	}
	formRef.value
		.validate()
		.then(() => {
			submitLoading.value = true
			const formDataParam = cloneDeep(formData.value)
			depotRepayOrderApi
				.depotRepayOrderSubmitForm(formDataParam, !formDataParam.id)
				.then(() => {
					onClose()
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
}
// 车牌增行
const addLicensePlates = () => {
	if (!formData.value.licensePlates) {
		formData.value.licensePlates = []
	}
	formData.value.licensePlates.push({
		licensePlate: undefined
	})
}
// 车牌减行
const delLicensePlates = (index) => {
	formData.value.licensePlates.splice(index, 1)
}
const customRequest = (data) => {
	formData.value.imageUrls = ref([])
	getBase64(data.file)
		.then((res) => {
			imageUrl.value = res
			formData.value.imageUrls.push(res)
			//保存图片
			const fileData = new FormData()
			fileData.append('file', data.file)
			fileApi
				.fileUploadReturnId(fileData)
				.then((result) => {
					formData.value.keeperCitizenPic = result.toString()
					console.log(formData.value.keeperCitizenPic)
				})
		})
		.catch((err) => {
		})
}
// 文件转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)
	})
}
// 抛出函数
defineExpose({
	onOpen
})
</script>
