<template>
	<a-drawer
		:title="formData.id ? '编辑出库还款' : '增加出库还款'"
		: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="depotId">
							<a-select v-model:value="formData.depotId" placeholder="请选择企业客户" :options="depotOptions"
									  style="width: 100%" @change="depotIdAuto"/>
						</a-form-item>
						<!--						<a-form-item label="贷款金额(元)：" name="loanSum">
													<a-input v-model:value="formData.loanSum" disabled/>
												</a-form-item>
												<a-form-item label="已质押库存总数(万吨)：" name="mortgageCount">
													<a-input v-model:value="formData.mortgageCount" disabled/>
												</a-form-item>-->
						<a-form-item label="库位：" name="shedName">
							<a-select v-model:value="formData.shedName" placeholder="请选择库位" :options="depotShedOptions"/>
						</a-form-item>
						<a-form-item label="粮食种类：" name="grainGroup">
							<a-select v-model:value="formData.grainGroup" placeholder="请选择粮食种类" @change="grainGroupChange" :options="grainGroupOptions"/>
						</a-form-item>
						<a-form-item label="贷款合同号：" name="contractCode">
							<a-input v-model:value="formData.contractCode" disabled/>
						</a-form-item>
						<a-form-item label="粮食质押价格(元/吨)：" name="loanPrice">
							<a-input v-model:value="formData.loanPrice" disabled/>
						</a-form-item>
						<a-form-item label="粮食种类库存数(万吨)：" name="loanTonW">
							<a-input v-model:value="formData.loanTonW" 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-number v-model:value="formData.repayPrincipal" placeholder="请输入还款本金" :min="0.01" style="width: 100%"
											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-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()">
								<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/>
									</a-col>
									<a-col :span="8" style="margin-top: 4px">
										<a-button size="small" type="primary" danger ghost @click="delLicensePlates(index)">移除</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";

// 抽屉状态
const visible = ref(false)
const emit = defineEmits({successful: null})
const formRef = ref()
// 表单数据
const formData = ref({})
const submitLoading = ref(false)
const depotShedOptions = ref([])
const depotOptions = ref([])

// 打开抽屉
const onOpen = (record) => {
	visible.value = true
	if (record) {
		let recordData = cloneDeep(record)
		formData.value = Object.assign({}, recordData)
		depotIdLoad()
		if (formData.value.licensePlate)
			formData.value.licensePlates = formData.value.licensePlate.split(',').map(function (key) {
				return {
					licensePlate: key
				}
			})
		dictOptionsApi.options({'dictValue': '库位', depotId: formData.value.depotId}).then((data) => {
			depotShedOptions.value = data
		})
	}
}
dictOptionsApi.options(Object.assign('', {'dictValue': '粮库'})).then((data) => {
	depotOptions.value = data
	if (data.length === 1 && !formData.value.depotId) {
		formData.value.depotId = data[0].value
		depotIdLoad()
	}
})
// 粮库选择
const depotIdAuto = () => {
	formData.value.contractCode = ''
	formData.value.loanSum = ''
	formData.value.mortgageCount = ''
	formData.value.shedName = ''
	formData.value.repayPrice = ''
	formData.value.repayTonThis = ''
	formData.value.grainGroup = ''
	depotIdLoad()
}
// 粮库加载
const depotIdLoad = () => {
	depotGrainInfoApi.depotGrainInfoDetail({"id": formData.value.depotId}).then((data) => {
		formData.value.contractCode = data.contractCode
		formData.value.loanSum = data.loanSum
		formData.value.mortgageCount = data.mortgageCount
		formData.value.priceChildren = data.priceChildren
		if (formData.value.grainGroup)
			grainGroupChange()
	})
	dictOptionsApi.options({'dictValue': '库位', depotId: formData.value.depotId}).then((data) => {
		depotShedOptions.value = data
	})
}
// 粮食选择
const grainGroupChange = () => {
	formData.value.loanTonW = ''
	formData.value.repayTonThis = ''
	formData.value.priceChildren.map((m) => {
		if (m.grainGroup === formData.value.grainGroup) {
			formData.value.loanPrice = m.loanPrice
			if (!formData.value.repayPrice)
				formData.value.repayPrice = m.repayPrice
			formData.value.loanTonW = m.loanTonW
			putRepayCount()
		}
	})
	if (formData.value.grainGroup)
		depotRepayOrderApi.depotRepayOrderGetBeforeAdd({depotId: formData.value.depotId, grainGroup: formData.value.grainGroup}).then((data) => {
			formData.value.repayBeforeTonSurplus = data.repayTonSurplus
			formData.value.repayBeforeOrderNo = data.repayOrderNo
		}).catch(() => {
			formData.value.grainGroup = ''
		})
}
// 计算总金额
const putRepayCount = () => {
	if (formData.value.repayTonThis && formData.value.repayPrice && formData.value.repayInterest && formData.value.depotId && formData.value.grainGroup) {
		formData.value.repayPrincipal = formData.value.repayTonThis * formData.value.repayPrice
		formData.value.repayAmount = (formData.value.repayPrincipal * 100000 + formData.value.repayInterest * 100000) / 100000
	}
}
// 关闭抽屉
const onClose = () => {
	formRef.value.resetFields()
	formData.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)
}
// 抛出函数
defineExpose({
	onOpen
})
const grainGroupOptions = tool.dictList('粮食种类')
</script>
