<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="orderNumber">
						<a-input v-model:value="searchFormState.orderNumber" placeholder="订单编号查询" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="订单名称" name="orderName">
						<a-input v-model:value="searchFormState.orderName" 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>
				<template v-if="advanced">
					<a-col :span="6">
						<a-form-item label="货品名称" name="goodsName">
							<a-input v-model:value="searchFormState.goodsName" placeholder="货品名称查询" />
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="订单状态" name="orderStatus">
							<a-select v-model:value="searchFormState.orderStatus" placeholder="订单状态查询"
									  :options="orderStatusList"
							> </a-select>
						</a-form-item>
					</a-col>
<!--					<a-col :span="6">
						<a-form-item label="订单来源" name="orderSource">
							<a-select v-model:value="searchFormState.orderSource" placeholder="订单状态查询"
									  :options="orderSourceList"
							> </a-select>
						</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('bizOrderAdd')">
						<template #icon><plus-outlined /></template>
						新增
					</a-button>
					<a-button @click="exportTotal" v-if="hasPerm('bizOrderExport')">
						<template #icon>
							<export-outlined/>
						</template>
						导出
					</a-button>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'orderType'">
					<a-tag
						:color="
							record.orderType === '1'
								? 'orange'
								: record.orderType === '2'
								  ? 'green'
								  : 'purple'
						"
					>
						{{ $TOOL.dictTypeData('order_type', record.orderType) }}
					</a-tag>
				</template>
				<template v-if="column.dataIndex === 'orderSource'">
					<a-tag
						:color="
							record.orderSource === '1'
								? 'orange'
								: record.orderSource === '2'
								  ? 'green'
								  : 'purple'
						"
					>
						{{ $TOOL.dictTypeData('order_source', record.orderSource) }}
					</a-tag>
				</template>
				<template v-if="column.dataIndex === 'orderStatus'">
					<a-tag
						:color="
							record.orderStatus === '1'
								? 'blue'
								: record.orderStatus === '2'
								  ? 'warning'
								  : record.orderStatus === '3'
								  ? 'processing'
								  : record.orderStatus === '4'
								  ? 'volcano'
								  : record.orderStatus === '5'
								  ? 'purple'
								  : record.orderStatus === '6'
								  ? 'error'
								  : record.orderStatus === '7'
								  ? 'red'
								  : '#f50'
						"
					>
						{{ $TOOL.dictTypeData('order_status', record.orderStatus) }}
					</a-tag>
				</template>
				<template v-if="column.dataIndex === 'orderWeight'">
					{{record.orderWeight + '吨'}}
				</template>
				<template v-if="column.dataIndex === 'netWeight'">
					{{record.netWeight + '吨'}}
				</template>
				<template v-if="column.dataIndex === 'action'">

					<a @click="showModal(record)" v-if="record.orderStatus == '3' || record.orderStatus == '4'">二维码</a>

					<a-divider type="vertical" v-if="record.orderStatus == '3' || record.orderStatus == '4'"/>

					<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('bizOrderSubmit') && record.orderStatus=='0'">
									<a style="color:orangered" size="small" type="link" @click="submit(record.id)">提交</a>
								</a-menu-item>
								<a-menu-item v-if="hasPerm('bizOrderEdit') && (record.orderStatus == '0')">
									<a style="color:blue" size="small" type="link" @click="formRef.onOpen(record)" >编辑</a>
								</a-menu-item>

								<a-menu-item v-if="hasPerm('bizOrderDelete') && (record.orderStatus == '0')">
									<a style="color:red" size="small" type="link" @click="deleteConfig(record)">删除</a>
								</a-menu-item>

