<template>
  <div class="merchant-management">
    <a-page-header
      title="商家管理"
      sub-title="管理系统商家信息"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleRefresh">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
          <a-button 
            v-if="hasPermission('merchant:write')" 
            type="primary" 
            @click="showCreateModal"
          >
            <template #icon>
              <PlusOutlined />
            </template>
            新增商家
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <a-card>
      <!-- 搜索区域 -->
      <div class="search-container">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="关键词">
            <a-input
              v-model:value="searchForm.keyword"
              placeholder="商家名称/联系人"
              allow-clear
            />
          </a-form-item>
          
          <a-form-item label="状态">
            <a-select
              v-model:value="searchForm.status"
              placeholder="全部状态"
              style="width: 120px"
              allow-clear
            >
              <a-select-option value="pending">待审核</a-select-option>
              <a-select-option value="approved">已通过</a-select-option>
              <a-select-option value="rejected">已拒绝</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="类型">
            <a-select
              v-model:value="searchForm.type"
              placeholder="全部类型"
              style="width: 120px"
              allow-clear
            >
              <a-select-option value="farm">农场</a-select-option>
              <a-select-option value="hotel">酒店</a-select-option>
              <a-select-option value="restaurant">餐厅</a-select-option>
              <a-select-option value="transport">交通</a-select-option>
              <a-select-option value="shop">商店</a-select-option>
              <a-select-option value="other">其他</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button style="margin-left: 8px" @click="handleReset">
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 商家表格 -->
      <a-table
        :columns="columns"
        :data-source="merchantList"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'actions'">
            <a-space :size="8">
              <a-button size="small" @click="handleView(record)">
                <EyeOutlined />
                查看
              </a-button>
              
              <a-button 
                v-if="hasPermission('merchant:write')" 
                size="small" 
                @click="handleEdit(record)"
              >
                <EditOutlined />
                编辑
              </a-button>
              
              <template v-if="record.status === 'pending' && hasPermission('merchant:write')">
                <a-button size="small" type="primary" @click="handleApprove(record)">
                  <CheckOutlined />
                  通过
                </a-button>
                <a-button size="small" danger @click="handleReject(record)">
                  <CloseOutlined />
                  拒绝
                </a-button>
              </template>
              
              <a-button 
                v-if="record.status === 'approved' && hasPermission('merchant:write')" 
                size="small" 
                danger 
                @click="handleDisable(record)"
              >
                <StopOutlined />
                禁用
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑商家模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="merchantFormRef"
        :model="currentMerchant"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="商家名称" name="name">
          <a-input v-model:value="currentMerchant.name" placeholder="请输入商家名称" />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="类型" name="type">
              <a-select v-model:value="currentMerchant.type" placeholder="请选择类型">
                <a-select-option value="farm">农场</a-select-option>
                <a-select-option value="hotel">酒店</a-select-option>
                <a-select-option value="restaurant">餐厅</a-select-option>
                <a-select-option value="transport">交通</a-select-option>
                <a-select-option value="shop">商店</a-select-option>
                <a-select-option value="other">其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select v-model:value="currentMerchant.status" placeholder="请选择状态">
                <a-select-option value="pending">待审核</a-select-option>
                <a-select-option value="approved">已通过</a-select-option>
                <a-select-option value="rejected">已拒绝</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="联系人" name="contact_person">
          <a-input v-model:value="currentMerchant.contact_person" placeholder="请输入联系人" />
        </a-form-item>
        
        <a-form-item label="联系电话" name="contact_phone">
          <a-input v-model:value="currentMerchant.contact_phone" placeholder="请输入联系电话" />
        </a-form-item>
        
        <a-form-item label="地址" name="address">
          <a-textarea
            v-model:value="currentMerchant.address"
            placeholder="请输入地址"
            :rows="2"
          />
        </a-form-item>
        
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="currentMerchant.description"
            placeholder="请输入商家描述"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal, type FormInstance } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  CheckOutlined,
  CloseOutlined,
  StopOutlined
} from '@ant-design/icons-vue'
import { useAppStore } from '@/stores/app'
import { 
  getMerchants, 
  getMerchant, 
  createMerchant, 
  updateMerchant, 
  approveMerchant, 
  rejectMerchant, 
  disableMerchant 
} from '@/api/merchant'
import type { Merchant, MerchantQueryParams } from '@/api/merchant'

interface SearchForm {
  keyword: string
  status: string
  type: string
}

const appStore = useAppStore()

// 权限检查方法
const hasPermission = (permission: string) => {
  return appStore.hasPermission(permission)
}

const loading = ref(false)
const searchForm = reactive<SearchForm>({
  keyword: '',
  status: '',
  type: ''
})

