<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="供应商管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="handleCreate">
          新增供应商
        </a-button>
      </template>

      <!-- 序号 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>

      <!-- 状态 -->
      <template #status="{ record }">
        <a-tag :color="getStatusColor(record.status)">
          {{ getStatusText(record.status) }}
        </a-tag>
      </template>

      <!-- 累计交易金额 -->
      <template #total_amount="{ record }">
        {{ formatMoney(record.total_amount) }}
      </template>

      <!-- 合作开始日期 -->
      <template #cooperation_start_date="{ record }">
        {{ formatDate(record.cooperation_start_date) }}
      </template>

      <!-- 操作 -->
      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleDetail(record)">
          详情
        </a-button>
        <a-button type="text" size="small" @click="handleEdit(record)">
          编辑
        </a-button>
        <a-button type="text" size="small" status="danger" @click="handleDelete(record)">
          删除
        </a-button>
      </template>
    </search-table>

    <!-- 供应商详情对话框 -->
    <supplier-detail-dialog
      v-model:visible="detailVisible"
      :supplier="currentSupplier"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import {
  fetchSupplierList,
  deleteSupplier,
  fetchSupplierDetail,
} from '@/api/ops/supplier'
import SupplierDetailDialog from '../components/SupplierDetailDialog.vue'

const router = useRouter()

// 状态选项
const statusOptions = [
  { label: '合作中', value: 'active' },
  { label: '暂停合作', value: 'paused' },
  { label: '黑名单', value: 'blacklist' },
  { label: '停止合作', value: 'inactive' },
]

// 状态管理
const loading = ref(false)
const tableData = ref<any[]>([])
const formModel = ref({
  keyword: '',
  status: '',
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入供应商名称/编码/联系人/电话',
  },
  {
    field: 'status',
    label: '状态',
    type: 'select',
    placeholder: '请选择状态',
    options: statusOptions,
    allowClear: true,
  },
])

// 表格列配置
const columns = computed(() => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 80,
    align: 'center' as const,
  },
  {
    title: '供应商编码',
    dataIndex: 'code',
    ellipsis: true,
    tooltip: true,
    width: 120,
  },
  {
    title: '供应商名称',
    dataIndex: 'name',
    ellipsis: true,
    tooltip: true,
    width: 200,
  },
  {
    title: '联系人',
    dataIndex: 'contact_person',
    ellipsis: true,
    tooltip: true,
    width: 100,
  },
  {
    title: '联系电话',
    dataIndex: 'contact_phone',
    ellipsis: true,
    tooltip: true,
    width: 130,
  },
  {
    title: '订单数量',
    dataIndex: 'order_count',
    width: 100,
    align: 'center' as const,
  },
  {
    title: '累计交易金额',
    dataIndex: 'total_amount',
    slotName: 'total_amount',
    width: 130,
    align: 'right' as const,
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100,
    align: 'center' as const,
  },
  {
    title: '合作开始日期',
    dataIndex: 'cooperation_start_date',
    slotName: 'cooperation_start_date',
    width: 130,
    align: 'center' as const,
  },
  {
    title: '操作',
    slotName: 'actions',
    width: 200,
    fixed: 'right' as const,
  },
])

// 当前选中的供应商
const currentSupplier = ref<any>(null)

// 对话框可见性
const detailVisible = ref(false)

// 获取供应商列表
const fetchSuppliers = async () => {
  loading.value = true

  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
      status: formModel.value.status || undefined,
    }

    const res = await fetchSupplierList(params)

    tableData.value = res.details?.data || []
    pagination.total = res.details?.total || 0
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    Message.error('获取供应商列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchSuppliers()
}

// 处理表单模型更新
const handleFormModelUpdate = (value: any) => {
  formModel.value = value
}

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    status: '',
  }
  pagination.current = 1
  fetchSuppliers()
}

// 分页变化
const handlePageChange = (current: number) => {
  pagination.current = current
  fetchSuppliers()
}

// 刷新
const handleRefresh = () => {
  fetchSuppliers()
  Message.success('数据已刷新')
}

// 新增供应商 - 跳转到新增页面
const handleCreate = () => {
  router.push('/assets/supplier/form')
}

// 编辑供应商 - 跳转到编辑页面（通过 query 参数传递 id）
const handleEdit = (record: any) => {
  router.push({
    path: '/assets/supplier/form',
    query: { id: record.id },
  })
}

// 详情
const handleDetail = async (record: any) => {
  try {
    const res = await fetchSupplierDetail(record.id)
    if (res.code === 0) {
      currentSupplier.value = res.details
      detailVisible.value = true
    } else {
      Message.error(res.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取供应商详情失败:', error)
    Message.error('获取详情失败')
  }
}

// 删除供应商
const handleDelete = async (record: any) => {
  try {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除供应商 ${record.name} 吗？`,
      onOk: async () => {
        const res = await deleteSupplier(record.id)
        if (res.code === 0) {
          Message.success('删除成功')
          fetchSuppliers()
        } else {
          Message.error(res.message || '删除失败')
        }
      },
    })
  } catch (error) {
    console.error('删除供应商失败:', error)
  }
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    active: 'green',
    paused: 'orange',
    blacklist: 'red',
    inactive: 'gray',
  }
  return colorMap[status] || 'gray'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    active: '合作中',
    paused: '暂停合作',
    blacklist: '黑名单',
    inactive: '停止合作',
  }
  return textMap[status] || status
}

// 格式化金额
const formatMoney = (value: number | string | null | undefined) => {
  if (value === null || value === undefined || value === '') return '-'
  const num = Number(value)
  if (isNaN(num)) return '-'
  return num.toLocaleString('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2,
  })
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

// 初始化加载数据
onMounted(() => {
  fetchSuppliers()
})
</script>

<script lang="ts">
export default {
  name: 'SupplierList',
}
</script>

<style scoped lang="less">
.container {
  margin-top: 20px;
}
</style>