<template>
    <div>
        <base-search :formItemList="formItemList" @search="searchFrom" ref="baseSearchRef"> </base-search>
        <div style="display: flex; padding: 10px; background: #fff; margin-bottom: 10px; gap: 10px">
            <el-button type="primary" @click="showAddDialog(null)">新增用户</el-button>
            <el-button type="success" @click="handleImportClick">导入数据</el-button>
            <input ref="fileInputRef" type="file" accept=".xlsx,.xls" style="display: none" @change="handleFileChange" />
        </div>
        <div class="main-container">
            <el-table :data="data.rows" border v-loading="data.dataListLoading" element-loading-text="数据加载中..." style="width: 100%">
                <el-table-column label="用户姓名" prop="name"></el-table-column>
                <el-table-column label="用户手机号" prop="mobile"> </el-table-column>
                <el-table-column label="用户类型" prop="type">
                    <template #default="scope"> {{ getRoleName(scope.row.type) }} </template>
                </el-table-column>
                <el-table-column label="CBK账户" prop="cbkAccount"> 
                    <template #default="scope">
                        <template v-if="scope.row.cbkAccount">
                            <el-tooltip :content="scope.row.cbkAccount" placement="top">
                                <span style="cursor: help">****</span>
                            </el-tooltip>
                        </template>
                        <template v-else>
                            --
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="账号状态" prop="status">
                    <template #default="scope"> {{ scope.row.status == 0 ? '启用' : '禁用' }} </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark"> 
                    <template #default="scope"> {{ scope.row.remark || '--' }} </template>
                </el-table-column>
                <el-table-column label="创建人" prop="createName">
                    <template #default="scope"> {{ scope.row.createName || '--' }} </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime"></el-table-column>
                <el-table-column label="操作" width="140">
                    <template #default="scope">
                        <el-button link type="primary" @click="showAddDialog(scope.row)">编辑</el-button>
                        <!-- <el-button link type="primary" @click="delClick(scope.row)">删除</el-button> -->
                    </template>
                </el-table-column>
                <template #empty>
                    <div class="dataListOnEmpty">暂无数据</div>
                </template>
            </el-table>
            <pagination v-model:limit="form.pageSize" v-model:page="form.pageNum" :total="data.total" @pagination="getDataList" />
            <UserDialog ref="UserDialogRef" @success="getDataList" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as XLSX from 'xlsx';
import baseSearch from '@/components/common/searchCustom/index.vue';
import { userList, userStatus, userAdd, userEdit } from '@/api/userManage.js';
import UserDialog from './userDialog.vue';

const baseSearchRef = ref();
const UserDialogRef = ref();
const fileInputRef = ref();
const formItemList = reactive([
    {
        label: '用户姓名',
        param: 'username',
        type: 'input',
        placeholder: '请输入用户名',
        span: 7,
        labelWidth: 100,
    },
    {
        label: '精确姓名',
        param: 'usernameExact',
        type: 'select',
        selectOptions: [
            { value: true, text: '是' },
            { value: false, text: '否' },
        ],
        span: 4,
        labelWidth: 80,
    },
    {
        label: '用户手机号',
        param: 'mobile',
        type: 'input',
        placeholder: '请输入用户手机号',
        span: 7,
        labelWidth: 100,
    },
    {
        label: '精确手机号',
        param: 'mobileExact',
        type: 'select',
        selectOptions: [
            { value: true, text: '是' },
            { value: false, text: '否' },
        ],
        span: 4,
        labelWidth: 90,
    },
    {
        label: '用户类型',
        type: 'select',
        selectOptions: [
            { value: 1, text: '司机' },
            { value: 2, text: '供应商' },
            { value: 3, text: '资金方' },
            { value: 4, text: '采购商' },
        ],
        param: 'type',
        span: 7,
        labelWidth: 100,
    },
]);
const searchFrom = () => {
    form.pageNum = 1;
    getDataList();
};
const data = reactive({
    rows: [],
    total: 0,
    dataListLoading: false,
});
const form = reactive({
    pageNum: 1,
    pageSize: 10,
});
const typeOptions = {
    1: '司机',
    2: '供应商',
    3: '资金方',
    4: '采购商',
};

// 根据type获取用户类型名称
const getRoleName = (type) => {
    if (type) {
        return typeOptions[type] || `未知类型${type}`;
    }
    return '--';
};
// 列表
const getDataList = () => {
    data.dataListLoading = true;
    const params = {
        ...form,
        ...baseSearchRef.value.penetrateParams(),
    };
    userList(params)
        .then((res) => {
            data.dataListLoading = false;
            data.rows = res.data.rows;
            data.total = res.data.total;
        })
        .catch(() => {
            data.dataListLoading = false;
        });
};
// 删除
const delClick = (row) => {
    ElMessageBox.confirm('请确认是否删除该条数据？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
    })
        .then(() => {
            ElMessage({
                type: 'success',
                message: '删除成功',
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            });
        });
};
const showAddDialog = (row) => {
    if (UserDialogRef.value) {
        UserDialogRef.value.onShowDialog(row);
    }
};

// 导入数据相关
const handleImportClick = () => {
    if (fileInputRef.value) {
        fileInputRef.value.click();
    }
};

