<!-- 客户管理-用户管理 -->
<template>
    <div class="customer-management">
        <!-- 搜索条件区 -->
        <div class="search-section">
            <a-form :model="searchForm" layout="inline">
                <a-form-item field="customerName" :label="$t('customer.customerName')">
                    <a-input v-model="searchForm.customerName" :placeholder="$t('customer.enterCustomerName')"
                        allow-clear />
                </a-form-item>
                <a-form-item field="operatorType" :label="$t('customer.operatorType')">
                    <a-select v-model="searchForm.operatorType" :placeholder="$t('customer.selectOperatorType')"
                        allow-clear style="width: 160px">
                        <a-option v-for="op in operatorTypeOptions" :key="op.value" :value="op.value">
                            {{ $t(`customer.operatorTypes.${op.value}`) }}
                        </a-option>
                    </a-select>
                </a-form-item>
                <a-form-item>
                    <a-button type="primary" @click="handleSearch">{{ $t('global.common.search') }}</a-button>
                </a-form-item>
                <a-form-item>
                    <a-button @click="resetSearch">{{ $t('global.common.reset') }}</a-button>
                </a-form-item>
            </a-form>
        </div>

        <!-- 顶部操作区 -->
        <div class="top-actions">
            <a-space>
                <a-button type="primary" @click="showNewCustomerForm">{{ $t('customer.addCustomer') }}</a-button>
                <a-button @click="handleBatchDelete">{{ $t('customer.batchDelete') }}</a-button>
            </a-space>
        </div>

        <!-- 数据表格 -->
        <a-table row-key="id" :columns="columns" :data="tableData" :pagination="pagination" :scroll="{ x: 'auto' }"
            :row-selection="{ type: 'checkbox', showCheckedAll: true }" @page-change="onPageChange">
            <template #state="{ record }">
                <a-tag :color="getStatusColor(record.state)">
                    {{ $t(`customer.status.${getStatusText(record.state)}`) }}
                </a-tag>
            </template>
            <template #operation="{ record }">
                <a-space>
                    <a-button type="text" size="small" @click="handleRecharge(record)">{{ $t('customer.recharge')
                        }}</a-button>
                    <a-button type="text" size="small" @click="handlePackageManagement(record)">{{
                        $t('customer.packageManagement') }}</a-button>
                    <a-button type="text" size="small" @click="handleEdit(record)">{{ $t('global.common.edit')
                        }}</a-button>
                </a-space>
            </template>
        </a-table>

        <!-- 新客户表单对话框 -->
        <new-customer-form v-model:visible="newCustomerFormVisible" :editMode="editMode" :editData="editData"
            :loading="loading" @submit="handleNewCustomerSubmit" />
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import { useI18n } from 'vue-i18n';
import NewCustomerForm from './NewCustomerForm.vue';
import { getCustomerList, addCustomer, getCustomer, updateCustomer } from '@/api/customer';

const { t } = useI18n();

const loading = ref(false);

const columns = computed(() => [
    { title: t('customer.id'), dataIndex: 'id' },
    { title: t('customer.customerCode'), dataIndex: 'customerCode' },
    { title: t('customer.customerName'), dataIndex: 'customerName' },
    { title: t('customer.accountNumber'), dataIndex: 'accountNumber' },
    { title: t('customer.accountBalance'), dataIndex: 'accountBalance' },
    { title: t('customer.paymentMethodName'), dataIndex: 'paymentMethod' },
    { title: t('customer.customerStatus'), slotName: 'state' },
    { title: t('customer.validPeriod'), dataIndex: 'validPeriod' },
    { title: t('customer.activeCards'), dataIndex: 'activeCards' },
    { title: t('customer.updateTime'), dataIndex: 'updateTime' },
    { title: t('global.common.operations'), slotName: 'operation', width: 250 },
]);

onMounted(() => {
    // fetchCustomerList();
});

