<template>
    <ele-page flex-table>
        <page-search @search="reload" />

        <common-table ref="pageRef" :pageConfig="pageConfig" :columns="columns">
            <template #toolbar>
                <el-button
                    type="success"
                    plain
                    v-permission="'customer:list:export'"
                    @click="handleExportExcel"
                    :icon="DownloadOutlined"
                >
                    导出EXCEL
                </el-button>
            </template>

            <template #nickName="{ row }">
                <div class="flex flex-col items-center">
                    <el-avatar :src="row.imgPath" />
                    <ele-text class="mt-1">{{ row.nickName }}</ele-text>
                </div>
            </template>
            <template #status="{ row }">
                <dict-data
                    code="user_info_status"
                    type="tag"
                    :model-value="row.status"
                />
            </template>

            <template #action="{ row }">
                <div>
                    <el-button
                        type="success"
                        link
                        v-permission="'customer:list:detail'"
                        @click="handleDetail(row)"
                    >
                        [用户详情]
                    </el-button>
                    <el-button
                        type="warning"
                        link
                        v-permission="'customer:list:userTag'"
                        @click="handleBindTag(row)"
                    >
                        [用户标签]
                    </el-button>
                    <el-button
                        type="warning"
                        link
                        v-permission="'customer:list:accountDetail'"
                        @click="handleDetail(row, 'accountChange')"
                    >
                        [账户明细]
                    </el-button>
                    <el-button
                        type="danger"
                        link
                        v-permission="'customer:list:reduceUserAccount'"
                        @click="handleReduceAccount(row)"
                    >
                        [扣减余额]
                    </el-button>
                    <el-button
                        type="success"
                        link
                        v-permission="'customer:list:blacklistHistory'"
                        @click="handleBlacklistHistory(row)"
                    >
                        [拉黑历史]
                    </el-button>
                    <el-button
                        v-if="row.status == 1"
                        type="danger"
                        link
                        v-permission="'customer:list:blacklist'"
                        @click="handleAddBlacklist(row)"
                    >
                        [加入黑名单]
                    </el-button>
                    <el-button
                        v-else
                        type="danger"
                        link
                        v-permission="'customer:list:blacklist'"
                        @click="handleRemoveBlacklist(row)"
                    >
                        [移除黑名单]
                    </el-button>
                </div>
            </template>
        </common-table>

        <blacklist-history ref="historyRef" />
        <customer-detail ref="detailRef" />
        <user-bind-tag ref="tagRef" />
    </ele-page>
</template>

<script setup>
    import { ref, reactive } from 'vue';
    import { ElMessageBox } from 'element-plus/es';
    import { EleMessage } from 'ele-admin-plus/es';
    import { DownloadOutlined } from '@/components/icons';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import pageSearch from './components/page-search.vue';
    import blacklistHistory from '@/views/customer/list/components/blacklist-history.vue';
    import customerDetail from '@/views/customer/list/components/customer-detail.vue';
    import userBindTag from '@/views/recycleOrder/components/user-bind-tag.vue';
    import request from '@/utils/request';

    defineOptions({ name: 'CustomerList' });

    /** 表格列配置 */
    const columns = ref([
        {
            label: '用户昵称',
            prop: 'nickName',
            align: 'center',
            slot: 'nickName'
        },
        { label: '用户ID', prop: 'id', align: 'center' },
        { label: '用户OpenId', prop: 'openId', align: 'center' },
        { label: '手机号', prop: 'mobile', align: 'center' },
        { label: '用户类型', prop: 'platName', align: 'center' },
        { label: '用户标签', prop: 'userTagStr', align: 'center' },
        { label: '状态', prop: 'statusName', align: 'center', slot: 'status' },
        { label: '创建时间', prop: 'createTime', align: 'center', width: 160 },
        {
            columnKey: 'action',
            label: '操作',
            width: 200,
            align: 'center',
            slot: 'action'
        }
    ]);

    /** 页面组件实例 */
    const pageRef = ref(null);

    const pageConfig = reactive({
        pageUrl: '/user/userInfo/pagelist',
        exportUrl: '/user/userInfo/export',
        fileName: '客户列表',
        cacheKey: 'customerListTable'
    });

    //刷新表格
    function reload(where) {
        pageRef.value?.reload(where);
    }

    //批量删除
    function handleBatchDelete(row) {
        let selections = row ? [row] : pageRef.value?.getSelections();
        let ids = selections.map((item) => item.id).join(',');
        let url = `/baseinfo/schoolInfo/removeById/${ids}`;
        pageRef.value?.operatBatch({
            title: '确认删除？',
            method: 'post',
            url,
            row
        });
    }
    //导出excel
    function handleExportExcel() {
        pageRef.value?.exportData('用户列表');
    }

    //加入黑名单
    function handleAddBlacklist(row) {
        ElMessageBox.confirm('确认加入黑名单？', '提示', {
            confirmButtonText: '确定',
            canceledButtonText: '关闭',
            showInput: true,
            inputPlaceholder: '请输入拉黑原因'
        }).then(({ value }) => {
            request
                .post('/user/black/add', { userId: row.id, reason: value })
                .then((res) => {
                    if (res.data.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '操作成功'
                        });
                        reload();
                    } else {
                        ElMessage({
                            type: 'error',
                            message: res.data.msg
                        });
                    }
                });
        });
    }
    //移除黑名单
    function handleRemoveBlacklist(row) {
        pageRef.value?.messageBoxConfirm({
            message: '确认移出黑名单？',
            fetch: () => request.post('/user/black/delete', { userId: row.id })
        });
    }

    //扣减余额
    function handleReduceAccount(row) {
        ElMessageBox.prompt(
            `请输入用户"${row.nickName}"(ID: ${row.id})的扣减金额`,
            '扣减余额',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPlaceholder: '请输入扣减金额',
                inputPattern: /^(?!0+(\.0+)?$)([1-9]\d*|0)(\.\d{1,2})?$/,
                inputErrorMessage: '金额必须大于0，且最多两位小数（例如：1.23 或 0.5）',
                draggable: true
            }
        ).then(({ value }) => {
            request
                .post('/user/userAccountInfo/reduceUserAccount', {
                    userId: row.id,
                    reduceMoney: Number(value).toFixed(2)
                })
                .then((res) => {
                    if (res.data.code == 200) {
                        EleMessage.success('操作成功');
                        reload();
                    } else {
                        EleMessage.error(res.data.msg);
                    }
                });
        });
    }

    //编辑页面
    const editRef = ref(null);
    function handleUpdate(row) {
        editRef.value?.handleOpen(row);
    }
    //详情页面
    const detailRef = ref(null);
    function handleDetail(row, type) {
        detailRef.value?.handleOpen(row, type);
    }

    //拉黑历史
    const historyRef = ref(null);
    function handleBlacklistHistory(row) {
        historyRef.value?.handleOpen(row);
    }

    //用户标签
    const tagRef = ref(null);
    function handleBindTag(row) {
        row.userId = row.id;
        tagRef.value?.handleOpen(row);
    }
</script>
