<template>
	<a-row :gutter="10">
		<a-col :xs="24" :sm="24" :md="24" :lg="5" :xl="5">
			<a-card :bordered="false" :loading="cardLoading" class="left-tree-container">
				<a-tree
					v-if="treeData.length > 0"
					v-model:expandedKeys="defaultExpandedKeys"
					:tree-data="treeData"
					:field-names="treeFieldNames"
					@select="treeSelect"
				/>
				<a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" />
			</a-card>
		</a-col>
		<a-col :xs="24" :sm="24" :md="24" :lg="19" :xl="19">
			<a-card :bordered="false" class="xn-mb10">
				<a-form ref="searchFormRef" name="advanced_search" class="ant-advanced-search-form" :model="searchFormState">
					<a-row :gutter="24">
						<a-col :span="8">
							<a-form-item name="searchKey" label="名称关键词">
								<a-input v-model:value="searchFormState.searchKey" placeholder="请输入门店名称关键词" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-button type="primary" @click="tableRef.refresh(true)">
								<template #icon><SearchOutlined /></template>
								查询
							</a-button>
							<a-button class="snowy-button-left" @click="reset">
								<template #icon><redo-outlined /></template>
								重置
							</a-button>
						</a-col>
					</a-row>
				</a-form>
			</a-card>
			<a-card :bordered="false">
				<s-table
					ref="tableRef"
					:columns="columns"
					:data="loadData"
					:expand-row-by-click="true"
					:alert="options.alert.show"
					bordered
					:row-key="(record) => record.id"
					:row-selection="options.rowSelection"
				>
					<template #operator class="table-operator">
						<a-space>
							<a-button type="primary" @click="formRef.onOpen(undefined, searchFormState.parentId)">
								<template #icon><plus-outlined /></template>
								新增
							</a-button>
							<xn-batch-button
								buttonName="批量删除"
								icon="DeleteOutlined"
								buttonDanger
								:selectedRowKeys="selectedRowKeys"
								@batchCallBack="deleteBatchOrg"
							/>
						</a-space>
					</template>
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'category'">
							{{ $TOOL.dictTypeData('ORG_CATEGORY', record.category) }}
						</template>
						<template v-if="column.dataIndex === 'action'">
							<a @click="showModal(record)" >二维码</a>
							<a-divider type="vertical" />
							<a @click="formRef.onOpen(record)">编辑</a>
							<a-divider type="vertical" />
							<a-popconfirm title="删除此组织与下级组织吗？" @confirm="removeOrg(record)">
								<a-button type="link" danger size="small">删除</a-button>
							</a-popconfirm>
						</template>
					</template>
				</s-table>
			</a-card>
		</a-col>
	</a-row>
	<Form ref="formRef" @successful="tableRef.refresh()" />


	<a-modal v-model:visible="open" title="二维码">
		<div id="qrcode" style="text-align: center; margin: 15px;">
			<a-row>
				<a-col :span="14">
					<br><br>
					<p><span>门店名称：</span>{{nowRecord.name}}</p>
					<p><span>门店编码：</span>{{ nowRecord.code }}</p>
				</a-col>
				<a-col :span="8">
					<a-image width="206" :src="qrCodeUrl.codeUrl">
						<template #default>
							<img src="https://www.antdv.com/assets/logo.1ef800a8.svg" class="icon" alt="Icon" />
						</template>
					</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="sysOrg">
	import { Empty } from 'ant-design-vue'
	import { isEmpty } from 'lodash-es'
	import orgApi from '@/api/sys/orgApi'
	import Form from './form.vue'
	import QRCode from 'qrcode'
	import html2canvas from 'html2canvas'

	const columns = [
		{
			title: '门店名称',
			dataIndex: 'name',
			width:150
		},
		{
			title: '门店编码',
			dataIndex: 'code',
			width:120
		},
		{
			title: '门店地址',
			dataIndex: 'address',
			width:180
		},
		{
			title: '分类',
			dataIndex: 'category',
			width: 100
		},
		{
			title: '排序',
			dataIndex: 'sortCode',
			width: 80
		},
		{
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: 180
		}
	]
	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		alert: {
			show: false,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	// 定义tableDOM
	const tableRef = ref(null)
	const formRef = ref()
	const searchFormRef = ref()
	const searchFormState = ref({})
	// 默认展开的节点
	const defaultExpandedKeys = ref([])
	const treeData = ref([])
	// 替换treeNode 中 title,key,children
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }
	const cardLoading = ref(true)

	// 表格查询 返回 Promise 对象
	const loadData = (parameter) => {
		loadTreeData()
		return orgApi.orgPage(Object.assign(parameter, searchFormState.value)).then((res) => {
			return res
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		tableRef.value.refresh(true)
	}
	// 加载左侧的树
	const loadTreeData = () => {
		orgApi.orgTree().then((res) => {
			cardLoading.value = false
			if (res !== null) {
				treeData.value = res
				if (isEmpty(defaultExpandedKeys.value)) {
					// 默认展开2级
					treeData.value.forEach((item) => {
						// 因为0的顶级
						if (item.parentId === '0') {
							defaultExpandedKeys.value.push(item.id)
							// 取到下级ID
							if (item.children) {
								item.children.forEach((items) => {
									defaultExpandedKeys.value.push(items.id)
								})
							}
						}
					})
				}
			}
		})
	}
	// 点击树查询
	const treeSelect = (selectedKeys) => {
		if (selectedKeys.length > 0) {
			searchFormState.value.parentId = selectedKeys.toString()
		} else {
			delete searchFormState.value.parentId
		}
		tableRef.value.refresh(true)
	}
	// 删除
	const removeOrg = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		orgApi.orgDelete(params).then(() => {
			tableRef.value.refresh(true)
		})
	}
	// 批量删除
	const deleteBatchOrg = (params) => {
		orgApi.orgDelete(params).then(() => {
			tableRef.value.clearRefreshSelected()
		})
	}


	//二维码
	const open = ref(false);
	const qrCodeUrl = ref({})
	const qrcodeCanvasRef = ref();
	const nowRecord = 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,
			code:record.code
		}
		QRCode.toDataURL(JSON.stringify(param), {
			errorCorrectionLevel: 'H',
			margin: 1,
			height: 206,
			width: 206,
			type: '10',
			scal: 177,
			color: {
				dark: '#000' // 二维码背景颜色
			},
			rendererOpts: {
				quality: 0.9
			},
			icon:'/public/img/tanglogo.png'
		})
			.then((url) => {
				qrCodeUrl.value.codeUrl = url
			})
			.catch((err) => {
				console.error(err)
			})
	}

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

	// 下载二维码
	const downloadFile = () => {
		html2canvas(qrcode, {
			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)
			})
	}
</script>

<style scoped>
	.ant-form-item {
		margin-bottom: 0 !important;
	}
	.snowy-button-left {
		margin-left: 8px;
	}
	.icon {
		position: absolute;
		top: 10px;
		right: 10px;
		width: 40px;
		height: 40px;
	}
</style>
