<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form mb-4">
			<a-row :gutter="24">
				<a-col :span="4">
					<a-form-item label="企业客户" name="depotId">
						<a-select v-model:value="searchFormState.depotId" placeholder="请选择企业客户" :options="depotOptions" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="贷款合同号" name="contractCode">
						<a-input v-model:value="searchFormState.contractCode" placeholder="请输入贷款合同号"/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="还款单号" name="repayOrderNo">
						<a-input v-model:value="searchFormState.repayOrderNo" placeholder="请输入贷款合同号"/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="单据状态" name="repayState">
						<a-select v-model:value="searchFormState.repayState" placeholder="请选择放款状态" :options="repayStateOptions"/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="审批状态" name="bankOpApprovalState">
						<a-select v-model:value="searchFormState.bankOpApprovalState" placeholder="请选择审批状态" :options="bankOpApprovalStateOptions"/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-button type="primary" @click="table.refresh(true)">查询</a-button>
					<a-button style="margin: 0 8px" @click="() => searchFormRef.resetFields()">重置</a-button>
					<a @click="toggleAdvanced" style="margin-left: 8px">
						{{ advanced ? '收起' : '展开' }}
						<component :is="advanced ? 'up-outlined' : 'down-outlined'"/>
					</a>
				</a-col>
				<template v-if="advanced">
					<a-col :span="4">
						<a-form-item label="车牌" name="licensePlate">
							<a-input v-model:value="searchFormState.licensePlate" placeholder="请输入车牌"/>
						</a-form-item>
					</a-col>
					<a-col :span="4">
						<a-form-item label="授权提货人" name="keeperName">
							<a-input v-model:value="searchFormState.keeperName" placeholder="请输入提货人"/>
						</a-form-item>
					</a-col>
				</template>
				<template v-if="advanced">
					<a-col :span="4">
						<a-form-item label="提货人身份证号" name="keeperCitizenId">
							<a-input v-model:value="searchFormState.keeperCitizenId" placeholder="请输入提货人身份证号"/>
						</a-form-item>
					</a-col>
				</template>
				<template v-if="advanced">
					<a-col :span="4">
						<a-form-item label="提货人联系方式" name="keeperMobile">
							<a-input v-model:value="searchFormState.keeperMobile" placeholder="请输入提货人联系方式"/>
						</a-form-item>
					</a-col>
				</template>
			</a-row>
		</a-form>
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="addFormRef.onOpen()" v-if="hasPerm('depotRepayOrderAdd')">
						<template #icon>
							<plus-outlined/>
						</template>
						新增
					</a-button>
					<!-- <a-button danger @click="deleteBatchDepotRepayOrder()" v-if="hasPerm('depotRepayOrderBatchDelete')">删除</a-button>-->
					<a-button type="primary" @click="exportTable()">
						<export-outlined/>
						导出
					</a-button>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'licensePlate' && record.licensePlate">
					<p v-for="textValue in record.licensePlate.split(',')" :key="textValue" color="green">{{ textValue }}</p>
				</template>
				<template v-if="column.dataIndex === 'keeperName'">
					{{ record.keeperName }}<br>
					{{ record.keeperMobile }}
				</template>
				<template v-if="column.dataIndex === 'bookFlag'">
					<a-switch
						:loading="statusLoading"
						:checked="record.bookFlag === '预约开启'"
						@change="editBookFlag(record)"
					/>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a @click="detailFormRef.onOpen(record)"><span>详情</span> </a>
					<a @click="fileFormRef.onOpen(Object.assign(record,{'addFlag':2,'removeFlag':2}))">
						<a-divider type="vertical"/>
						<span>文件</span>
					</a>
					<a @click="approvalStateForm.onOpen(record)" v-if="hasPerm('出库还款二级审批') && record.bankOpApprovalState === '待审批'">
						<a-divider type="vertical"/>
						<span>审批</span></a>
					<br>
					<template v-if="record.bankOpApprovalState === '已审批' && record.repayState !== '已结束'">
						<a @click="addPlugFormRef.onOpen(record)" v-if="hasPerm('候补车牌')">
							<a-divider type="vertical"/>
							<span>补充车牌</span>
						</a>
						<a @click="offOrderFormRef.onOpen(record)">
							<a-divider type="vertical"/>
							<span>关单</span> </a>
						<a @click="approvalPlugFormRef.onOpen(record)" v-if="hasPerm('放款单二级审批') && record.licensePlatePlug">
							<a-divider type="vertical"/>
							<span>车牌审批</span>
						</a>
					</template>
					<template v-if="record.bankOpApprovalState === '待审批'">
						<a @click="editFormRef.onOpen(record)" v-if="hasPerm('depotRepayOrderEdit') && record.bankOpApprovalState === '待审批'">
							<a-divider type="vertical"/>
							<span>编辑</span>
						</a>
						<a-popconfirm title="确定要删除吗？" @confirm="deleteDepotRepayOrder(record)">
							<a-button type="link" danger size="small" v-if="hasPerm('depotRepayOrderDelete')">
								<a-divider type="vertical"/>
								<span>删除</span>
							</a-button>
						</a-popconfirm>
					</template>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="table.refresh(true)"/>
	<AddForm ref="addFormRef" @successful="table.refresh(true)"/>
	<AddPlugForm ref="addPlugFormRef" @successful="table.refresh(true)"/>
	<EditForm ref="editFormRef" @successful="table.refresh(true)"/>
	<FileForm ref="fileFormRef" @successful="table.refresh(true)"/>
	<DetailForm ref="detailFormRef"/>
	<OffOrderForm ref="offOrderFormRef" @successful="table.refresh(true)"/>
	<ApprovalForm ref="approvalFormRef" @successful="table.refresh(true)"/>
	<ApprovalPlugForm ref="approvalPlugFormRef" @successful="table.refresh(true)"/>
	<ApprovalStateForm ref="approvalStateForm" @successful="table.refresh(true)"/>