const tableData = ref([
    {
        id: "1", customerCode: "8",
        customerName: "泰国景和",
        accountBalance: "TS001",
        paymentMethod: "预付费",
        state: "1",
        validPeriod: "2024-12-54",
        activeCards: "0/0",
        updateTime: "2024-09-20 08:05:54"
    },
    {
        id: "2", customerCode: "9",
        customerName: "泰国景和",
        accountBalance: "TS001",
        paymentMethod: "后付费",
        state: "1",
        validPeriod: "2024-12-54",
        activeCards: "0/0",
        updateTime: "2024-09-20 08:05:54"
    },
    {
        id: "3", customerCode: "10",
        customerName: "泰国景和",
        accountBalance: "TS001",
        paymentMethod: "后付费",
        state: "1",
        validPeriod: "2024-12-54",
        activeCards: "0/0",
        updateTime: "2024-09-20 08:05:54"
    },
    {
        id: "4", customerCode: "11",
        customerName: "泰国景和",
        accountBalance: "TS001",
        paymentMethod: "后付费",
        state: "1",
        validPeriod: "2024-12-54",
        activeCards: "0/0",
        updateTime: "2024-09-20 08:05:54"
    },
]);

// const pagination = reactive({
//   // total: 100,
//   current: 1,
//   pageSize: 10,
// });
const pagination = { pageSize: 10 }
const fetchCustomerList = async () => {
    try {
        const response = await getCustomerList({
            current: pagination.current,
            pageSize: pagination.pageSize,
            customerName: searchForm.customerName,
            operatorType: searchForm.operatorType,
        });
        if (response.code === 200 && response.data) {
            tableData.value = response.data.records;
            pagination.total = response.data.total;
            pagination.current = response.data.current;
            pagination.pageSize = response.data.size;
        } else {
            Message.error(response.message || 'Failed to fetch customer list');
        }
    } catch (error) {
        Message.error('Failed to fetch customer list');
        console.error(error);
    }
};

const onPageChange = (page) => {
    pagination.current = page;
    fetchCustomerList();
};

const newCustomerFormVisible = ref(false);
const editMode = ref(false);
const editData = ref(null);

const searchForm = reactive({
    customerName: '',
    operatorType: '',
});

const operatorTypeOptions = [
    { value: 'domestic', label: t('customer.operatorTypes.domestic') },
    { value: 'international', label: t('customer.operatorTypes.international') },
];

const showNewCustomerForm = () => {
    editMode.value = false;
    editData.value = null;
    newCustomerFormVisible.value = true;
};

const handleEdit = async (record) => {
    try {
        loading.value = true;
        const response = await getCustomer({ id: record.id });
        if (response.code === 200) {
            // 处理返回的数据，确保数据结构匹配表单
            const formattedData = {
                userInfo: {
                    ...response.data.userInfo,
                    password: '', // 清空密码字段
                    passwordState: true // 添加密码状态控制
                },
                customerInfo: {
                    ...response.data.customerInfo,
                    // 确保日期格式正确
                    exTime: response.data.customerInfo.exTime ? new Date(response.data.customerInfo.exTime) : null
                },
                customerProperty: {
                    ...response.data.customerProperty,
                    // 确保数值类型正确
                    amount: Number(response.data.customerProperty?.amount || 0),
                    rechargeLimit: Number(response.data.customerProperty?.rechargeLimit || 0),
                    lineOfCredit: Number(response.data.customerProperty?.lineOfCredit || 0),
                    smsUnitPrice: Number(response.data.customerProperty?.smsUnitPrice || 0),
                    iotSmsUnitPrice: Number(response.data.customerProperty?.iotSmsUnitPrice || 0),
                    paymentMethod: response.data.customerProperty?.paymentMethod || 'prepaid'
                },
                customerInvoice: {
                    ...response.data.customerInvoice,
                    // 处理文件列表
                    businessLicenseFile: response.data.customerInvoice?.businessLicenseFile ? [response.data.customerInvoice.businessLicenseFile] : [],
                    taxRegistrationFile: response.data.customerInvoice?.taxRegistrationFile ? [response.data.customerInvoice.taxRegistrationFile] : [],
                    generalTaxpayerFile: response.data.customerInvoice?.generalTaxpayerFile ? [response.data.customerInvoice.generalTaxpayerFile] : []
                },
                customerCardQualification: {
                    ...response.data.customerCardQualification,
                    // 处理图片和文件字段
                    blImg: response.data.customerCardQualification?.blImg || null,
                    legalPersonIdCardImgUp: response.data.customerCardQualification?.legalPersonIdCardImgUp || null,
                    legalPersonIdCardImgDown: response.data.customerCardQualification?.legalPersonIdCardImgDown || null,
                    iotImg: response.data.customerCardQualification?.iotImg || null,
                    contractImg: response.data.customerCardQualification?.contractImg || null,
                    commitmentImg: response.data.customerCardQualification?.commitmentImg || null,
                    customerForm: response.data.customerCardQualification?.customerForm || null,
                    phoneForm: response.data.customerCardQualification?.phoneForm || null,
                    otherFile: response.data.customerCardQualification?.otherFile || null
                },
                customerWarningParameter: {
                    ...response.data.customerWarningParameter,
                    // 确保数值类型正确
                    accountBalanceWarning: Number(response.data.customerWarningParameter?.accountBalanceWarning || 0),
                    reachWarning: Number(response.data.customerWarningParameter?.reachWarning || 0),
                    stopSending: Number(response.data.customerWarningParameter?.stopSending || 0),
                    networkDisconnection: Number(response.data.customerWarningParameter?.networkDisconnection || 0),
                    // 设置默认值
                    stopSendingAction: response.data.customerWarningParameter?.stopSendingAction || 'noRecovery',
                    networkDisconnectionAction: response.data.customerWarningParameter?.networkDisconnectionAction || 'noRecovery'
                },
                customerInterfaceParams: {
                    ...(response.data.customerInterfaceParams || {}),
                    // 设置默认值
                    smsStatusReportUrl: response.data.customerInterfaceParams?.smsStatusReportUrl || '',
                    reportIp: response.data.customerInterfaceParams?.reportIp || '',
                    deliveryPriority: response.data.customerInterfaceParams?.deliveryPriority || '',
                    dataReportUrl: response.data.customerInterfaceParams?.dataReportUrl || ''
                }
            };

            editMode.value = true;
            editData.value = formattedData;
            newCustomerFormVisible.value = true;
        } else {
            Message.error(response.message || t('customer.fetchFailed'));
        }
    } catch (error) {
        console.error('获取客户详情时发生错误:', error);
        Message.error(t('customer.fetchError'));
    } finally {
        loading.value = false;
    }
};

