<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row class="ml10" v-show="showSearch">
				<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
					<el-form-item :label="$t('agentUser.agentName')" prop="query">
						<el-input :placeholder="$t('agentUser.searchAgentAccount')" style="max-width: 180px" v-model="state.queryForm.query" />
					</el-form-item>
					<el-form-item>
						<el-button @click="getDataList" icon="search" type="primary">
							{{ $t('common.queryBtn') }}
						</el-button>
						<el-button @click="resetQuery" icon="Refresh">{{ $t('common.resetBtn') }} </el-button>
					</el-form-item>
				</el-form>
			</el-row>
			<el-row>
				<div class="mb8" style="width: 100%">
					<el-button @click="formDialogRef.openDialog()" class="ml10" icon="folder-add" type="primary" v-auth="'agent_admin'">
						{{ $t('common.addBtn') }}
					</el-button>
					<right-toolbar
						@queryTable="getDataList"
						class="ml10"
						style="float: right; margin-right: 20px"
						v-model:showSearch="showSearch"
					></right-toolbar>
				</div>
			</el-row>
			<el-table
				:data="state.dataList"
				@selection-change="handleSelectionChange"
				@sort-change="sortChangeHandle"
				style="width: 100%"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
			>
				<el-table-column align="center" type="selection" width="40" />
				<el-table-column :label="$t('agentUser.agentId')" prop="userId" show-overflow-tooltip />
				<el-table-column :label="$t('agentUser.agentName')" prop="agentName" show-overflow-tooltip />
				<el-table-column label="可用余额" prop="totalAmount" show-overflow-tooltip>
					<template #default="scope">
						{{ scope.row.availableAmount ? `¥${scope.row.availableAmount.toFixed(2)}` : '¥0.00' }}
					</template>
				</el-table-column>
				<el-table-column label="冻结金额" prop="freezeAmount" show-overflow-tooltip>
					<template #default="scope">
						{{ scope.row.freezeAmount ? `¥${scope.row.freezeAmount.toFixed(2)}` : '¥0.00' }}
					</template>
				</el-table-column>
				<el-table-column label="总提现金额" prop="withdrawnAmount" show-overflow-tooltip>
					<template #default="scope">
						{{ scope.row.withdrawnAmount ? `¥${scope.row.withdrawnAmount.toFixed(2)}` : '¥0.00' }}
					</template>
				</el-table-column>
				<el-table-column :label="$t('agentUser.status')" prop="status" show-overflow-tooltip>
					<template #default="scope">
						<el-switch
							v-model="scope.row.status"
							:active-value="true"
							:inactive-value="false"
							@change="handleStatusChange(scope.row)"
							v-auth="'agent_admin'"
						/>
					</template>
				</el-table-column>
				<el-table-column :label="$t('agentUser.operation')" width="360">
					<template #default="scope">
						<el-button icon="View" @click="handleView(scope.row)" text type="primary" v-auth="'agent_admin'">{{ $t('agentUser.viewBtn') }}</el-button>
						<el-button icon="edit-pen" @click="formDialogRef.openDialog(scope.row.userId)" text type="primary" v-auth="'agent_admin'"
							>{{ $t('common.editBtn') }}
						</el-button>
						<el-button icon="Key" @click="handleChangePwd(scope.row)" text type="warning" v-auth="'agent_admin'">{{
							$t('agentUser.changePwdBtn')
						}}</el-button>
						<el-button icon="Setting" @click="handleAgentPayment(scope.row, 'HARVEST')" text type="success" v-auth="'agent_payment_type_query'"
							>代收
						</el-button>
						<el-button icon="Setting" @click="handleAgentPayment(scope.row, 'PAY')" text type="warning" v-auth="'agent_payment_type_query'"
							>代付
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination @current-change="currentChangeHandle" @size-change="sizeChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog @refresh="getDataList(false)" ref="formDialogRef" />

		<!-- 修改密码 -->
		<change-pwd-dialog @refresh="getDataList(false)" ref="changePwdDialogRef" />

		<!-- 代理商支付通道配置 -->
		<agent-payment-dialog ref="agentPaymentDialogRef" />
	</div>
</template>

<script lang="ts" name="systemAgentUser" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, changeStatus } from '/@/api/agent';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const ChangePwdDialog = defineAsyncComponent(() => import('./changePwd.vue'));
const AgentPaymentDialog = defineAsyncComponent(() => import('./agentPaymentDialog.vue'));

// 定义变量内容
const formDialogRef = ref();
const changePwdDialogRef = ref();
const agentPaymentDialogRef = ref();
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	descs: ['create_time'],
});

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value.resetFields();
	// 清空多选
	selectObjs.value = [];
	getDataList();
};

// 多选事件
const handleSelectionChange = (objs: { userId: string }[]) => {
	selectObjs.value = objs.map(({ userId }) => userId);
	multiple.value = !objs.length;
};

// 状态切换
const handleStatusChange = async (row: any) => {
	try {
		await changeStatus(row.userId);
		useMessage().success(t('agentUser.statusChangeSuccess'));
		getDataList(false);
	} catch (err: any) {
		useMessage().error(err.msg);
		// 恢复原状态
		row.status = !row.status;
	}
};

// 批量启用/禁用
const handleBatchChangeStatus = async () => {
	if (selectObjs.value.length === 0) {
		useMessage().warning('请选择要操作的数据');
		return;
	}

	try {
		await useMessageBox().confirm('确认要批量修改状态吗？');
		for (const id of selectObjs.value) {
			await changeStatus(id);
		}
		useMessage().success('批量操作成功');
		getDataList(false);
	} catch (err: any) {
		if (err !== 'cancel') {
			useMessage().error(err.msg || '操作失败');
		}
	}
};

// 查看详情
const handleView = (row: any) => {
	formDialogRef.value.openDialog(row.userId, true);
};

// 修改密码
const handleChangePwd = (row: any) => {
	changePwdDialogRef.value.openDialog(row.userId);
};

// 打开代理商支付通道配置
const handleAgentPayment = (row: any, type: 'PAY' | 'HARVEST') => {
	agentPaymentDialogRef.value.openDialog(row.userId, type);
};
</script>
