<template>
  <div class="supplier-form-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <a-button type="text" @click="handleBack">
          <template #icon><icon-left /></template>
          返回列表
        </a-button>
        <a-divider direction="vertical" />
        <h2 class="page-title">{{ pageTitle }}</h2>
      </div>
      <div class="header-right">
        <a-space>
          <a-button @click="handleBack">取消</a-button>
          <a-button type="primary" :loading="submitting" @click="handleSubmit">
            {{ isEdit ? '保存' : '创建' }}
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="page-content">
      <a-spin :loading="loading" style="width: 100%">
        <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
          <!-- 基本信息 -->
          <a-card class="info-card" title="基本信息">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="供应商名称" field="name" required>
                  <a-input
                    v-model="form.name"
                    placeholder="请输入供应商名称"
                    :max-length="200"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="供应商编码" field="code" required>
                  <a-input
                    v-model="form.code"
                    placeholder="请输入供应商编码"
                    :max-length="100"
                    :disabled="isEdit"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="简称" field="short_name">
                  <a-input
                    v-model="form.short_name"
                    placeholder="请输入简称"
                    :max-length="100"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="供应商类型" field="supplier_type" required>
                  <a-select
                    v-model="form.supplier_type"
                    placeholder="请选择供应商类型"
                    allow-clear
                  >
                    <a-option value="生产商">生产商</a-option>
                    <a-option value="代理商">代理商</a-option>
                    <a-option value="经销商">经销商</a-option>
                    <a-option value="服务商">服务商</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="供应商级别" field="supplier_level">
                  <a-select
                    v-model="form.supplier_level"
                    placeholder="请选择供应商级别"
                    allow-clear
                  >
                    <a-option value="A">A</a-option>
                    <a-option value="B">B</a-option>
                    <a-option value="C">C</a-option>
                    <a-option value="D">D</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="状态" field="status" required>
                  <a-select v-model="form.status" placeholder="请选择状态">
                    <a-option value="active">合作中</a-option>
                    <a-option value="paused">暂停合作</a-option>
                    <a-option value="blacklist">黑名单</a-option>
                    <a-option value="inactive">停止合作</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 联系信息 -->
          <a-card class="info-card" title="联系信息">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="联系人" field="contact_person" required>
                  <a-input
                    v-model="form.contact_person"
                    placeholder="请输入联系人"
                    :max-length="50"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="联系电话" field="contact_phone" required>
                  <a-input
                    v-model="form.contact_phone"
                    placeholder="请输入联系电话"
                    :max-length="20"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="备用联系电话" field="contact_mobile" required>
                  <a-input
                    v-model="form.contact_mobile"
                    placeholder="请输入备用联系电话"
                    :max-length="20"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="联系邮箱" field="contact_email" required>
                  <a-input
                    v-model="form.contact_email"
                    placeholder="请输入联系邮箱"
                    :max-length="100"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 地址信息 -->
          <a-card class="info-card" title="地址信息">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="省份" field="province">
                  <a-input
                    v-model="form.province"
                    placeholder="请输入省份"
                    :max-length="50"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="城市" field="city">
                  <a-input
                    v-model="form.city"
                    placeholder="请输入城市"
                    :max-length="50"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="邮编" field="postal_code">
                  <a-input
                    v-model="form.postal_code"
                    placeholder="请输入邮编"
                    :max-length="10"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="详细地址" field="address">
                  <a-input
                    v-model="form.address"
                    placeholder="请输入详细地址"
                    :max-length="200"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 企业信息 -->
          <a-card class="info-card" title="企业信息">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="法定代表人" field="legal_representative">
                  <a-input
                    v-model="form.legal_representative"
                    placeholder="请输入法定代表人"
                    :max-length="50"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="注册资本" field="registered_capital">
                  <a-input
                    v-model="form.registered_capital"
                    placeholder="请输入注册资本"
                    :max-length="50"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="营业执照号" field="business_license">
                  <a-input
                    v-model="form.business_license"
                    placeholder="请输入营业执照号"
                    :max-length="100"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="税号" field="tax_id">
                  <a-input
                    v-model="form.tax_id"
                    placeholder="请输入税号"
                    :max-length="50"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="企业类型" field="company_type">
                  <a-input
                    v-model="form.company_type"
                    placeholder="请输入企业类型"
                    :max-length="50"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="官网地址" field="website">
                  <a-input
                    v-model="form.website"
                    placeholder="请输入官网地址"
                    :max-length="200"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="供应商描述" field="description">
                  <a-textarea
                    v-model="form.description"
                    placeholder="请输入供应商描述"
                    :auto-size="{ minRows: 3, maxRows: 6 }"
                    :max-length="500"
                    show-word-limit
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-form>
      </a-spin>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue/es/form'
