<!-- @Author: Antigravity -->
<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="search">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="85px">
                    <el-form-item label="用户名" prop="userName">
                        <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>

        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" :data="customerList" border @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="头像" align="center" width="80">
                    <template #default="scope">
                        <el-avatar :size="36" :src="scope.row.avatarUrl" icon="UserFilled" />
                    </template>
                </el-table-column>
                <el-table-column label="用户名" align="center" prop="userName" />
                <el-table-column label="手机号" align="center" prop="phone" />
                <el-table-column label="注册时间" align="center" prop="createTime" width="160" />
                <el-table-column label="授权客户名称" align="center" prop="authClientName" :show-overflow-tooltip="true" />
                <el-table-column label="授权客户类型" align="center" prop="authClientClass" width="120" />
                <el-table-column label="授权加入时间" align="center" prop="authClientEnterDate" width="160" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
                    <template #default="scope">
                        <el-button v-hasPermi="['customer:customer:auth']" link type="success" icon="User"
                            @click="handleAuth(scope.row)">授权</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                :total="total" @pagination="getList" />
        </el-card>

        <!-- 授权客户对话框 -->
        <el-dialog v-model="authDialog.visible" title="授权客户" width="900px" append-to-body>
            <el-form :model="erpQueryParams" ref="erpQueryFormRef" :inline="true" label-width="68px">
                <el-form-item label="客户名称" prop="name">
                    <el-input v-model="erpQueryParams.name" placeholder="请输入客户名称" clearable style="width: 240px"
                        @keyup.enter="getErpList" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="getErpList">搜索</el-button>
                    <el-button icon="Refresh" @click="resetErpQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="erpLoading" :data="erpList" highlight-current-row
                @current-change="handleErpCurrentChange">
                <el-table-column label="代码" align="center" prop="num" width="100"
                    :formatter="(row: ErpClientVO) => row.num || '-'" />
                <el-table-column label="名称" align="left" prop="name" min-width="180" :show-overflow-tooltip="true"
                    :formatter="(row: ErpClientVO) => row.name || '-'" />
                <el-table-column label="客户类型" align="center" prop="class" width="100"
                    :formatter="(row: ErpClientVO) => row.class || '-'" />
                <el-table-column label="加入名称" align="center" prop="enterName" width="100"
                    :formatter="(row: ErpClientVO) => row.enterName || '-'" />
                <el-table-column label="加入时间" align="center" prop="enterDate" width="170"
                    :formatter="(row: ErpClientVO) => row.enterDate || '-'" />
            </el-table>
            <pagination v-show="erpTotal > 0" v-model:page="erpQueryParams.pageNum"
                v-model:limit="erpQueryParams.pageSize" :total="erpTotal" layout="total, prev, pager, next"
                @pagination="getErpList" />
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" icon="Check" @click="confirmAuth">确 定</el-button>
                    <el-button icon="Close" @click="authDialog.visible = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Customer" lang="ts">
import { listCustomer, getCustomer, authCustomer } from '@/api/system/customer';
import { CustomerVO, CustomerQuery, CustomerForm } from '@/api/system/customer/types';
import { listErpClient } from '@/api/erp/client';
import { ErpClientVO, ErpClientQuery } from '@/api/erp/client/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const customerList = ref<CustomerVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

// 授权客户对话框相关
const authDialog = reactive({
    visible: false,
    customerId: undefined as string | number | undefined
});
const erpLoading = ref(false);
const erpList = ref<ErpClientVO[]>([]);
const erpTotal = ref(0);
const erpQueryParams = reactive<ErpClientQuery>({
    pageNum: 1,
    pageSize: 10,
    name: undefined
});
const selectedErpClient = ref<ErpClientVO | null>(null);
const erpQueryFormRef = ref<ElFormInstance>();

const data = reactive<PageData<CustomerForm, CustomerQuery>>({
    form: {} as any,
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phone: undefined,
        wechatOpenid: undefined
    },
    rules: {}
});

const { queryParams } = toRefs(data);

/** 查询客户列表 */
const getList = async () => {
    loading.value = true;
    const res = await listCustomer(queryParams.value);
    customerList.value = res.rows;
    total.value = res.total;
    loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CustomerVO[]) => {
    ids.value = selection.map((item) => item.id);
};

/** 授权客户按钮操作 */
const handleAuth = (row: CustomerVO) => {
    authDialog.customerId = row.id;
    authDialog.visible = true;
    selectedErpClient.value = null;
    resetErpQuery();
};

/** 获取ERP客户列表 */
const getErpList = async () => {
    erpLoading.value = true;
    const res = await listErpClient(erpQueryParams);
    erpList.value = res.rows;
    erpTotal.value = res.total;
    erpLoading.value = false;
};

/** 重置ERP查询 */
const resetErpQuery = () => {
    erpQueryFormRef.value?.resetFields();
    erpQueryParams.pageNum = 1;
    getErpList();
};

/** ERP客户行选中 */
const handleErpCurrentChange = (val: ErpClientVO | null) => {
    selectedErpClient.value = val;
};

/** 确认授权 */
const confirmAuth = async () => {
    if (!selectedErpClient.value) {
        proxy?.$modal.msgError('请选择一个ERP客户');
        return;
    }
    buttonLoading.value = true;
    try {
        await authCustomer(authDialog.customerId!, selectedErpClient.value.rowId);
        proxy?.$modal.msgSuccess('授权成功');
        authDialog.visible = false;
        getList();
    } finally {
        buttonLoading.value = false;
    }
};

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

<style scoped>
/** @Author: Antigravity - 优化弹窗分页居中 */
:deep(.el-dialog .pagination-container) {
    display: flex !important;
    justify-content: center !important;
    background-color: transparent !important;
    padding: 20px 0 10px 0 !important;
    margin-top: 0 !important;
}
</style>