<!--								<a-menu-item v-if="record.orderStatus == '1'">
									<a style="color:orange" @click="selectCustomer(record)">绑定</a>
								</a-menu-item>-->

								<a-menu-item v-if="hasPerm('bizOrderSign') && record.orderStatus == '1'">
									<a style="color:orange" @click="XnSignNameRef.show(record.id)">签名</a>
								</a-menu-item>

								<a-menu-item v-if="hasPerm('bizOrderConfirm') && record.orderStatus == '2'">
									<a style="color:blue" @click="orderConfirm(record.id)">确认</a>
								</a-menu-item>

								<a-menu-item v-if="hasPerm('bizOrderAudit') && record.orderStatus == '5'">
									<a style="color:green" @click="reviewRef.showModal(record.id)">审核</a>
								</a-menu-item>

								<a-menu-item v-if="hasPerm('bizOrderFlow') && (record.orderStatus == '4' || record.orderStatus=='5' || record.orderStatus=='6' || record.orderStatus=='7')">
									<a style="color:deepskyblue" @click="flowRef.onOpen(record)">流水</a>
								</a-menu-item>

								<a-menu-item v-if="hasPerm('bizOrderConfig') && (record.orderStatus == '3' || record.orderStatus=='4')">
									<a style="color:forestgreen" @click="showMore(record)">配置</a>
								</a-menu-item>

								<a-menu-item v-if="hasPerm('bizOrderEnd') && (record.orderStatus == '3' || record.orderStatus == '4')">
									<a style="color:red" @click="endRef.showModal(record.id)">结束</a>
								</a-menu-item>
							</a-menu>
						</template>
					</a-dropdown>

<!--					<a-space>
						<a @click="formRef.onOpen(record)" v-if="hasPerm('bizOrderEdit')">编辑</a>
						<a-divider type="vertical" v-if="hasPerm(['bizOrderEdit', 'bizOrderDelete'], 'and')" />
						<a-button type="link" danger size="small" v-if="hasPerm('bizOrderDelete')" @click="deleteConfig(record)">删除</a-button>
					</a-space>-->
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="tableRef.refresh()" />

	<Detail ref="detailRef" @successful="tableRef.refresh()" />
	<Flow ref="flowRef" @successful="tableRef.refresh()" />
	<Review ref="reviewRef" @successful="tableRef.refresh(true)" />
	<End ref="endRef" @successful="tableRef.refresh(true)" />
	<XnSignName ref="XnSignNameRef" :image="searchFormState.orderSign" @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="projectNameFlag">订单名称：{{nowRecord.orderName}}</p>
						<p id="projectCodeFlag">订单编码：{{ nowRecord.orderNumber }}</p>
						<p id="projectCodeFlag">客户名称：{{ nowRecord.customerName }}</p>
						<p id="projectCodeFlag">货品名称：{{ nowRecord.goodsName }}</p>
						<p id="projectCodeFlag">提货时间：{{ nowRecord.confStartTime+'~'+nowRecord.confEndTime }}</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>


	<xn-customer-selector
		ref="CustomerSelectorPlusRef"
		:add-show="false"
		:show="false"
		:role-global="true"
		@onBack="customerBack"
	/>


	<a-modal
		v-model:visible="moreFlag"
		title="扫码次数配置"
		:footer="null"
		width="1100px"
		:body-style="{
			height: 'calc(100vh - 300px)',
			overflow: 'auto'
		}"
		@cancel="onCloseAccount"
	>
		<a-card :bordered="false">
<!--			<a-button type="primary" @click="addAccount()" style="margin-bottom:10px;">
				<template #icon><plus-outlined /></template>
				新增
			</a-button>-->
			<a-table ref="tableRef" :columns="columns1" :data-source="data1" bordered :row-key="(record) => record.id">
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'action'">
						<a @click="editAccount(record)">编辑</a>
<!--						<a-divider type="vertical" />
						<a-popconfirm title="确定要删除吗？" @confirm="removeUser(record)">
							<a-button type="link" danger size="small">删除</a-button>
						</a-popconfirm>-->
					</template>
					<template v-if="column.dataIndex === 'remain'">
						{{record.applyNumber-record.applyNumberAlready}}
					</template>
				</template>
			</a-table>
		</a-card>
	</a-modal>

	<a-modal
		v-model:visible="editAccountFlag"
		:title="formData.id ? '编辑扫码次数' : '添加扫码次数'"
		class="custom-modal"
		width="800px"
		@ok="handleOk"
		@cancel="onClose"
	>

		<a-form ref="formSubmitRef" :model="formData" :rules="formRules" :wrapper-col="wrapperCol" :label-col="labelCol">
			<a-form-item label="开始时间：" name="beginTime">
				<a-input v-model:value="formData.beginTime" placeholder="请输入提货开始时间" allow-clear disabled/>
			</a-form-item>
			<a-form-item label="结束时间：" name="endTime">
				<a-input v-model:value="formData.endTime" placeholder="请输入提货结束时间" allow-clear disabled/>
			</a-form-item>
			<a-form-item label="申请数量：" name="applyNumber">
				<a-input-number v-model:value="formData.applyNumber" style="width:90%"  :precision="0" :min="1" :max="99999" placeholder="请输入申请数量" allow-clear /><span style="margin-left:10px;">次</span>
			</a-form-item>
		</a-form>

	</a-modal>
