<template>
  <page-container>
    <div class="coupon-template-list">
      <div class="table-header">
        <h1>优惠券模板</h1>
        <a-button type="primary" @click="showAddModal">
          新建模板
        </a-button>
      </div>

      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'amount'">
            <span>{{ record.amount > 0 ? `${record.amount}元` : '-' }}</span>
          </template>
          <template v-if="column.key === 'coupon_type'">
            <a-tag :color="getCouponTypeColor(record.coupon_type)">
              {{ getCouponTypeText(record.coupon_type) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'create_time'">
            {{ formatDateTime(record.create_time) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 添加/编辑模态框 -->
      <a-modal
        v-model:visible="modalVisible"
        :title="isEdit ? '编辑优惠券模板' : '新建优惠券模板'"
        @ok="handleSubmit"
        @cancel="handleCancel"
        :confirmLoading="submitting"
      >
        <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          layout="vertical"
        >
          <a-form-item
            label="模板名称"
            name="name"
            :rules="[{ required: true, message: '请输入模板名称' }]"
          >
            <a-input 
              v-model:value="formState.name"
              placeholder="请输入模板名称"
              :maxLength="50"
            />
          </a-form-item>
          
          <a-form-item
            label="优惠券类型"
            name="coupon_type"
            :rules="[{ required: true, message: '请选择优惠券类型' }]"
          >
            <a-select
              v-model:value="formState.coupon_type"
              @change="handleCouponTypeChange"
              placeholder="请选择优惠券类型"
            >
              <a-select-option value="CASH">现金券</a-select-option>
              <a-select-option value="PRODUCT">商品兑换券</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item
            label="优惠金额"
            name="amount"
            v-if="formState.coupon_type === 'CASH'"
            :rules="[{ required: true, message: '请输入优惠金额' }]"
          >
            <a-input-number
              v-model:value="formState.amount"
              :min="0"
              :precision="2"
              :step="0.5"
              style="width: 100%"
              placeholder="请输入优惠金额"
              addonAfter="元"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </page-container>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue'
import { message, Table, Modal, Button, Form, Input, Select, Tag, Space, InputNumber } from 'ant-design-vue'
import PageContainer from '@/components/PageContainer.vue'
import dayjs from 'dayjs'
import request from '@/utils/request'

export default defineComponent({
  components: {
    PageContainer,
    ATable: Table,
    AModal: Modal, 
    AButton: Button,
    AForm: Form,
    AFormItem: Form.Item,
    AInput: Input,
    AInputNumber: InputNumber,
    ASelect: Select,
    ASelectOption: Select.Option,
    ATag: Tag,
    ASpace: Space
  },
  
  setup() {
    const loading = ref(false)
    const tableData = ref([])
    
    const pagination = ref({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`
    })

    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 60,
        align: 'center'
      },
      {
        title: '模板名称',
        dataIndex: 'name',
        key: 'name',
        width: 250
      },
      {
        title: '优惠金额',
        dataIndex: 'amount',
        key: 'amount',
        width: 100,
        align: 'right'
      },
      {
        title: '优惠券类型',
        dataIndex: 'coupon_type',
        key: 'coupon_type',
        width: 100,
        align: 'center'
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        width: 180
      },
      {
        title: '操作',
        key: 'action',
        width: 80,
        fixed: 'right'
      }
    ]

    // 获取优惠券类型显示文本
    const getCouponTypeText = (type) => {
      const typeMap = {
        'CASH': '现金券',
        'PRODUCT': '商品兑换券'
      }
      return typeMap[type] || type
    }

    // 获取优惠券类型标签颜色
    const getCouponTypeColor = (type) => {
      const colorMap = {
        'CASH': 'blue',
        'PRODUCT': 'green'
      }
      return colorMap[type] || 'default'
    }

    // 格式化日期时间
    const formatDateTime = (value) => {
      if (!value) return ''
      return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    }

    // 获取列表数据
    const fetchData = async () => {
      try {
        loading.value = true
        const params = {
          skip: (pagination.value.current - 1) * pagination.value.pageSize,
          limit: pagination.value.pageSize
        }
        
        const res = await request.get('/api/coupon/list', { params })
        if (res.code === 200) {
          tableData.value = res.data
          pagination.value.total = res.data.length
        } else {
          message.error(res.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取优惠券模板列表失败:', error)
        message.error('获取数据失败')
      } finally {
        loading.value = false
      }
    }

    // 处理表格分页变化
    const handleTableChange = (pag) => {
      pagination.value.current = pag.current
      pagination.value.pageSize = pag.pageSize
      fetchData()
    }

    const modalVisible = ref(false)
    const submitting = ref(false)
    const isEdit = ref(false)
    const currentId = ref(null)
    const formRef = ref(null)
    
    const formState = ref({
      name: '',
      amount: undefined,
      coupon_type: undefined
    })

    // 表单验证规则
    const rules = {
      name: [{ required: true, message: '请输入模板名称' }],
      coupon_type: [{ required: true, message: '请选择优惠券类型' }],
      amount: [{ required: true, message: '请输入优惠金额' }]
    }

    // 显示新建模态框
    const showAddModal = () => {
      isEdit.value = false
      currentId.value = null
      formState.value = {
        name: '',
        amount: undefined,
        coupon_type: undefined
      }
      modalVisible.value = true
    }

    // 显示编辑模态框
    const handleEdit = (record) => {
      isEdit.value = true
      currentId.value = record.id
      formState.value = {
        name: record.name,
        amount: record.coupon_type === 'CASH' ? (record.amount || 0) : undefined,
        coupon_type: record.coupon_type
      }
      modalVisible.value = true
    }

    // 处理优惠券类型变化
    const handleCouponTypeChange = (value) => {
      if (value === 'PRODUCT') {
        formState.value.amount = undefined;
      } else if (value === 'CASH') {
        formState.value.amount = formState.value.amount || 0;
      }
    }

    // 提交表单
    const handleSubmit = () => {
      formRef.value.validate().then(async () => {
        try {
          submitting.value = true
          const params = {
            name: formState.value.name,
            amount: formState.value.coupon_type === 'CASH' ? formState.value.amount : 0,
            coupon_type: formState.value.coupon_type
          }
          
          let res
          if (isEdit.value) {
            res = await request.put(`/api/coupon/${currentId.value}`, params)
          } else {
            res = await request.post('/api/coupon', params)
          }
          
          if (res.code === 200) {
            message.success(isEdit.value ? '更新成功' : '创建成功')
            modalVisible.value = false
            fetchData()
          } else {
            message.error(res.message || (isEdit.value ? '更新失败' : '创建失败'))
          }
        } catch (error) {
          console.error(isEdit.value ? '更新优惠券模板失败:' : '创建优惠券模板失败:', error)
          message.error(isEdit.value ? '更新失败' : '创建失败')
        } finally {
          submitting.value = false
        }
      })
    }

    // 取消操作
    const handleCancel = () => {
      formRef.value?.resetFields()
      modalVisible.value = false
    }

    onMounted(() => {
      fetchData()
    })

    return {
      loading,
      tableData,
      columns,
      pagination,
      getCouponTypeText,
      getCouponTypeColor,
      formatDateTime,
      handleTableChange,
      modalVisible,
      submitting,
      formState,
      formRef,
      showAddModal,
      handleEdit,
      handleSubmit,
      handleCancel,
      handleCouponTypeChange,
      rules
    }
  }
})
</script>

<style scoped>
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h1 {
  margin: 0;
}

:deep(.ant-table-content) {
  overflow-x: auto;
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-input-number) {
  width: 100% !important;
}
</style> 