<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { columns } from '@/views/financial/budget-saving/saving-goal/utils/columns';
import PureTableBar from '@/components/TableBar/src/bar';
import AddFill from '@iconify-icons/ri/add-circle-line';
import PureTable from '@pureadmin/table';
import { deleteIds, onAdd, onDelete, onDeleteBatch, onSearch, onUpdate } from '@/views/financial/budget-saving/saving-goal/utils/hooks';
import Delete from '@iconify-icons/ep/delete';
import EditPen from '@iconify-icons/ep/edit-pen';
import Refresh from '@iconify-icons/ep/refresh';
import { $t } from '@/plugins/i18n';
import { useSavingGoalStore } from '@/store/financial/savingGoal';
import { useRenderIcon } from '@/components/CommonIcon/src/hooks';
import { FormInstance } from 'element-plus';
import { useAdminUserStore } from '@/store/system/adminUser';
import LoadingSvg from '@/assets/svg/loading.svg';
import { budget } from '@/enums/bill/budget';
import { selectUserinfo } from '@/components/Table/Userinfo/columns';
import { savingGoal } from '@/enums/bill/savingGoal';
import { hasAuth } from '@/router/utils';
import { auth } from '@/views/financial/budget-saving/saving-goal/utils/auth';

const tableRef = ref();
const formRef = ref();
// 用户信息列表
const userDataList = ref();
// 搜索用户加载
const loading = ref(false);
const adminUserStore = useAdminUserStore();
const savingGoalStore = useSavingGoalStore();

/** 当前页改变时 */
const onCurrentPageChange = async (value: number) => {
	savingGoalStore.pagination.currentPage = value;
	await onSearch();
};

/** 当分页发生变化 */
const onPageSizeChange = async (value: number) => {
	savingGoalStore.pagination.pageSize = value;
	await onSearch();
};

/** 选择多行 */
const onSelectionChange = (rows: Array<any>) => {
	deleteIds.value = rows.map((row: any) => row.id);
};

/** 搜索 */
const onSearchUserinfo = async (keyword: string) => {
	loading.value = true;
	userDataList.value = await adminUserStore.queryUser({ keyword });
	loading.value = false;
};

/** 重置表单 */
const resetForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	savingGoalStore.form.duration = undefined;
	savingGoalStore.form.startDuration = undefined;
	savingGoalStore.form.endDuration = undefined;
	await onSearch();
};

onMounted(() => {
	onSearch();
});
</script>

