<template>
  <GiPageLayout>
    <GiTable
      row-key="typeId"
      title="制度类型管理"
      :data="dataList"
      :columns="tableColumns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
      @refresh="search"
    >
      <template #top>
        <div class="search-container">
          <a-form layout="inline" :model="searchForm" class="search-form">
            <a-form-item label="类型名称">
              <a-input 
                v-model="searchForm.typeName" 
                placeholder="请输入类型名称" 
                allow-clear
                style="width: 200px"
              />
            </a-form-item>
            
            <a-form-item label="状态">
              <a-select 
                v-model="searchForm.status" 
                placeholder="请选择状态" 
                allow-clear
                style="width: 150px"
              >
                <a-option value="">全部</a-option>
                <a-option value="1">启用</a-option>
                <a-option value="0">禁用</a-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="备注">
              <a-input 
                v-model="searchForm.remark" 
                placeholder="请输入备注内容" 
                allow-clear
                style="width: 200px"
              />
            </a-form-item>
            
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="search">
                  <template #icon><icon-search /></template>
                  搜索
                </a-button>
                <a-button @click="reset">
                  <template #icon><icon-refresh /></template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
      </template>
      
      <template #toolbar-left>
        <a-space>
          <a-button type="primary" @click="openAddModal">
            <template #icon><icon-plus /></template>
            <template #default>新增类型</template>
          </a-button>
          <span class="search-result-info">
            共找到 <strong>{{ pagination.total }}</strong> 条记录
          </span>
        </a-space>
      </template>
      
      <!-- 启用状态 -->
      <template #isEnabled="{ record }">
        <a-tag :color="record.isEnabled === '1' ? 'green' : 'red'">
          {{ record.isEnabled === '1' ? '启用' : '禁用' }}
        </a-tag>
      </template>
      
      <!-- 操作列 -->
      <template #action="{ record }">
        <a-space>
          <a-link @click="editRecord(record)">编辑</a-link>
          <a-popconfirm
            content="确定要删除这个制度类型吗？"
            @ok="deleteRecord(record)"
          >
            <a-link status="danger">删除</a-link>
          </a-popconfirm>
        </a-space>
      </template>
    </GiTable>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="600px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="类型名称" field="typeName">
          <a-input v-model="formData.typeName" placeholder="请输入制度类型名称" />
        </a-form-item>
        
        <a-form-item label="排序" field="sortOrder">
          <a-input-number 
            v-model="formData.sortOrder" 
            placeholder="请输入排序值" 
            :min="0"
            :max="999"
            style="width: 100%"
          />
        </a-form-item>
        
        <a-form-item label="状态" field="isEnabled">
          <a-radio-group v-model="formData.isEnabled">
            <a-radio value="1">启用</a-radio>
            <a-radio value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="备注" field="remark">
          <a-textarea 
            v-model="formData.remark" 
            placeholder="请输入备注信息" 
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </GiPageLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconSearch, IconRefresh } from '@arco-design/web-vue/es/icon'
import { regulationApi } from '@/apis/regulation'
import { 
  type RegulationType,
  type CreateRegulationTypeRequest,
  type UpdateRegulationTypeRequest,
  type RegulationTypeSearchRequest
} from '@/apis/regulation/type'

defineOptions({ name: 'RegulationType' })

// 表格列定义
const tableColumns = [
  { title: '类型名称', dataIndex: 'typeName', key: 'typeName', width: 150 },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 200 },
  { title: '状态', dataIndex: 'isEnabled', key: 'isEnabled', slotName: 'isEnabled', width: 100 },
  { title: '创建人', dataIndex: 'createrName', key: 'createrName', width: 120 },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
  { title: '排序', dataIndex: 'sortOrder', key: 'sortOrder', width: 100 },
  { title: '操作', key: 'action', slotName: 'action', width: 150, fixed: 'right' }
]



// 表格数据
const dataList = ref<RegulationType[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true
})

// 查询表单
const searchForm = reactive({
  typeName: '',
  status: '',
  remark: ''
})