import {
  createSupplier,
  updateSupplier,
  fetchSupplierDetail,
} from '@/api/ops/supplier'

interface Supplier {
  id?: number
  name?: string
  code?: string
  short_name?: string
  description?: string
  contact_person?: string
  contact_phone?: string
  contact_email?: string
  contact_mobile?: string
  province?: string
  city?: string
  address?: string
  postal_code?: string
  website?: string
  legal_representative?: string
  registered_capital?: string
  business_license?: string
  tax_id?: string
  company_type?: string
  supplier_type?: string
  supplier_level?: string
  status?: string
}

const router = useRouter()
const route = useRoute()

// 页面状态
const isEdit = ref(false)
const supplierId = ref<number | null>(null)
const pageTitle = ref('新增供应商')
const loading = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const form = ref<Supplier>({
  name: '',
  code: '',
  short_name: '',
  description: '',
  contact_person: '',
  contact_phone: '',
  contact_email: '',
  contact_mobile: '',
  province: '',
  city: '',
  address: '',
  postal_code: '',
  website: '',
  legal_representative: '',
  registered_capital: '',
  business_license: '',
  tax_id: '',
  company_type: '',
  supplier_type: '',
  supplier_level: '',
  status: 'active',
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入供应商名称' }],
  code: [{ required: true, message: '请输入供应商编码' }],
  supplier_type: [{ required: true, message: '请选择供应商类型' }],
  status: [{ required: true, message: '请选择状态' }],
  contact_person: [{ required: true, message: '请输入联系人' }],
  contact_phone: [{ required: true, message: '请输入联系电话' }],
  contact_mobile: [{ required: true, message: '请输入备用联系电话' }],
  contact_email: [
    { required: true, message: '请输入联系邮箱' },
    { type: 'email', message: '请输入正确的邮箱格式' },
  ],
}

// 初始化页面
const initPage = async () => {
  const id = route.query.id
  if (id) {
    isEdit.value = true
    supplierId.value = Number(id)
    pageTitle.value = '编辑供应商'
    await loadSupplierDetail()
  }
}

// 加载供应商详情
const loadSupplierDetail = async () => {
  if (!supplierId.value) return

  loading.value = true
  try {
    const res = await fetchSupplierDetail(supplierId.value)
    if (res.code === 0) {
      form.value = { ...res.details }
    } else {
      Message.error(res.message || '获取详情失败')
      router.push('/assets/supplier')
    }
  } catch (error) {
    console.error('获取供应商详情失败:', error)
    Message.error('获取详情失败')
    router.push('/assets/supplier')
  } finally {
    loading.value = false
  }
}

// 返回上一级
const handleBack = () => {
  router.push('/assets/supplier')
}

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (valid) {
      return
    }

    submitting.value = true

    const data = { ...form.value }

    let res
    if (isEdit.value && supplierId.value) {
      res = await updateSupplier({ ...data, id: supplierId.value })
    } else {
      res = await createSupplier(data)
    }

    if (res.code === 0) {
      Message.success(isEdit.value ? '更新成功' : '创建成功')
      handleBack()
    } else {
      Message.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    Message.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 初始化
onMounted(() => {
  initPage()
})
</script>

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

<style scoped lang="less">
.supplier-form-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--color-fill-2);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: var(--color-bg-2);
  border-bottom: 1px solid var(--color-border);
  flex-shrink: 0;

  .header-left {
    display: flex;
    align-items: center;

    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }
}

.page-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.info-card {
  margin-bottom: 16px;

  &:last-child {
    margin-bottom: 0;
  }
}

// 表单项样式优化
:deep(.arco-form-item) {
  margin-bottom: 16px;
}

:deep(.arco-card) {
  .arco-card-header {
    border-bottom: 1px solid var(--color-border);
  }
}
</style>