<script setup>

import { Search } from '@element-plus/icons-vue'
import { ref, onMounted, reactive } from 'vue'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { ElMessage } from 'element-plus'
import {
    getCustomerList,
    createCustomer,
    updateCustomer,
    deleteCustomerAPI
} from '../api/customer'

const form = reactive({
    id: '',
    name: '',           // 姓名，默认为空字符串
    phone: '',          // 电话，默认为空字符串
    region: [],         // 地区，默认为空数组（省市区三级代码）
    address: '',        // 详细地址，默认为空字符串
    email: '',          // 电子邮箱，默认为空字符串
    customer_type: 'Normal'  // 客户类型，默认选中"普通客户"
})

const search = ref('')
const select = ref('1')
const searchResults = ref([])
const showSearchResults = ref(false) //是否显示搜索结果
const showAddForm = ref(false) //是否显示新增表单
const isEditMode = ref(false)   //是否为编辑模式
const currentCustomerId = ref(null)  //当前编辑的客户的ID
const loading = ref(false)

onMounted(() => {
    fetchData()
})

//获取用户列表
const fetchData = async () => {
    loading.value = true;
    const res = await getCustomerList()
    searchResults.value = res.data
    showSearchResults.value = true
    loading.value = false
}

//搜索
const handleSearch = async () => {
    loading.value = true
    const res = await getCustomerList({ keyword: search.value, searchField: select.value })
    searchResults.value = res.data
    showSearchResults.value = true
    loading.value = false
}

// 清空表单
const resetForm = () => {
    form.id = ''
    form.name = ''
    form.phone = ''
    form.region = []
    form.address = ''
    form.email = ''
    form.customer_type = 'Normal'
    isEditMode.value = false
    currentCustomerId.value = null
}

// 显示新增表单
const addCustomer = () => {
    resetForm()
    showAddForm.value = true
    showSearchResults.value = false
}

//编辑
const editCustomer = (row) => {
    isEditMode.value = true
    currentCustomerId.value = row.id
    form.name = row.name
    form.phone = row.phone
    // 名称转回代码，让级联选择器显示
    form.region = [
        TextToCode[row.province]?.code || '',
        TextToCode[row.province]?.[row.city]?.code || '',
        TextToCode[row.province]?.[row.city]?.[row.district]?.code || ''
    ]
    form.address = row.address
    form.email = row.email
    form.customer_type = row.customer_type
    showAddForm.value = true
    showSearchResults.value = false
}

const saveCustomer = async () => {
    const formData = {
        name: form.name,
        phone: form.phone,
        province: CodeToText[form.region[0]] || '',
        city: CodeToText[form.region[1]] || '',
        district: CodeToText[form.region[2]] || '',
        address: form.address,
        email: form.email,
        customer_type: form.customer_type
    }
    if (isEditMode.value) {
        await updateCustomer(currentCustomerId.value, formData)
        ElMessage.success('更新成功')
    } else {
        await createCustomer(formData)
        ElMessage.success('新增成功')
    }

    cancelAdd()
    fetchData()
}

// 删除
const deleteCustomer = async (id) => {
    ElMessageBox.confirm('确定删除该客户吗？', '提示', {
        type: 'warning'
    }).then(async () => {
        await deleteCustomerAPI(id)
        ElMessage.success('删除成功')
        fetchData()
    })
}

// 取消
const cancelAdd = () => {
    resetForm()
    showAddForm.value = false
    showSearchResults.value = true
}

// 清空搜索
const clearSearch = () => {
    search.value = ''
    showSearchResults.value = false
    showAddForm.value = false
    fetchData()
}

</script>

<template>
    <div class="customer-container">
        <!-- 搜索栏区域 -->
        <div class="customer-search">
            <el-input v-model="search" style="max-width: 600px" placeholder="Please input"
                class="customer-search-with-select" @keyup.enter="handleSearch">
                <template #prepend>
                    <el-select v-model="select" placeholder="Select" style="width: 115px">
                        <el-option label="姓名" value="1" />
                        <el-option label="编号" value="2" />
                        <el-option label="电话" value="3" />
                        <el-option label="邮箱" value="4" />
                    </el-select>
                </template>
                <template #append>
                    <el-button :icon="Search" @click="handleSearch" />
                </template>
            </el-input>

            <el-button type="default" @click="clearSearch" style="margin-left:20px">
                重置
            </el-button>
            <el-button color="#E60012" @click="addCustomer" style="margin-left: 20px">
                新增用户
            </el-button>

        </div>

        <div v-if="showSearchResults" class="customer-list">
             <div v-if="loading" class="loading-container">
                <el-skeleton :rows="5" animated />
            </div>

            <div v-else-if="searchResults.length === 0" class="empty-container">
                <el-empty description="暂无客户数据" />
            </div>


            <div v-else class="customer-table">
                <el-table :data="searchResults" v-loading="loading" border style="width: 100%">
                    <el-table-column prop="id" label="编号" width="80" />
                    <el-table-column prop="name" label="姓名" width="120" />
                    <el-table-column prop="phone" label="电话" width="150" />
                    <el-table-column label="地区" width="200">
                        <template #default="{ row }">
                            {{ [row.province, row.city, row.district].filter(Boolean).join(' ') }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="address" label="详细地址" width="200" />
                    <el-table-column prop="email" label="电子邮箱" width="200" />
                    <el-table-column prop="customer_type" label="代理商类型" width="120">
                        <template #default="{ row }">
                            <el-tag :type="row.customer_type === 'VIP' ? 'danger' : 'info'">
                                {{ row.customer_type === 'VIP' ? '地区总代理' : '普通代理' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150" fixed="right">
                        <template #default="{ row }">
                            <el-button link type="primary" @click="editCustomer(row)">编辑</el-button>
                            <el-button link type="danger" @click="deleteCustomer(row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div style="margin-top: 10px; color: #909399; font-size: 14px;">
                    找到 {{ searchResults.length }} 条结果
                    <el-button link type="primary" @click="clearSearch">清空搜索</el-button>
                </div>
            </div>
        </div>
       

        <!-- 新增客户表单 -->
        <div v-if="showAddForm" class="customer-info-label">
            <el-divider content-position="left">{{ isEditMode ? '编辑客户信息' : '新增客户' }}</el-divider>
            <el-form :model="form" label-width="auto" style="max-width: 600px" label-position="top">
                <el-form-item label="姓名">
                    <el-input v-model="form.name" placeholder="请输入姓名" />
                </el-form-item>

                <el-form-item label="电话">
                    <el-input v-model="form.phone" :controls="false" :min="0" :max="99999999999" :precision="0"
                        placeholder="请输入11位手机号" style="width: 100%" />
                </el-form-item>

                <el-form-item label="地区">
                    <el-cascader v-model="form.region" :options="regionData" :props="{ expandTrigger: 'hover' }"
                        placeholder="请选择省/市/区" clearable style="width: 100%" />
                </el-form-item>

                <el-form-item label="详细地址">
                    <el-input v-model="form.address" placeholder=" 请输入详细地址" />
                </el-form-item>

                <el-form-item label="电子邮箱">
                    <el-input v-model="form.email" placeholder=" 请输入邮箱地址" />
                </el-form-item>

                <el-form-item label="代理商类型">
                    <el-radio-group v-model="form.customer_type">
                        <el-radio value="VIP">地区总代理</el-radio>
                        <el-radio value="Normal">普通代理</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveCustomer">保存</el-button>
                    <el-button type="danger" @click="cancelAdd">取消</el-button>
                </el-form-item>
            </el-form>

        </div>
    </div>
</template>

<style scoped></style>