<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>联系人管理</span>
          <el-button type="primary" @click="handleAdd">新增联系人</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="客户">
          <el-select v-model="searchForm.customerId" placeholder="请选择客户" clearable style="width: 200px" @change="handleSearch">
            <el-option 
              v-for="customer in customerList" 
              :key="customer.customerId" 
              :label="customer.customerName" 
              :value="customer.customerId" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="searchForm.contactName" placeholder="请输入联系人姓名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" stripe border>
        <el-table-column prop="contactId" label="联系人 ID" width="100" />
        <el-table-column prop="contactName" label="姓名" width="120" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="department" label="部门" width="150" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="mobile" label="手机号码" width="130" />
        <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
        <el-table-column prop="wechat" label="微信" width="120" />
        <el-table-column prop="isPrimary" label="主联系人" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isPrimary === '1' ? 'success' : 'info'">
              {{ scope.row.isPrimary === '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{ scope.row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              v-if="scope.row.isPrimary !== '1'" 
              type="warning" 
              link 
              @click="handleSetPrimary(scope.row)"
            >
              设为主联系人
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属客户" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择客户" style="width: 100%">
                <el-option 
                  v-for="customer in customerList" 
                  :key="customer.customerId" 
                  :label="customer.customerName" 
                  :value="customer.customerId" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="form.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input v-model="form.department" placeholder="请输入部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信" prop="wechat">
              <el-input v-model="form.wechat" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="QQ" prop="qq">
              <el-input v-model="form.qq" placeholder="请输入QQ号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主联系人" prop="isPrimary">
              <el-switch v-model="form.isPrimary" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getContactList, createContact, updateContact, deleteContact } from '../../api/customer'
import { getCustomerList } from '../../api/customer'

const searchForm = reactive({
  customerId: null,
  contactName: ''
})

const customerList = ref([])
const tableData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增联系人')
const formRef = ref(null)
const form = reactive({
  contactId: null,
  customerId: null,
  contactName: '',
  position: '',
  department: '',
  phone: '',
  mobile: '',
  email: '',
  wechat: '',
  qq: '',
  isPrimary: '0',
  remark: ''
})

const rules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }]
}

const loadCustomerList = async () => {
  try {
    const res = await getCustomerList({ current: 1, size: 1000 })
    customerList.value = res.records
  } catch (error) {
    ElMessage.error('加载客户列表失败')
  }
}

const loadTableData = async () => {
  if (!searchForm.customerId) {
    tableData.value = []
    return
  }
  
  try {
    const res = await getContactList(searchForm.customerId)
    let contacts = res || []
    
    // 根据姓名过滤
    if (searchForm.contactName) {
      contacts = contacts.filter(c => c.contactName.includes(searchForm.contactName))
    }
    
    tableData.value = contacts
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
}

const handleSearch = () => {
  loadTableData()
}

const handleReset = () => {
  searchForm.customerId = null
  searchForm.contactName = ''
  tableData.value = []
}

const handleAdd = () => {
  dialogTitle.value = '新增联系人'
  Object.assign(form, {
    contactId: null,
    customerId: searchForm.customerId || null,
    contactName: '',
    position: '',
    department: '',
    phone: '',
    mobile: '',
    email: '',
    wechat: '',
    qq: '',
    isPrimary: '0',
    remark: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑联系人'
  Object.assign(form, {
    contactId: row.contactId,
    customerId: row.customerId,
    contactName: row.contactName,
    position: row.position,
    department: row.department,
    phone: row.phone,
    mobile: row.mobile,
    email: row.email,
    wechat: row.wechat,
    qq: row.qq,
    isPrimary: row.isPrimary,
    remark: row.remark
  })
  dialogVisible.value = true
}

const handleSubmit = async () => {
  await formRef.value.validate()
  try {
    if (form.contactId) {
      await updateContact(form.contactId, form)
      ElMessage.success('更新成功')
    } else {
      await createContact(form)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadTableData()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该联系人吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteContact(row.contactId)
      ElMessage.success('删除成功')
      loadTableData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSetPrimary = (row) => {
  ElMessageBox.confirm('确定要将此联系人设置为主联系人吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const updatedContact = { ...row, isPrimary: '1' }
      await updateContact(row.contactId, updatedContact)
      ElMessage.success('设置成功')
      loadTableData()
    } catch (error) {
      ElMessage.error('设置失败')
    }
  })
}

onMounted(() => {
  loadCustomerList()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}
</style>
