<template>
	<a-card :bordered="false" style="margin-bottom: 10px" class="mb-2">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="预约单号" name="loadNumber">
						<a-input v-model:value="searchFormState.loadNumber" placeholder="预约单号查询" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="客户名称" name="customerName">
						<a-input v-model:value="searchFormState.customerName" placeholder="客户名称查询" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="货品名称" name="goodsName">
						<a-input v-model:value="searchFormState.goodsName" placeholder="货品名称查询" />
					</a-form-item>
				</a-col>
				<template v-if="advanced">

					<a-col :span="6">
						<a-form-item label="支付方式" name="payType">
							<a-select v-model:value="searchFormState.payType" placeholder="支付方式查询"
									  :options="payTypeList"
							> </a-select>
						</a-form-item>
					</a-col>

					<a-col :span="6">
						<a-form-item label="创建时间" name="createTime">
							<a-range-picker
								v-model:value="searchFormState.createTime"
								value-format="YYYY-MM-DD"
							/>
						</a-form-item>
					</a-col>
				</template>
				<a-col :span="6">
					<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
					<a @click="toggleAdvanced" style="margin-left: 8px">
						{{ advanced ? '收起' : '展开' }}
						<component :is="advanced ? 'up-outlined' : 'down-outlined'" />
					</a>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
	<a-card :bordered="false">
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			bordered
			:row-key="(record) => record.id"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('bizLoadAppointAdd')">
						<template #icon><plus-outlined /></template>
						新增
					</a-button>
					<a-button @click="exportTotal" v-if="hasPerm('bizLoadAppointExport')">
						<template #icon>
							<export-outlined/>
						</template>
						导出
					</a-button>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'action'">
<!--					<a-space>
						<a @click="formRef.onOpen(record)" v-if="hasPerm('bizLoadAppointEdit')">编辑</a>
						<a-divider type="vertical" v-if="hasPerm(['bizLoadAppointEdit', 'bizLoadAppointDelete'], 'and')" />
						<a-popconfirm title="确定要删除吗？" @confirm="deleteBizLoadAppoint(record)">
							<a-button type="link" danger size="small" v-if="hasPerm('bizLoadAppointDelete')">删除</a-button>
						</a-popconfirm>
					</a-space>-->

					<a @click="showModal(record)" v-if="record.status == '2'">二维码</a>

					<a-divider type="vertical" v-if="record.status == '2' "/>

					<a-dropdown>
						<a class="ant-dropdown-link">
							更多
							<DownOutlined />
						</a>
						<template #overlay>
							<a-menu>
								<a-menu-item>
									<a size="small" type="link" @click="detailRef.onOpen(record)" >详情</a>
								</a-menu-item>
								<a-menu-item  v-if="hasPerm('bizLoadAppointSubmit') && record.status=='0'">
									<a style="color:orangered" size="small" type="link" @click="bizLoadAppointsubmit(record.id)">提交</a>
								</a-menu-item>
								<a-menu-item v-if="hasPerm('bizLoadAppointSign') && record.status == '1'">
									<a style="color:orange" @click="XnSignNameRef.show(record.id)">签名</a>
								</a-menu-item>
								<a-menu-item v-if="hasPerm('bizLoadAppointEdit') && (record.status == '0')">
									<a style="color:blue" size="small" type="link" @click="formRef.onOpen(record)" >编辑</a>
								</a-menu-item>
								<a-menu-item v-if="hasPerm('bizLoadAppointDelete') && (record.status == '0')">
									<a style="color:red" size="small" type="link" @click="deleteConfig(record)">删除</a>
								</a-menu-item>
							</a-menu>
						</template>
					</a-dropdown>
				</template>
				<template v-if="column.dataIndex === 'status'">
					<a-tag
						:color="
							record.status === '1'
								? 'blue'
								: record.status === '2'
								  ? 'warning'
								  : record.status === '3'
								  ? 'processing'
								  : record.status === '4'
								  ? 'volcano'
								  : record.status === '5'
								  ? 'purple'
								  : record.status === '6'
								  ? 'error'
								  : record.status === '7'
								  ? 'red'
								  : record.status === '8'
								  ? 'cyan'
								  : '#f50'
						"
					>
						{{ $TOOL.dictTypeData('load_appoint_status', record.status) }}
					</a-tag>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="tableRef.refresh()" />
	<Detail ref="detailRef" @successful="tableRef.refresh()" />
	<XnSignName ref="XnSignNameRef" @successful="signSuccess" />

	<a-modal v-model:visible="open" title="二维码" width="600px" style="height: 700px">
		<div id="qrcode" style="text-align: center; margin:  15px 5px 15px 5px">
			<a-row>
				<a-col :span="13" id="colFlag">
					<div style="margin-top:10px;font-size:16px;">
						<p id="projectCodeFlag">预约单号：{{ nowRecord.loadNumber }}</p>
						<p id="projectCodeFlag">服务客户名称：{{ nowRecord.customerName }}</p>
						<p id="projectCodeFlag">货品名称：{{ nowRecord.goodsName }}</p>
						<p id="projectCodeFlag">货品编码：{{ nowRecord.goodsCode }}</p>
						<p id="projectCodeFlag">船运供应商：{{ nowRecord.supplierName }}</p>
					</div>
				</a-col>
				<a-col :span="11">
					<a-image width="250"  height="100%" :src="qrCodeUrl.codeUrl"></a-image>
				</a-col>
			</a-row>
		</div>
		<template #footer>
			<a-button @click="closeQrCode">关闭</a-button>
			<a-button type="primary" @click="downloadFile">下载</a-button>
		</template>
	</a-modal>