const handleRecharge = (record) => {
    Message.success(`为客户 ${record.customerName} 充值`);
};

const handlePackageManagement = (record) => {
    Message.success(`管理客户 ${record.customerName} 的套餐`);
};

const handleNewCustomerSubmit = async (formData) => {
    try {
        loading.value = true;
        let response;
        if (editMode.value) {
            response = await updateCustomer(formData);
        } else {
            response = await addCustomer(formData);
        }

        if (response.code === 200) {
            Message.success(editMode.value ? t('customer.updateSuccess') : t('customer.addSuccess'));
            newCustomerFormVisible.value = false;
            fetchCustomerList();
        } else {
            Message.error(response.message || (editMode.value ? t('customer.updateFailed') : t('customer.addFailed')));
        }
    } catch (error) {
        console.error(editMode.value ? '更新客户时发生错误:' : '添加客户时发生错误:', error);
        Message.error(editMode.value ? t('customer.updateError') : t('customer.addError'));
    } finally {
        loading.value = false;
    }
};

const handleSearch = () => {
    pagination.current = 1;
    fetchCustomerList();
};

const resetSearch = () => {
    Object.keys(searchForm).forEach(key => {
        searchForm[key] = '';
    });
    pagination.current = 1;
    fetchCustomerList();
};

const handleBatchDelete = () => {
    Message.warning(t('customer.batchDeleteWarning'));
};

const getStatusColor = (state) => {
    const stateColors = {
        '1': 'green',    // 正常 - 绿色
        '2': 'red',      // 禁用 - 红色
        '3': 'orange',   // 待审 - 橙色
        '4': 'gray'      // 暂停 - 灰色
    };
    return stateColors[state] || 'default';
};

const getStatusText = (state) => {
    const stateTexts = {
        '1': 'normal',     // 正常
        '2': 'disabled',   // 禁用
        '3': 'pending',    // 待审
        '4': 'suspended'   // 暂停
    };
    return stateTexts[state] || 'undefined';
};
</script>

<style scoped>
.customer-management {
    padding: 20px !important;
}

.top-actions {
    margin-bottom: 20px;
}

.search-section {
    margin-bottom: 20px;
}

.customer-management .arco-table-th {
    white-space: nowrap;
}
</style>