const merchantList = ref<Merchant[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const columns = [
  {
    title: '商家名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '类型',
    key: 'type',
    width: 100,
    align: 'center'
  },
  {
    title: '联系人',
    dataIndex: 'contact_person',
    key: 'contact_person',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'contact_phone',
    key: 'contact_phone',
    width: 120
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 120
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center'
  }
]

// 状态映射
const getStatusColor = (status: string) => {
  const colors = {
    pending: 'orange',
    approved: 'green',
    rejected: 'red'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getStatusText = (status: string) => {
  const texts = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return texts[status as keyof typeof texts] || '未知'
}

// 类型映射
const getTypeColor = (type: string) => {
  const colors = {
    farm: 'green',
    hotel: 'blue',
    restaurant: 'orange',
    transport: 'purple',
    shop: 'pink',
    other: 'gray'
  }
  return colors[type as keyof typeof colors] || 'default'
}

const getTypeText = (type: string) => {
  const texts = {
    farm: '农场',
    hotel: '酒店',
    restaurant: '餐厅',
    transport: '交通',
    shop: '商店',
    other: '其他'
  }
  return texts[type as keyof typeof texts] || '未知'
}

// 添加模态框相关状态
const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('新增商家')
const isEditing = ref(false)
const merchantFormRef = ref<FormInstance>()

// 当前商家数据
const currentMerchant = ref<Partial<Merchant>>({})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入商家名称' }
  ],
  type: [
    { required: true, message: '请选择类型' }
  ],
  status: [
    { required: true, message: '请选择状态' }
  ],
  contact_person: [
    { required: true, message: '请输入联系人' }
  ],
  contact_phone: [
    { required: true, message: '请输入联系电话' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ]
}

// 生命周期
onMounted(() => {
  loadMerchants()
})

// 方法
const loadMerchants = async () => {
  loading.value = true
  try {
    const params: MerchantQueryParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status,
      type: searchForm.type
    }
    
    const response = await getMerchants(params)
    merchantList.value = response.data.list
    pagination.total = response.data.pagination.total
  } catch (error) {
    message.error('加载商家列表失败')
  } finally {
    loading.value = false
  }
}

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

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    type: ''
  })
  pagination.current = 1
  loadMerchants()
}

const handleRefresh = () => {
  loadMerchants()
  message.success('数据已刷新')
}

const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current!
  pagination.pageSize = pag.pageSize!
  loadMerchants()
}

const handleView = async (record: Merchant) => {
  try {
    const response = await getMerchant(record.id)
    Modal.info({
      title: '商家详情',
      width: 600,
      content: h('div', { class: 'merchant-detail-modal' }, [
        h('a-descriptions', {
          column: 1,
          bordered: true
        }, [
          h('a-descriptions-item', { label: '商家名称' }, response.data.name),
          h('a-descriptions-item', { label: '类型' }, [
            h('a-tag', { color: getTypeColor(response.data.type) }, getTypeText(response.data.type))
          ]),
          h('a-descriptions-item', { label: '状态' }, [
            h('a-tag', { color: getStatusColor(response.data.status) }, getStatusText(response.data.status))
          ]),
          h('a-descriptions-item', { label: '联系人' }, response.data.contact_person),
          h('a-descriptions-item', { label: '联系电话' }, response.data.contact_phone),
          h('a-descriptions-item', { label: '地址' }, response.data.address || '-'),
          h('a-descriptions-item', { label: '描述' }, response.data.description || '-'),
          h('a-descriptions-item', { label: '创建时间' }, response.data.created_at)
        ])
      ]),
      okText: '关闭'
    })
  } catch (error) {
    message.error('获取商家详情失败')
  }
}

const handleEdit = async (record: Merchant) => {
  try {
    modalLoading.value = true
    const response = await getMerchant(record.id)
    modalTitle.value = '编辑商家'
    isEditing.value = true
    currentMerchant.value = response.data
    modalVisible.value = true
  } catch (error) {
    message.error('获取商家详情失败')
  } finally {
    modalLoading.value = false
  }
}

const showCreateModal = () => {
  modalTitle.value = '新增商家'
  isEditing.value = false
  currentMerchant.value = {
    status: 'pending',
    type: 'farm'
  }
  modalVisible.value = true
}

const handleModalOk = () => {
  merchantFormRef.value
    ?.validate()
    .then(() => {
      if (isEditing.value) {
        handleUpdateMerchant()
      } else {
        handleCreateMerchant()
      }
    })
    .catch((error: any) => {
      console.error('表单验证失败:', error)
    })
}

const handleModalCancel = () => {
  modalVisible.value = false
  merchantFormRef.value?.resetFields()
}

const handleCreateMerchant = async () => {
  try {
    modalLoading.value = true
    await createMerchant(currentMerchant.value as any)
    message.success('创建商家成功')
    modalVisible.value = false
    loadMerchants()
  } catch (error) {
    message.error('创建商家失败')
  } finally {
    modalLoading.value = false
  }
}

const handleUpdateMerchant = async () => {
  try {
    modalLoading.value = true
    await updateMerchant(currentMerchant.value.id!, currentMerchant.value as any)
    message.success('更新商家成功')
    modalVisible.value = false
    loadMerchants()
  } catch (error) {
    message.error('更新商家失败')
  } finally {
    modalLoading.value = false
  }
}

const handleApprove = async (record: Merchant) => {
  Modal.confirm({
    title: '确认通过',
    content: `确定要通过商家 "${record.name}" 的审核吗？`,
    onOk: async () => {
      try {
        await approveMerchant(record.id)
        message.success('商家审核已通过')
        loadMerchants()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleReject = async (record: Merchant) => {
  Modal.confirm({
    title: '确认拒绝',
    content: `确定要拒绝商家 "${record.name}" 的审核吗？`,
    onOk: async () => {
      try {
        await rejectMerchant(record.id)
        message.success('商家审核已拒绝')
        loadMerchants()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleDisable = async (record: Merchant) => {
  Modal.confirm({
    title: '确认禁用',
    content: `确定要禁用商家 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        await disableMerchant(record.id)
        message.success('商家已禁用')
        loadMerchants()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}
</script>

<style scoped lang="less">
.merchant-management {
  .search-container {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
    
    :deep(.ant-form-item) {
      margin-bottom: 16px;
    }
  }
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}
</style>