// 弹窗相关
const modalVisible = ref(false)
const modalTitle = ref('新增制度类型')
const formRef = ref()
const formData = reactive({
  typeId: '',
  typeName: '',
  sortOrder: 0,
  isEnabled: '1',
  remark: ''
})

// 表单验证规则
const rules = {
  typeName: [{ required: true, message: '请输入制度类型名称' }],
  sortOrder: [{ required: true, message: '请输入排序值' }],
  isEnabled: [{ required: true, message: '请选择状态' }]
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    // 使用后端搜索接口
    const response = await regulationApi.searchRegulationTypes({
      page: pagination.current,
      size: pagination.pageSize,
      typeName: searchForm.typeName || undefined,
      status: searchForm.status || undefined,
      remark: searchForm.remark || undefined,
    })
    
    if (response.status === 200) {
      dataList.value = response.data.records || response.data
      pagination.total = response.data.total || response.data.length
      pagination.current = response.data.current || 1
    } else {
      Message.error('搜索失败')
    }
  } catch (error) {
    console.error('搜索制度类型失败:', error)
    Message.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const search = () => {
  pagination.current = 1
  getTableData()
}



// 重置
const reset = () => {
  Object.assign(searchForm, {
    typeName: '',
    status: '',
    remark: ''
  })
  pagination.current = 1
  getTableData()
}

// 分页事件
const onPageChange = (page: number) => {
  pagination.current = page
  getTableData()
}

const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  getTableData()
}

// 新增
const openAddModal = () => {
  modalTitle.value = '新增制度类型'
  modalVisible.value = true
  resetForm()
}

// 编辑
const editRecord = (record: RegulationType) => {
  modalTitle.value = '编辑制度类型'
  modalVisible.value = true
  Object.assign(formData, {
    typeId: record.typeId,
    typeName: record.typeName,
    sortOrder: record.sortOrder,
    isEnabled: record.isEnabled,
    remark: record.remark || ''
  })
}

// 删除
const deleteRecord = async (record: RegulationType) => {
  try {
    await regulationApi.deleteRegulationType(record.typeId)
    Message.success('删除成功')
    getTableData()
  } catch (error) {
    console.error('删除失败:', error)
    Message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (formData.typeId) {
      // 更新
      const updateData: UpdateRegulationTypeRequest = {
        typeName: formData.typeName,
        sortOrder: formData.sortOrder,
        isEnabled: formData.isEnabled,
        remark: formData.remark
      }
      await regulationApi.updateRegulationType(formData.typeId, updateData)
      Message.success('更新成功')
    } else {
      // 新增
      const createData: CreateRegulationTypeRequest = {
        typeName: formData.typeName,
        sortOrder: formData.sortOrder,
        isEnabled: formData.isEnabled,
        remark: formData.remark
      }
      await regulationApi.createRegulationType(createData)
      Message.success('新增成功')
    }
    
    modalVisible.value = false
    getTableData()
  } catch (error) {
    console.error('操作失败:', error)
    Message.error('操作失败')
  }
}

// 取消
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    typeId: '',
    typeName: '',
    sortOrder: 0,
    isEnabled: '1',
    remark: ''
  })
  formRef.value?.resetFields()
}

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

<style scoped lang="scss">
.regulation-type {
  .arco-card {
    margin-bottom: 16px;
  }
}

.search-container {
  padding: 16px;
  background: var(--color-bg-2);
  border-radius: 6px;
  margin-bottom: 16px;
  
  .search-form {
    .arco-form-item {
      margin-bottom: 0;
      margin-right: 16px;
      
      .arco-form-item-label {
        font-weight: 500;
        color: var(--color-text-1);
        margin-right: 8px;
      }
    }
    
    .arco-input,
    .arco-select {
      border-radius: 4px;
    }
    
    .arco-btn {
      border-radius: 4px;
    }
  }
}

.search-result-info {
  color: var(--color-text-2);
  font-size: 14px;
  
  strong {
    color: var(--color-text-1);
    font-weight: 600;
  }
}
</style> 