const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (!file) {
        return;
    }

    // 验证文件类型
    const fileName = file.name;
    const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
    if (fileExtension !== 'xlsx' && fileExtension !== 'xls') {
        ElMessage.error('请选择Excel文件（.xlsx或.xls格式）');
        event.target.value = '';
        return;
    }

    try {
        // 读取Excel文件
        const data = await readExcelFile(file);
        
        // 解析和转换数据
        const userDataList = parseExcelData(data);
        
        if (userDataList.length === 0) {
            ElMessage.warning('Excel文件中没有有效数据');
            event.target.value = '';
            return;
        }

        // 批量导入
        await batchImportUsers(userDataList);
        
        // 清空文件选择
        event.target.value = '';
    } catch (error) {
        console.error('导入失败:', error);
        ElMessage.error('导入失败：' + (error.message || '未知错误'));
        event.target.value = '';
    }
};

// 读取Excel文件
const readExcelFile = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                resolve(jsonData);
            } catch (error) {
                reject(new Error('Excel文件解析失败：' + error.message));
            }
        };
        reader.onerror = () => {
            reject(new Error('文件读取失败'));
        };
        reader.readAsArrayBuffer(file);
    });
};

// 解析Excel数据
const parseExcelData = (data) => {
    if (!data || data.length < 2) {
        return [];
    }

    // 第一行是表头
    const headers = data[0].map(h => String(h || '').trim());
    
    // 查找列索引
    const companyNameIndex = headers.findIndex(h => h.includes('公司昵称') || h.includes('公司名称'));
    const statusIndex = headers.findIndex(h => h.includes('合作状态'));
    const contactPersonIndex = headers.findIndex(h => h.includes('对接人'));
    const contactInfoIndex = headers.findIndex(h => h.includes('联系方式'));

    if (companyNameIndex === -1) {
        throw new Error('未找到"公司昵称"列');
    }
    if (statusIndex === -1) {
        throw new Error('未找到"合作状态"列');
    }

    const userDataList = [];
    
    // 从第二行开始读取数据
    for (let i = 1; i < data.length; i++) {
        const row = data[i];
        if (!row || row.length === 0) {
            continue;
        }

        const companyName = String(row[companyNameIndex] || '').trim();
        const status = String(row[statusIndex] || '').trim();
        const contactPerson = contactPersonIndex >= 0 ? String(row[contactPersonIndex] || '').trim() : '';
        const contactInfo = contactInfoIndex >= 0 ? String(row[contactInfoIndex] || '').trim() : '';

        // 跳过空行
        if (!companyName && !status) {
            continue;
        }

        // 构建用户姓名：公司昵称/对接人
        let username = companyName;
        if (contactPerson) {
            username = `${companyName}/${contactPerson}`;
        }

        // 映射用户类型：采购商=4，供应商=2
        let type = null;
        if (status === '采购商') {
            type = 4;
        } else if (status === '供应商') {
            type = 2;
        } else if (status) {
            // 如果合作状态不是采购商或供应商，跳过该行
            console.warn(`第${i + 1}行：未知的合作状态"${status}"，已跳过`);
            continue;
        }

        // 如果用户类型无法确定，跳过
        if (type === null) {
            console.warn(`第${i + 1}行：无法确定用户类型，已跳过`);
            continue;
        }

        userDataList.push({
            username,
            mobile: contactInfo || null, // 联系方式作为手机号，如果为空则为null
            type,
            cbkAccount: '', // CBK账号为空
            status: 0, // 账号状态：启用
            remark: '', // 备注为空
        });
    }

    return userDataList;
};

// 批量导入用户
const batchImportUsers = async (userDataList) => {
    const total = userDataList.length;
    let successCount = 0;
    let failCount = 0;
    const failMessages = [];

    ElMessage.info(`开始导入，共${total}条数据`);

    for (let i = 0; i < userDataList.length; i++) {
        const userData = userDataList[i];
        
        try {
            // 如果手机号不为空，先检查是否存在
            let existingUser = null;
            if (userData.mobile) {
                // 查询是否存在该手机号的用户
                const queryResult = await userList({
                    pageNum: 1,
                    pageSize: 1,
                    mobile: userData.mobile,
                    mobileExact: true,
                });
                
                if (queryResult.data && queryResult.data.rows && queryResult.data.rows.length > 0) {
                    existingUser = queryResult.data.rows[0];
                }
            }

            if (existingUser) {
                // 如果存在，则更新
                await userEdit({
                    id: existingUser.id,
                    ...userData,
                });
                successCount++;
            } else {
                // 如果不存在，则新增
                await userAdd(userData);
                successCount++;
            }
        } catch (error) {
            failCount++;
            const errorMsg = error.response?.data?.msg || error.message || '未知错误';
            failMessages.push(`第${i + 1}行（${userData.username}）：${errorMsg}`);
            console.error(`导入第${i + 1}行失败:`, error);
        }
    }

    // 显示导入结果
    if (failCount === 0) {
        ElMessage.success(`导入成功！共导入${successCount}条数据`);
    } else {
        ElMessage.warning(`导入完成：成功${successCount}条，失败${failCount}条`);
        if (failMessages.length > 0) {
            console.error('导入失败详情:', failMessages);
            // 可以在这里显示详细的错误信息，比如使用MessageBox
            ElMessageBox.alert(
                failMessages.slice(0, 10).join('\n') + (failMessages.length > 10 ? `\n...还有${failMessages.length - 10}条错误` : ''),
                '导入失败详情',
                { type: 'error' }
            );
        }
    }

    // 刷新列表
    getDataList();
};

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

<style lang="less" scoped></style>