</template>

<script setup name="bizorder">
	import { cloneDeep } from 'lodash-es'
	import Form from './form.vue'
	import Detail from './detail.vue'
	import bizOrderApi from '@/api/biz/bizOrderApi'
	import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
	import {Modal} from 'ant-design-vue';
	import {createVNode} from 'vue';
	import QRCode from 'qrcode'
	import html2canvas from 'html2canvas'
	import userApi from '@/api/sys/userApi'
	import downloadUtil from '@/utils/downloadUtil'
	import tool from '@/utils/tool'
	import Review from './review.vue'
	import Flow from './flow.vue'
	import bizOrderConfigApi from "@/api/biz/bizOrderConfigApi";
	import { required } from '@/utils/formRules'
	import End from './end.vue'

	const editAccountFlag = ref(false)
	const moreFlag = ref(false)
	const selectedRecord = ref({})
	const CustomerSelectorPlusRef = ref()
	const nowRecord = ref()
	const tableRef = ref()
	const formRef = ref()
	const configRef = ref()
	const flowRef = ref()
	const reviewRef = ref()
	const endRef = ref()
	const detailRef = ref()
	const XnSignNameRef = ref()
	const submitLoading = ref(false)
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }

	//查询数据
	const searchFormState = ref({})
	const searchFormRef = ref()
	const orderStatusList = tool.dictList('order_status')
	const orderSourceList = tool.dictList('order_source')

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

	// 表单数据
	const formData = ref({})

	const columns = [
		{
			title: '订单编号',
			dataIndex: 'orderNumber',
			align:'center',
			width: 130
		},
		{
			title: '订单名称',
			dataIndex: 'orderName',
			align:'center',
			width: 130
		},
		{
			title: '客户名称',
			dataIndex: 'customerName',
			align:'center',
			width: 130
		},
		{
			title: '货品名称',
			dataIndex: 'goodsName',
			align:'center',
			width: 130
		},
		/*{
			title: '订单类型',
			dataIndex: 'orderType',
			align:'center'
		},*/
		/*{
			title: '订单来源',
			dataIndex: 'orderSource',
			align:'center',
			width: 100
		},*/
		{
			title: '提货开始时间',
			dataIndex: 'confStartTime',
			align:'center',
			width: 130
		},
		{
			title: '提货结束时间',
			dataIndex: 'confEndTime',
			align:'center',
			width: 130
		},
		{
			title: '订单状态',
			dataIndex: 'orderStatus',
			align:'center',
			width: 80
		},
		{
			title: '订单重量',
			dataIndex: 'orderWeight',
			align:'center',
			width: 100
		},
		{
			title: '过磅重量',
			dataIndex: 'netWeight',
			align:'center',
			width: 100
		},
	]
	// 操作栏通过权限判断是否显示
	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)
		return bizOrderApi.bizOrderPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		tableRef.value.refresh(true)
	}

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

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

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

				bizOrderApi
					.submit(params)
					.then(() => {
						tableRef.value.refresh(true)
					})
					.finally(() => {
						submitLoading.value = false
					})
			},
			onCancel() {}
		})
	}
	// 删除
	const deleteBizOrder = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		bizOrderApi.bizOrderDelete(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
					}
				]

				bizOrderApi
					.bizOrderDelete(params)
					.then(() => {
						tableRef.value.refresh(true)
					})
					.finally(() => {
						submitLoading.value = false
					})
			},
			onCancel() {}
		})
	}
	// 批量删除
	const deleteBatchBizOrder = (params) => {
		bizOrderApi.bizOrderDelete(params).then(() => {
			tableRef.value.clearRefreshSelected()
		})
	}

	//二维码
	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,
			orderName:record.orderName
		}
		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 selectCustomer = (record) => {
		selectedRecord.value = record
		// 查询到已有角色，并转为ids的格式，给角色选择器
		CustomerSelectorPlusRef.value.showModel(record.customerId)
	}
	// 角色选择回调
	const customerBack = (value) => {
		let params = {
			id: selectedRecord.value.id,
			customerIdList: []
		}
		if (value.length > 0) {
			value.forEach((item) => {
				params.customerIdList.push(item)
			})
		}
		bizOrderApi.bindCustomerId(params).then(() => {
			tableRef.value.refresh()
		})
	}


	//导出
	const exportTotal = () => {
		const searchFormParam = cloneDeep(searchFormState.value)
		bizOrderApi.exportRecord(Object.assign(searchFormParam)).then((res)=>{
			downloadUtil.resultDownload(res)
		})
	}

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

	//结束订单
	const endOrder = (record) => {
		/*let param = {
			id:record.id
		}
		bizOrderApi.endOrder(param).then((res)=>{
			tableRef.value.refresh()
		})*/

		Modal.confirm({
			title: '确定结束该订单吗？',
			icon: createVNode(ExclamationCircleOutlined),
			content: '',
			onOk() {
				submitLoading.value = true
				let param = {
					id:record.id
				}

				bizOrderApi
					.endOrder(param)
					.then(() => {
						tableRef.value.refresh(true)
					})
					.finally(() => {
						submitLoading.value = false
					})
			},
			onCancel() {}
		})
	}

	const data1 = ref([])
	const orderId = ref()
	const beginTime = ref()
	const endTime = ref()
	const formSubmitRef = ref()
	//打开扫码次数配置页
	const showMore = (record) => {
		orderId.value = record.id
		beginTime.value = record.confStartTime
		endTime.value = record.confEndTime
		loadData1()
		moreFlag.value = true

	}

	const loadData1 = () => {
		let param={
			orderId:orderId.value
		}
		bizOrderConfigApi.bizOrderConfigPage(param).then((res)=>{
			data1.value = res.records
		})
	}

	const columns1 = [
		{
			title: '提货开始时间',
			dataIndex: 'beginTime',
			align: 'center',
			resizable: true,
			ellipsis: true,
			width: 130
		},
		{
			title: '提货结束时间',
			dataIndex: 'endTime',
			align: 'center',
			resizable: true,
			ellipsis: true,
			width: 130
		},
		{
			title: '申请数量',
			dataIndex: 'applyNumber',
			align: 'center',
			resizable: true,
			ellipsis: true,
			width: 100
		},
		{
			title: '已约数量',
			dataIndex: 'applyNumberAlready',
			align: 'center',
			resizable: true,
			ellipsis: true,
			width: 100
		},
		{
			title: '可约数量',
			dataIndex: 'remain',
			align: 'center',
			resizable: true,
			ellipsis: true,
			width: 100
		},
	]
	columns1.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		fixed: 'right',
		width: 140,
	})


	const addAccount = () =>{
		formData.value = {}
		formData.value.orderId = orderId.value
		formData.value.beginTime = beginTime.value
		formData.value.endTime = endTime.value
		editAccountFlag.value = true
	}

	const formRules = {
		applyNumber: [required('请输入申请数量')],
	}

	//表单提交
	const handleOk = () => {
		console.log("handleOk")
		formSubmitRef.value.validate().then(() => {
			submitLoading.value = true
			const formDataParam = cloneDeep(formData.value)
			bizOrderConfigApi
				.bizOrderConfigSubmitForm(formDataParam, formDataParam.id)
				.then(() => {
					onClose()
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}

	const onClose = () => {
		formSubmitRef.value.resetFields()
		formData.value = {}
		editAccountFlag.value = false
		loadData1()
	}

	const editAccount = (record) => {
		formData.value = record
		editAccountFlag.value = true
	}


	const removeUser = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		bizOrderConfigApi.bizOrderConfigDelete(params).then(() => {
			loadData1()
		})
	}

	const onCloseAccount = () => {
		moreFlag.value = false
		data1.value = []
		orderId.value = ''
	}
</script>
