<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>
			<!--  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 plain :icon="Plus" type="primary" @click="addHandler">新增</el-button>
					<el-button plain :icon="Delete" :disabled="curSelectionRows.length === 0" type="danger" @click="batch_del">删除</el-button>
					<el-link type="danger" :underline="false" class="ml-2">演示关联业务审批逻辑，对应 业务流程KEY为 purchaseOrder</el-link>
				</template>

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

				<template #actionSlot="{ row }">
					<div v-if="row.status === 0" class="flex flex-align-pack-center">
						<el-tooltip effect="dark" content="发起审批" placement="top">
							<LeIcon class="text-lg text-icon-color cursor-pointer" icon-class="icon-processInfo-navigation" @click="submitProcessEv(row)" />
						</el-tooltip>

						<LeIcon class="text-lg ml-2 text-rose-700 cursor-pointer" icon-class="icon-processInfo-iconoir--trash" @click="table_del(row)" />
					</div>
				</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" @refresh="refreshEv"></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: 'title',
		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,
		align: 'center',
		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 => {
	ElMessageBox.confirm(`确认删除「${row.title}」这条数据？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'error'
	}).then(async () => {
		deleteItem([row.id])
	})
}

// 发起审批
const submitProcessEv = async row => {
	try {
		const res = await progressBusinessApi()
		record.value = { ...res, rowId: row.id }
		drawerVisible.value = true
	} catch (e) {
		console.log(e)
	}
}

//批量删除
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>
