<template>
	<div class="pageWrap bgc">
		<div class="content-warp flex-column-page-wrap">
			<!-- 公用搜索组件 -->
			<LeSearchForm ref="searchForm" v-model:searchData="searchData" :forms="forms" :loading="tableOpts.options.loading"> </LeSearchForm>
			<div style="margin: 20px; font-size: 1.2em; color: red">演示关联业务审批逻辑，对应 业务流程KEY为 purchaseOrder</div>
			<!--  LeTable 组件使用  -->
			<LeTable
				ref="tableRef"
				v-model:searchParams="tableOpts.searchParams"
				v-bind="tableOpts"
				v-model:curRow="tableOpts.curRow"
				v-model:checked-options="checkedColumns"
				:columns="activeColumns"
			>
				<template #toolLeft>
					<el-button type="primary" @click="addHandler">
						<el-icon class="btn-icon">
							<Plus />
						</el-icon>
					</el-button>
					<el-button type="danger" :disabled="curSelectionRows.length === 0" @click="batch_del">
						<el-icon class="btn-icon">
							<Delete />
						</el-icon>
					</el-button>
				</template>

				<template #statusSlot="scope">
					<el-tag v-if="scope.row.status === 1" type="danger">已拒绝</el-tag>
					<el-tag v-else-if="scope.row.status === 2" type="success">已通过</el-tag>
					<el-tag v-else type="info">待审批</el-tag>
				</template>

				<template #actionSlot="scope">
					<el-tooltip content="提交审批" placement="bottom" effect="light">
						<el-icon class="ibt0" @click="submitProcessEv(scope.row)">
							<Promotion />
						</el-icon>
					</el-tooltip>
					<el-divider direction="vertical"></el-divider>
					<el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row)">
						<template #reference>
							<el-icon class="ibt0">
								<Delete />
							</el-icon>
						</template>
					</el-popconfirm>
				</template>
			</LeTable>
		</div>

		<LeFormConfigDialog
			v-if="visible"
			ref="dialogUserRef"
			v-model="visible"
			title="新增采购订单"
			width="600px"
			:form-data="activeData"
			:form-options="formOptions"
			@submit="submitHandler"
		/>

		<!-- 设计表单 -->
		<business-launch v-if="drawerVisible" v-model="drawerVisible" :record="record"></business-launch>
	</div>
