<template>
  <div style="padding: 20px;">
    <h2 style="margin-bottom: 20px;">服务权益管理</h2>

    <div class="header-toolbar">
      <el-form :inline="true" @submit.prevent>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="SKU/物料名称"
            clearable
            @keyup.enter="handleSearch"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="服务商">
          <el-input
            v-model="searchForm.provider_name"
            placeholder="服务商名称"
            clearable
            @keyup.enter="handleSearch"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="searchForm.start_date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="searchForm.end_date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增服务</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" border stripe style="width: 100%;" v-loading="loading">
      <el-table-column prop="sku" label="SKU" width="200" />
      <el-table-column prop="material_name" label="物料名称" />
      <el-table-column prop="provider_name" label="服务商" width="150" />
      <el-table-column prop="sale_price" label="售价" width="120">
        <template #default="{row}">￥{{ row.sale_price.toFixed(2) }}</template>
      </el-table-column>
      <el-table-column prop="description" label="简介" show-overflow-tooltip />
      <el-table-column prop="created_at" label="创建时间" width="160" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 20px; text-align: center;">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="perPage"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="基础物料ID" prop="base_id">
          <el-input-number
            v-model="form.base_id"
            placeholder="请输入基础物料ID"
            :controls="false"
            style="width: 100%;"
          />
          <div style="font-size:12px;color:#999;">需要先创建基础物料</div>
        </el-form-item>
        <el-form-item label="售价" prop="sale_price">
          <el-input-number
            v-model="form.sale_price"
            placeholder="请输入售价"
            :controls="false"
            :precision="2"
            :min="0"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="服务商" prop="provider_name">
          <el-input
            v-model="form.provider_name"
            placeholder="请输入服务商名称"
          />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入服务简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getServiceList,
  createService,
  updateService,
  deleteService,
  type ServiceItem,
  type ServiceQueryParams,
  type ServiceCreateRequest
} from '@/api/inbound/service'

// 表格数据
const tableData = ref<ServiceItem[]>([])
const loading = ref(false)
const page = ref(1)
const perPage = ref(20)
const total = ref(0)

const searchForm = reactive({
  keyword: '',
  provider_name: '',
  start_date: '',
  end_date: ''
})

// 加载列表
const loadData = async () => {
  loading.value = true
  try {
    const params: ServiceQueryParams = {
      page: page.value,
      per_page: perPage.value,
      keyword: searchForm.keyword || undefined,
      provider_name: searchForm.provider_name || undefined,
      start_date: searchForm.start_date || undefined,
      end_date: searchForm.end_date || undefined
    }
    const res = await getServiceList(params)
    if (res.code === 200) {
      tableData.value = res.data.items
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '加载失败')
    }
  } catch (error) {
    ElMessage.error('网络错误')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  loadData()
}
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    provider_name: '',
    start_date: '',
    end_date: ''
  })
  page.value = 1
  loadData()
}
const handleSizeChange = (val: number) => {
  perPage.value = val
  loadData()
}
const handlePageChange = (val: number) => {
  page.value = val
  loadData()
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const form = reactive({
  id: 0,
  base_id: 0,
  sale_price: 0,
  provider_name: '',
  description: ''
})
const rules = reactive<FormRules>({
  base_id: [
    { required: true, message: '请选择基础物料', trigger: 'blur' },
    { type: 'number', min: 1, message: '物料ID必须大于0', trigger: 'blur' }
  ],
  sale_price: [
    { required: true, message: '请输入售价', trigger: 'blur' },
    { type: 'number', min: 0, message: '售价不能为负数', trigger: 'blur' }
  ],
  provider_name: [
    { required: true, message: '请输入服务商名称', trigger: 'blur' }
  ]
})

const handleAdd = () => {
  dialogTitle.value = '新增服务'
  Object.assign(form, {
    id: 0,
    base_id: 0,
    sale_price: 0,
    provider_name: '',
    description: ''
  })
  dialogVisible.value = true
}
const handleEdit = (row: ServiceItem) => {
  dialogTitle.value = '编辑服务'
  Object.assign(form, {
    id: row.id,
    base_id: row.base_id,
    sale_price: row.sale_price,
    provider_name: row.provider_name,
    description: row.description
  })
  dialogVisible.value = true
}
const handleDialogConfirm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const reqData: ServiceCreateRequest = {
        base_id: form.base_id,
        sale_price: form.sale_price,
        provider_name: form.provider_name,
        description: form.description
      }
      if (form.id === 0) {
        await createService(reqData)
        ElMessage.success('创建成功')
      } else {
        await updateService(form.id, reqData)
        ElMessage.success('更新成功')
      }
      dialogVisible.value = false
      loadData()
    } catch (error: any) {
      ElMessage.error(error?.response?.data?.msg || '操作失败')
    }
  })
}
const resetDialog = () => {
  formRef.value?.clearValidate()
}

const handleDelete = (row: ServiceItem) => {
  ElMessageBox.confirm(`确定删除服务权益 "${row.sku}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteService(row.id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error: any) {
      ElMessage.error(error?.response?.data?.msg || '删除失败')
    }
  }).catch(() => {})
}

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