</template>

<script setup name="depotRepayOrder">
import {message} from 'ant-design-vue'
import tool from '@/utils/tool'
import Form from './form.vue'
import AddForm from './addForm.vue'
import AddPlugForm from './addPlugForm.vue'
import ApprovalPlugForm from './approvalPlugForm.vue'
import EditForm from './editForm.vue'
import DetailForm from './detailForm.vue'
import OffOrderForm from './offOrderForm.vue'
import ApprovalForm from './approvalForm.vue'
import ApprovalStateForm from './approvalStateForm.vue'
import depotRepayOrderApi from '@/api/biz/depotRepayOrderApi'
import dictOptionsApi from "@/api/biz/dictOptionsApi";
import FileForm from '../depotFile/formLeft.vue'
import jobApi from "@/api/dev/jobApi";
import depotLockBookApi from "@/api/biz/depotLockBookApi";
import * as XLSX from "xlsx";
import moment from "moment";

let searchFormState = reactive({})
const searchFormRef = ref()
const table = ref()
const formRef = ref()
const addFormRef = ref()
const addPlugFormRef = ref()
const editFormRef = ref()
const detailFormRef = ref()
const offOrderFormRef = ref()
const approvalFormRef = ref()
const approvalPlugFormRef = ref()
const approvalStateForm = ref()
const fileFormRef = ref()
const depotOptions = ref([])
const statusLoading = ref(false)
const toolConfig = {refresh: true, height: true, columnSetting: true, striped: false}
// 查询区域显示更多控制
const advanced = ref(false)
const toggleAdvanced = () => {
	advanced.value = !advanced.value
}
const columns = [
	{
		title: '企业客户',
		dataIndex: 'depotGrainName'
	},
	{
		title: '贷款合同号',
		dataIndex: 'contractCode'
	},
	{
		title: '还款单号',
		dataIndex: 'repayOrderNo'
	},
	{
		title: '粮食种类',
		dataIndex: 'grainGroup'
	},
	{
		title: '状态',
		dataIndex: 'repayState'
	},
	{
		title: '还款本金(元)',
		dataIndex: 'repayPrincipal'
	},
	{
		title: '利息(元)',
		dataIndex: 'repayInterest'
	},
	{
		title: '出库单价(元/吨)',
		dataIndex: 'repayPrice'
	},
	{
		title: '总提货量(吨)',
		dataIndex: 'repayTonSum'
	},
	{
		title: '已出库量(吨)',
		dataIndex: 'repayTonOut'
	},
	{
		title: '车牌',
		dataIndex: 'licensePlate'
	},
	{
		title: '授权提货人',
		dataIndex: 'keeperName'
	},
	{
		title: '审批',
		dataIndex: 'bankOpApprovalState'
	},
	{
		title: '车辆预约',
		dataIndex: 'bookFlag',
		width: '80px'
	},
]
// 操作栏通过权限判断是否显示
columns.push({
	title: '操作',
	dataIndex: 'action',
	align: 'center',
	width: '150px'
})
let selectedRowKeys = ref([])
// 列表选择配置
const options = {
	alert: {
		show: false,
		clear: () => {
			selectedRowKeys = ref([])
		}
	},
	rowSelection: {
		onChange: (selectedRowKey, selectedRows) => {
			selectedRowKeys.value = selectedRowKey
		}
	}
}
dictOptionsApi.options(Object.assign('', {'dictValue': '粮库'})).then((data) => {
	depotOptions.value = data
})
let loadDataLst
const loadData = (parameter) => {
	const searchFormParam = JSON.parse(JSON.stringify(searchFormState))
	return depotRepayOrderApi.depotRepayOrderPage(Object.assign(parameter, searchFormParam)).then((data) => {
		loadDataLst = data.records
		return data
	})
}
// 预约启停
const editBookFlag = (record) => {
	if (record.bankOpApprovalState !== '已审批') {
		message.warning('还未审批，不可操作')
		return false
	}
	statusLoading.value = true
	depotRepayOrderApi
		.depotRepayOrderEditBookFlag({"id": record.id, "bookFlag": record.bookFlag === '预约开启' ? '预约关闭' : '预约开启'}, false)
		.then(() => {
			table.value.refresh(true)
		})
		.finally(() => {
			statusLoading.value = false
		})
}
// 关单
const offOrder = (record) => {
	statusLoading.value = true
	depotRepayOrderApi
		.depotRepayOrderEditOffOrder({"id": record.id})
		.then(() => {
			table.value.refresh(true)
		}).catch((err) => {
		console.log(err)
		if (err.code !== 13004) return
		console.log(err.msg)
	})
		.finally(() => {
			statusLoading.value = false
		})
}
// 删除
const deleteDepotRepayOrder = (record) => {
	let params = [
		{
			id: record.id
		}
	]
	depotRepayOrderApi.depotRepayOrderDelete(params).then(() => {
		table.value.refresh(true)
	})
}
// 批量删除
const deleteBatchDepotRepayOrder = () => {
	if (selectedRowKeys.value.length < 1) {
		message.warning('请选择一条或多条数据')
		return false
	}
	const params = selectedRowKeys.value.map((m) => {
		return {
			id: m
		}
	})
	depotRepayOrderApi.depotRepayOrderDelete(params).then(() => {
		table.value.clearRefreshSelected()
	})
}
// 导出
const exportTable = () => {
	let tableData = [['企业客户', '贷款合同编号', '还款单号', '上次结转还款单号', '粮食种类', '库位', '还款本金', '利息', '还款单价', '还款金额'
		, '本单出库量(吨)', '总提货量(吨)', '已出库重量(吨)', '待出库重量(吨)', '上次扭转余量(吨)', '车牌', '候补车牌', '授权提货人', '授权提货人身份证号'
		, '授权提货人联系方式', '审批状态', '审批人', '审批时间', '预约开启状态', '单据状态', '申请时间', '申请人']]
	let idStr = ''
	if (selectedRowKeys.value.length > 0) {
		selectedRowKeys.value.map((m) => {
			idStr = idStr + ',' + m
		})
	}
	loadDataLst.map((m) => {
		if (!idStr || idStr.indexOf(m.id) > 0)
			tableData.push([m.depotGrainName, m.contractCode, m.repayOrderNo, m.repayBeforeOrderNo, m.grainGroup, m.shedName, m.repayPrincipal, m.repayInterest, m.repayPrice, m.repayAmount
				, m.repayTonThis, m.repayTonSum, m.repayTonOut, m.repayTonSurplus, m.repayBeforeTonSurplus, m.licensePlate, m.licensePlatePlug, m.keeperName, m.keeperCitizenId
				, m.keeperMobile, m.bankOpApprovalState, m.approvalUserName, m.bankOpApprovalTime, m.bookFlag, m.repayState, m.createTime, m.createUserName])
	})
	let workSheet = XLSX.utils.aoa_to_sheet(tableData)
	let bookNew = XLSX.utils.book_new()
	XLSX.utils.book_append_sheet(bookNew, workSheet, 'Sheet1')
	let name = '还款单记录' + moment().format('_YYYY-MM-DD') + '.xlsx'
	XLSX.writeFile(bookNew, name)
}
const repayStateOptions = tool.dictList('单据状态')
const bankOpApprovalStateOptions = tool.dictList('审批状态')
</script>