</template>
<script lang="tsx" setup>
import BusinessLaunch from './businessLaunch.vue'
import purchaseOrder from '@/api/test/purchaseOrder'
import { progressBusinessApi } from '@/api/flow/process'
import { computed, nextTick, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import { useTablePage } from '@/hooks/useTablePage'
import { Plus, Delete } from '@element-plus/icons-vue'
const drawerVisible = ref(false)
const visible = ref(false) // 弹窗显示隐藏
const activeData = ref({})
const record = ref({})
const formsDialog = [
	{
		prop: 'title',
		label: '标题',
		itemType: 'input',
		rules: [{ required: true, message: '请输入采购订单标题', trigger: 'blur' }]
	},
	{
		prop: 'content',
		label: '内容',
		rows: '2',
		type: 'textarea',
		rules: [{ required: true, message: '请输入采购订单内容', trigger: 'blur' }]
	}
]
// 新增的表单 和 编辑的表单
const formOptions = computed(() => {
	return {
		forms: formsDialog,
		labelWidth: 120,
		span: 30,
		showResetBtn: true,
		formConfig: {
			showCancelBtn: true,
			submitLoading: false
		}
	}
})
const groupFilterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

// 表格搜索条件
const forms = ref([
	{
		prop: 'keyword',
		label: '采购单名称：',
		itemType: 'input',
		placeholder: '请输入采购单名称'
	}
])

// table列表数据请求
const queryList = async () => {
	const { options, searchParams } = tableOpts
	options.loading = true
	try {
		const { records: list, total } = await purchaseOrder.postPageApi(searchParams)
		tableOpts.total = total
		tableOpts.list = list
	} catch {
		console.log('获取列表数据失败')
		tableOpts.total = 0
		tableOpts.list = []
		options.loading = false // 更改加载中的 loading值
	} finally {
		options.loading = false
	}
}

// table 参数
const columns = [
	{
		prop: 'title',
		label: '标题',
		minWidth: 80
	},
	{
		prop: 'content',
		label: '内容',
		minWidth: 100
	},
	{
		prop: 'status',
		label: '状态',
		minWidth: 50,
		slots: {
			default: 'statusSlot'
		}
	},
	{
		prop: 'flwComment',
		label: '审批内容',
		minWidth: 100
	},
	{
		prop: 'createBy',
		label: '创建人',
		minWidth: 100
	},
	{
		prop: 'createTime',
		label: '创建时间',
		minWidth: 126
	},
	{
		prop: 'action',
		label: '操作',
		width: 100,
		fixed: 'right',
		slots: {
			default: 'actionSlot'
		}
	}
]

const { searchData, tableOpts, checkedColumns, activeColumns, curSelectionRows, updateParams } = useTablePage(
	{
		options: {
			showIndex: false
		},
		// 需要展示的列
		columns,
		// 控制列配置
		columnsConfig: {
			columns
		}
	},
	{
		queryList,
		fetchImmediate: false
	}
)

// 删除
const deleteItem = async ids => {
	// try {
	await purchaseOrder.postDeleteApi(ids)
	ElMessage.error(`删除成功~`)
	updateParams()
	// } catch (e) {
	// 	console.log('删除失败')
	// 	ElMessage.error(`删除失败~`)
	// }
}

// 单个删除
const table_del = row => {
	deleteItem([row.id])
}

// 发起审批
const submitProcessEv = async row => {
	const res = await progressBusinessApi()
	// const res1 = {
	// 	processId: '1808038047693168642',
	// 	processKey: 'qj',
	// 	processName: '请假申请',
	// 	processIcon: 'approval',
	// 	remark: '请假申请 V2',
	// 	categoryId: '1778232603034517506',
	// 	useScope: 0,
	// 	modelContent:
	// 		'{"name":"请假申请","key":"qj","instanceUrl":null,"nodeConfig":{"nodeName":"发起人","nodeKey":"flk1719904834757","callProcess":null,"actionUrl":null,"type":0,"setType":null,"nodeAssigneeList":[],"examineLevel":null,"directorLevel":null,"selectMode":null,"term":null,"termMode":null,"examineMode":null,"directorMode":null,"typeOfApprove":null,"passWeight":null,"conditionNodes":null,"remind":null,"allowSelection":null,"allowTransfer":null,"allowAppendNode":null,"allowRollback":null,"approveSelf":null,"extendConfig":null,"childNode":{"nodeName":"抄送人","nodeKey":"flk1719904831597","callProcess":null,"actionUrl":null,"type":2,"setType":null,"nodeAssigneeList":[],"examineLevel":null,"directorLevel":null,"selectMode":null,"term":null,"termMode":null,"examineMode":null,"directorMode":null,"typeOfApprove":null,"passWeight":null,"conditionNodes":null,"remind":null,"allowSelection":true,"allowTransfer":null,"allowAppendNode":null,"allowRollback":null,"approveSelf":null,"extendConfig":null,"childNode":{"nodeName":"条件路由","nodeKey":"flk1718359030676","callProcess":null,"actionUrl":null,"type":4,"setType":null,"nodeAssigneeList":null,"examineLevel":null,"directorLevel":null,"selectMode":null,"term":null,"termMode":null,"examineMode":null,"directorMode":null,"typeOfApprove":null,"passWeight":null,"conditionNodes":[{"nodeName":"条件1","nodeKey":"flk17183590306761","type":3,"priorityLevel":1,"conditionList":[[{"label":"a","field":"a","operator":"==","value":"1"}]],"childNode":{"nodeName":"延时处理","nodeKey":"flk1718359047245","callProcess":null,"actionUrl":null,"type":6,"setType":null,"nodeAssigneeList":null,"examineLevel":null,"directorLevel":null,"selectMode":null,"term":null,"termMode":null,"examineMode":null,"directorMode":null,"typeOfApprove":null,"passWeight":null,"conditionNodes":null,"remind":null,"allowSelection":null,"allowTransfer":null,"allowAppendNode":null,"allowRollback":null,"approveSelf":null,"extendConfig":{"time":"1:m"},"childNode":null,"parentNode":null,"parallelNodes":null,"delayType":null}},{"nodeName":"条件2","nodeKey":"flk17183590306762","type":3,"priorityLevel":2,"conditionList":[],"childNode":null}],"remind":null,"allowSelection":null,"allowTransfer":null,"allowAppendNode":null,"allowRollback":null,"approveSelf":null,"extendConfig":null,"childNode":{"nodeName":"审核人","nodeKey":"flk1716338897514","callProcess":null,"actionUrl":null,"type":1,"setType":3,"nodeAssigneeList":[{"tenantId":null,"id":"1492884198322536450","name":"财务总监","weight":null}],"examineLevel":1,"directorLevel":1,"selectMode":1,"term":0,"termMode":1,"examineMode":1,"directorMode":0,"typeOfApprove":1,"passWeight":null,"conditionNodes":null,"remind":false,"allowSelection":null,"allowTransfer":null,"allowAppendNode":null,"allowRollback":null,"approveSelf":0,"extendConfig":{"formConfig":[{"label":"人员","id":1716338743519,"opera":"1"},{"label":"请假类型","id":1716338807257,"opera":"1"},{"label":"日期","id":1716338768612,"opera":"1"},{"label":"原因","id":1716338745581,"opera":"1"}]},"childNode":null,"parentNode":null,"parallelNodes":null,"delayType":null},"parentNode":null,"parallelNodes":null,"delayType":null},"parentNode":null,"parallelNodes":null,"delayType":null},"parentNode":null,"parallelNodes":null,"delayType":null}}',
	// 	processForm:
	// 		'{"formStructure":{"list":[{"type":"inline","columns":[1716338743519],"style":{},"id":1716338743519,"key":"inline1716338743519"},{"type":"inline","columns":[1716338807257]},{"type":"inline","columns":[1716338768612]},{"type":"inline","columns":[1716338745581]}],"config":{"isSync":true,"pc":{"size":"default","labelPosition":"left","completeButton":{"text":"提交","color":"","backgroundColor":""}},"mobile":{"labelPosition":"left","completeButton":{"text":"提交","color":"","backgroundColor":""}}},"fields":[{"type":"select","label":"人员","icon":"employee","key":"select1716338743519","id":1716338743519,"options":{"dataKey":1716338743519,"filterable":true,"multiple":false,"defaultValue":"","placeholder":"请选择","labelWidth":100,"isShowLabel":true,"disabled":false,"clearable":true,"required":false,"renderType":2,"options":[{"value":"1778248547756670978","label":"test05"},{"value":"1778264912529981441","label":"test06"},{"value":"1778235567803465730","label":"test04"},{"value":"1778235419958444034","label":"test03"},{"value":"1778236021094481921","label":"test01"},{"value":"1778236187025342466","label":"test02"},{"value":"0","label":"admin"}]},"style":{"width":{"pc":"100%","mobile":"100%"}}},{"type":"select","label":"请假类型","icon":"dropdown0","key":"select1716338807257","id":1716338807257,"options":{"dataKey":1716338807257,"filterable":true,"multiple":false,"defaultValue":"","placeholder":"请选择","labelWidth":100,"isShowLabel":true,"disabled":false,"clearable":true,"required":false,"renderType":1},"style":{"width":{"pc":"100%","mobile":"50%"}}},{"type":"date","label":"日期","icon":"calendar","key":"date1716338768612","id":1716338768612,"options":{"isShowWordLimit":false,"clearable":true,"format":"YYYY-MM-DD","defaultValue":null,"startTime":null,"endTime":null,"placeholder":"请选择","labelWidth":100,"isShowLabel":true,"type":"date","required":false,"disabled":false},"style":{"width":{"pc":"100%","mobile":"100%"}}},{"type":"input","label":"原因","icon":"input","key":"input1716338745581","id":1716338745581,"options":{"clearable":true,"isShowWordLimit":false,"renderType":1,"disabled":false,"showPassword":false,"defaultValue":"","placeholder":"请输入","labelWidth":96,"isShowLabel":true,"required":false,"min":null,"max":null},"style":{"width":{"pc":"100%","mobile":"100%"}}}],"data":{"1716338743519":{"type":"select","list":[{"label":"Option1","value":"Zs-bVqTYdXkRjwIO3yh6L"},{"label":"Option2","value":"6ZEVueHFQmhnapsHGIzOh"},{"label":"Option3","value":"NBWpYD9GOT7mZTuSEvARr"}]},"1716338807257":{"type":"select","list":[{"label":"年","value":"0"},{"label":"病","value":"1"},{"label":"伤","value":"2"}]}},"logic":{}},"formData":{}}',
	// 	processSetting: {
	// 		allowRevocation: true,
	// 		allowRevocationDay: true,
	// 		allowUpdateDay: true,
	// 		allowDelegate: true,
	// 		allowBatchOperate: true,
	// 		secondOperatePrompt: true,
	// 		repeatOperateSkip: true
	// 	},
	// 	formTemplate: {
	// 		id: 0,
	// 		createId: 0,
	// 		createBy: 'string',
	// 		createTime: '2024-07-02T14:54:19.580Z',
	// 		updateBy: 'string',
	// 		updateTime: '2024-07-02T14:54:19.580Z',
	// 		tenantId: 'string',
	// 		formCategoryId: 0,
	// 		name: 'string',
	// 		code: 'string',
	// 		type: 0,
	// 		pcUrl: 'string',
	// 		appUrl: 'string',
	// 		content: 'string',
	// 		remark: 'string',
	// 		status: 0,
	// 		sort: 0
	// 	}
	// }
	const flag = Reflect.has(res, 'formTemplate')
	if (!flag) return
	if (res.formTemplate.type) {
		// vue自定义
	} else {
		record.value = { ...res, rowId: row.id}
		drawerVisible.value = true
	}
}

//批量删除
const batch_del = () => {
	const ids = curSelectionRows.value.map(item => item.id) // 多选数据
	ElMessageBox.confirm('是否删除选中数据？', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'error',
		buttonSize: 'default'
	}).then(() => {
		deleteItem(ids)
	})
}

// 弹窗事件
const submitHandler = async params => {
	formOptions.value.formConfig.submitLoading = true
	try {
		params.status = params.status ? 1 : 0
		params.id = null
		await purchaseOrder.postAddOrEditSaveApi(params)
		ElMessage.success(`新增成功~`)
		visible.value = false
		updateParams()
		formOptions.value.formConfig.submitLoading = false
	} catch (e) {
		console.log(e)
		formOptions.value.formConfig.submitLoading = false
	}
}

const addHandler = () => {
	activeData.value = {}
	visible.value = true
}

nextTick(() => {
	queryList()
})

watch(groupFilterText, val => {
	treeRef.value!.filter(val)
})
</script>