<template>
	<div class="main">
		<el-form ref="formRef" :inline="true" :model="savingGoalStore.form" class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto">
			<!-- 绑定的用户id -->
			<el-form-item :label="$t('user')" prop="userId">
				<el-select
					v-model="savingGoalStore.form.userId"
					:loading="loading"
					:placeholder="$t('user')"
					:remote-method="onSearchUserinfo"
					class="!w-[180px]"
					clearable
					filterable
					remote
					remote-show-suffix
				>
					<el-option v-for="item in userDataList" :key="item.id" :label="item.username" :value="item.id" />
					<template #loading>
						<el-icon class="is-loading">
							<LoadingSvg />
						</el-icon>
					</template>
				</el-select>
			</el-form-item>

			<!-- 完成状态 -->
			<el-form-item :label="$t('statusType')" prop="statusType">
				<el-select
					v-model="savingGoalStore.form.statusType"
					:placeholder="$t('statusType')"
					class="!w-[180px]"
					clearable
					filterable
					remote
					remote-show-suffix
				>
					<el-option v-for="item in savingGoal" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>

			<!-- 储值目标名称 -->
			<el-form-item :label="$t('savingGoalName')" prop="savingGoalName">
				<el-input v-model="savingGoalStore.form.savingGoalName" :placeholder="`${$t('input')}${$t('savingGoalName')}`" class="!w-[180px]" clearable />
			</el-form-item>

			<!-- 目标金额 -->
			<el-form-item :label="$t('amount')" prop="amount">
				<el-input v-model="savingGoalStore.form.amount" :placeholder="`${$t('input')}${$t('amount')}`" class="!w-[180px]" clearable />
			</el-form-item>

			<!-- 已存入金额 -->
			<el-form-item :label="$t('amountDeposited')" prop="amountDeposited">
				<el-input v-model="savingGoalStore.form.amountDeposited" :placeholder="`${$t('input')}${$t('amountDeposited')}`" class="!w-[180px]" clearable />
			</el-form-item>

			<!-- 目标时长 -->
			<el-form-item :label="$t('duration')" prop="duration">
				<el-date-picker
					v-model="savingGoalStore.form.duration"
					:end-placeholder="$t('endTime')"
					:start-placeholder="$t('startTime')"
					class="!w-[210px]"
					time-format="YYYY-MM-DD"
					type="datetimerange"
					value-format="YYYY-MM-DD"
				/>
			</el-form-item>

			<!-- 搜索和重置 -->
			<el-form-item>
				<el-button
					v-if="hasAuth(auth.search)"
					:icon="useRenderIcon('ri:search-line')"
					:loading="savingGoalStore.loading"
					type="primary"
					@click="onSearch"
				>
					{{ $t('search') }}
				</el-button>
				<el-button v-if="hasAuth(auth.search)" :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
					{{ $t('buttons.reset') }}
				</el-button>
			</el-form-item>
		</el-form>

		<PureTableBar :columns="columns" :title="$t('savingGoal')" @fullscreen="tableRef.setAdaptive()" @refresh="onSearch">
			<template #buttons>
				<el-button v-if="hasAuth(auth.add)" :icon="useRenderIcon(AddFill)" type="primary" @click="onAdd">
					{{ $t('addNew') }}
				</el-button>

				<!-- 批量删除按钮 -->
				<el-button v-if="hasAuth(auth.deleted)" v-show="deleteIds.length > 0" :icon="useRenderIcon(Delete)" type="danger" @click="onDeleteBatch">
					{{ $t('delete_batches') }}
				</el-button>
			</template>

			<template v-slot="{ size, dynamicColumns }">
				<pure-table
					ref="tableRef"
					:adaptiveConfig="{ offsetBottom: 96 }"
					:columns="dynamicColumns"
					:data="savingGoalStore.datalist"
					:header-cell-style="{ background: 'var(--el-fill-color-light)', color: 'var(--el-text-color-primary)' }"
					:loading="savingGoalStore.loading"
					:pagination="savingGoalStore.pagination"
					:size="size"
					adaptive
					align-whole="center"
					border
					highlight-current-row
					row-key="id"
					showOverflowTooltip
					table-layout="auto"
					@page-size-change="onPageSizeChange"
					@selection-change="onSelectionChange"
					@page-current-change="onCurrentPageChange"
				>
					<template #statusType="{ row }">
						<component :is="budget.find(item => item.value === row.statusType).el" />
					</template>

					<template #username="{ row }">
						<el-button v-show="row.username" link type="primary" @click="selectUserinfo(row.userId)">
							{{ row.username }}
						</el-button>
					</template>

					<template #createUser="{ row }">
						<el-button v-show="row.createUser" link type="primary" @click="selectUserinfo(row.createUser)">
							{{ row.createUsername }}
						</el-button>
					</template>

					<template #updateUser="{ row }">
						<el-button v-show="row.updateUser" link type="primary" @click="selectUserinfo(row.updateUser)">
							{{ row.updateUsername }}
						</el-button>
					</template>

					<template #operation="{ row }">
						<el-button
							v-if="hasAuth(auth.update)"
							:icon="useRenderIcon(EditPen)"
							:size="size"
							class="reset-margin"
							link
							type="primary"
							@click="onUpdate(row)"
						>
							{{ $t('modify') }}
						</el-button>
						<el-popconfirm v-if="hasAuth(auth.deleted)" :title="`${$t('delete')}?`" @confirm="onDelete(row)">
							<template #reference>
								<el-button :icon="useRenderIcon(Delete)" :size="size" class="reset-margin" link type="primary">
									{{ $t('delete') }}
								</el-button>
							</template>
						</el-popconfirm>
					</template>
				</pure-table>
			</template>
		</PureTableBar>
	</div>
</template>