</template>

<script setup name="bizloadappoint">
	import { cloneDeep } from 'lodash-es'
	import Form from './form.vue'
	import bizLoadAppointApi from '@/api/biz/bizLoadAppointApi'
	import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
	import {Modal} from 'ant-design-vue';
	import {createVNode} from 'vue';
	import tool from '@/utils/tool'
	import Detail from "./detail.vue";
	import QRCode from 'qrcode'
	import html2canvas from 'html2canvas'
	import downloadUtil from '@/utils/downloadUtil'


	const tableRef = ref()
	const formRef = ref()
	const detailRef = ref()
	const XnSignNameRef = ref()
	const nowRecord = ref()
	const submitLoading = ref(false)
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }

	//查询数据
	const searchFormState = ref({})
	const searchFormRef = ref()
	const payTypeList = tool.dictList('pay_type')

	// 查询区域显示更多控制
	const advanced = ref(false)
	const toggleAdvanced = () => {
		advanced.value = !advanced.value
	}


	const columns = [
		{
			title: '预约单号',
			dataIndex: 'loadNumber',
			align:'center'
		},
		{
			title: '服务客户名称',
			dataIndex: 'customerName',
			align:'center'
		},
		{
			title: '货品名称',
			dataIndex: 'goodsName',
			align:'center'
		},
		{
			title: '订单数量(吨)',
			dataIndex: 'orderWeight',
			align:'center'
		},
		{
			title: '单价(元/吨)',
			dataIndex: 'orderPrice',
			align:'center'
		},
		{
			title: '订单总额(元)',
			dataIndex: 'orderAmount',
			align:'center'
		},
		{
			title: '船运供应商',
			dataIndex: 'supplierName',
			align:'center'
		},
		{
			title: '运费单价(元/吨)',
			dataIndex: 'freightPrice',
			align:'center'
		},

		{
			title: '状态',
			dataIndex: 'status',
			align:'center'
		},
	]
	// 操作栏通过权限判断是否显示
	columns.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: 150
	})

	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		// columns数字类型字段加入 needTotal: true 可以勾选自动算账
		alert: {
			show: true,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	const loadData = (parameter) => {
		const searchFormParam = cloneDeep(searchFormState.value)
		// 创建时间范围查询条件重载
		if (searchFormParam.createTime) {
			searchFormParam.createTimeBegin = searchFormParam.createTime[0]
			searchFormParam.createTimeEnd = searchFormParam.createTime[1]
			delete searchFormParam.createTime
		}
		return bizLoadAppointApi.bizLoadAppointPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}

	//提交
	const bizLoadAppointsubmit = (id) =>{
		Modal.confirm({
			title: '提示',
			icon: createVNode(ExclamationCircleOutlined),
			content: '是否提交该数据？',
			onOk() {
				submitLoading.value = true
				let params =
					{
						id: id
					}

				bizLoadAppointApi
					.submit(params)
					.then(() => {
						tableRef.value.refresh(true)
					})
					.finally(() => {
						submitLoading.value = false
					})
			},
			onCancel() {}
		})
	}

	// 签名板组件回调
	const signSuccess = (value) => {
		const param = {
			id:value.id,
			customerSign: value.value
		}
		bizLoadAppointApi.updateCustomerSign(param).then(() => {
			tableRef.value.refresh(true)
		})
	}


	//导出
	const exportTotal = () => {
		Modal.confirm({
			title: '确定要导出记录吗？',
			icon: createVNode(ExclamationCircleOutlined),
			content: '',
			onOk() {
				submitLoading.value = true
				const searchFormParam = cloneDeep(searchFormState.value)
				// 创建时间范围查询条件重载
				if (searchFormParam.createTime) {
					searchFormParam.createTimeBegin = searchFormParam.createTime[0]
					searchFormParam.createTimeEnd = searchFormParam.createTime[1]
					delete searchFormParam.createTime
				}
				bizLoadAppointApi
					.exportRecord(Object.assign(searchFormParam))
					.then((res) => {
						downloadUtil.resultDownload(res)
					})
					.finally(() => {
						submitLoading.value = false
					})
			},
			onCancel() {}
		})
	}


	//二维码
	const open = ref(false);
	const qrCodeUrl = ref({})
	const showModal = (record) => {
		nowRecord.value = record
		open.value = true;
		getQrCode(record)

	};

	const getQrCode = (record) => {
		//QRCode.toDataURL("id:"+record.id+"saleCode:"+record.saleCode, {
		let param = {
			id:record.id,
			loadNumber:record.loadNumber
		}
		QRCode.toDataURL(JSON.stringify(param), {
			errorCorrectionLevel: 'H',
			margin: 1,
			height: 206,
			width: 206,
			type: '10',
			scal: 177,
			color: {
				dark: '#000' // 二维码背景颜色
			},
			rendererOpts: {
				quality: 0.9
			}
		})
			.then((url) => {
				qrCodeUrl.value.codeUrl = url
			})
			.catch((err) => {
				console.error(err)
			})
	}

	const closeQrCode = () => {
		open.value = false;
	}

	// 下载二维码
	const downloadFile = () => {
		const qrcodeDiv = document.getElementById('qrcode');
		html2canvas(qrcodeDiv, {
			logging: false,
			allowTaint: true,
			scale: window.devicePixelRatio,
			scrollY: 0,
			scrollX: 0,
			useCORS: true,
			backgroundColor: '#ffffff'
		})
			.then(function (canvas) {
				const a = window.document.createElement('a')
				a.href = canvas.toDataURL('image/png')
				a.download = '二维码'
				a.click()
				this.$message.success('正在进行下载保存')
			})
			.catch((err) => {
				console.log(err)
			})
	}

	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		tableRef.value.refresh(true)
	}
	// 删除
	const deleteBizLoadAppoint = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		bizLoadAppointApi.bizLoadAppointDelete(params).then(() => {
			tableRef.value.refresh(true)
		})
	}
	// 删除
	const deleteConfig = (record) => {

		Modal.confirm({
			title: '确定删除该数据吗？',
			icon: createVNode(ExclamationCircleOutlined),
			content: '',
			onOk() {
				submitLoading.value = true
				let params = [
					{
						id: record.id
					}
				]

				bizLoadAppointApi
					.bizLoadAppointDelete(params)
					.then(() => {
						tableRef.value.refresh(true)
					})
					.finally(() => {
						submitLoading.value = false
					})
			},
			onCancel() {}
		})
	}
	// 批量删除
	const deleteBatchBizLoadAppoint = (params) => {
		bizLoadAppointApi.bizLoadAppointDelete(params).then(() => {
			tableRef.value.clearRefreshSelected()
		})
	}
</script>
