<template>
  <div class="cattle-academy-container">
    <div class="header">
      <a-button type="primary" @click="handleNewInfo">新增资讯</a-button>
      <a-input-search
        placeholder="搜索标题或作者"
        style="width: 300px; margin-left: 16px;"
        @search="handleSearch"
        v-model:value="searchKeyword"
      />
    </div>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'coverImage'">
          <img :src="record.coverImage" alt="封面图" class="cover-image" />
        </template>
        <template v-if="column.key === 'status'">
          <a-switch 
            :checked="record.status" 
            @change="(checked) => handleToggleStatus(record, checked)"
          />
        </template>
        <template v-if="column.key === 'operations'">
          <a-space>
            <a @click="handleView(record)">查看</a>
            <a @click="handleEdit(record)">编辑</a>
            <a @click="handleDelete(record)" style="color: #ff4d4f;">删除</a>
          </a-space>
        </template>
      </template>
    </a-table>
    
    <!-- 新增/编辑表单 -->
    <a-modal
      v-model:open="isModalOpen"
      :title="currentInfo.id ? '编辑资讯' : '新增资讯'"
      @ok="handleSave"
      @cancel="handleCancel"
      :width="800"
      :confirm-loading="modalLoading"
    >
      <a-form
        :model="currentInfo"
        layout="vertical"
        :rules="formRules"
        ref="formRef"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="标题" name="title">
              <a-input v-model:value="currentInfo.title" placeholder="请输入标题" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="分类" name="category">
              <a-select v-model:value="currentInfo.category" placeholder="请选择分类">
                <a-select-option value="技术资讯">技术资讯</a-select-option>
                <a-select-option value="养殖技术">养殖技术</a-select-option>
                <a-select-option value="健康管理">健康管理</a-select-option>
                <a-select-option value="营养管理">营养管理</a-select-option>
                <a-select-option value="智能设备">智能设备</a-select-option>
                <a-select-option value="环保管理">环保管理</a-select-option>
                <a-select-option value="繁殖技术">繁殖技术</a-select-option>
                <a-select-option value="经营管理">经营管理</a-select-option>
                <a-select-option value="市场分析">市场分析</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="作者" name="author">
              <a-input v-model:value="currentInfo.author" placeholder="请输入作者" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="排序" name="sort">
              <a-input-number v-model:value="currentInfo.sort" placeholder="请输入排序" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="封面图URL" name="coverImage">
          <a-input v-model:value="currentInfo.coverImage" placeholder="请输入封面图URL" />
        </a-form-item>
        
        <a-form-item label="摘要" name="summary">
          <a-textarea v-model:value="currentInfo.summary" placeholder="请输入摘要" :rows="3" />
        </a-form-item>
        
        <a-form-item label="内容" name="content">
          <a-textarea v-model:value="currentInfo.content" placeholder="请输入内容" :rows="6" />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="是否置顶">
              <a-switch v-model:checked="currentInfo.isTop" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="是否推荐">
              <a-switch v-model:checked="currentInfo.isRecommend" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="状态">
              <a-switch v-model:checked="currentInfo.status" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="备注" name="remarks">
          <a-textarea v-model:value="currentInfo.remarks" placeholder="请输入备注" :rows="2" />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 详情查看 -->
    <a-modal
      v-model:open="isDetailModalOpen"
      title="资讯详情"
      :footer="null"
      :width="800"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="标题">{{ detailData.title }}</a-descriptions-item>
        <a-descriptions-item label="分类">{{ detailData.category }}</a-descriptions-item>
        <a-descriptions-item label="作者">{{ detailData.author }}</a-descriptions-item>
        <a-descriptions-item label="排序">{{ detailData.sort }}</a-descriptions-item>
        <a-descriptions-item label="浏览次数">{{ detailData.viewCount }}</a-descriptions-item>
        <a-descriptions-item label="发布时间">{{ detailData.publishTime }}</a-descriptions-item>
        <a-descriptions-item label="是否置顶">
          <a-tag :color="detailData.isTop ? 'red' : 'default'">
            {{ detailData.isTop ? '是' : '否' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="是否推荐">
          <a-tag :color="detailData.isRecommend ? 'green' : 'default'">
            {{ detailData.isRecommend ? '是' : '否' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="detailData.status ? 'green' : 'red'">
            {{ detailData.status ? '启用' : '禁用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ detailData.createdAt }}</a-descriptions-item>
        <a-descriptions-item label="封面图" :span="2">
          <img v-if="detailData.coverImage" :src="detailData.coverImage" alt="封面图" class="cover-image" />
        </a-descriptions-item>
        <a-descriptions-item label="摘要" :span="2">{{ detailData.summary }}</a-descriptions-item>
        <a-descriptions-item label="内容" :span="2">{{ detailData.content }}</a-descriptions-item>
        <a-descriptions-item label="备注" :span="2">{{ detailData.remarks }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import cattleAcademyApi from '@/utils/cattleAcademyApi';

const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    width: 200,
    ellipsis: true
  },
  {
    title: '封面图',
    dataIndex: 'coverImage',
    key: 'coverImage',
    width: 100
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 100
  },
  {
    title: '作者',
    dataIndex: 'author',
    key: 'author',
    width: 100
  },
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
    width: 80
  },
  {
    title: '浏览次数',
    dataIndex: 'viewCount',
    key: 'viewCount',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150
  },
  {
    title: '操作',
    key: 'operations',
    width: 150,
    fixed: 'right'
  },
];

const dataSource = ref([]);
const loading = ref(false);
const searchKeyword = ref('');

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// 模态框状态
const isModalOpen = ref(false);
const isDetailModalOpen = ref(false);
const modalLoading = ref(false);

// 表单引用
const formRef = ref(null);

// 当前编辑的资讯
const currentInfo = reactive({
  id: '',
  title: '',
  coverImage: '',
  content: '',
  summary: '',
  category: '',
  sort: 0,
  status: true,
  author: '',
  publishTime: null,
  isTop: false,
  isRecommend: false,
  remarks: ''
});

// 详情数据
const detailData = reactive({});

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ]
};

// 获取资讯列表
const fetchCattleAcademyList = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      title: searchKeyword.value,
      author: searchKeyword.value
    };
    
    const response = await cattleAcademyApi.getCattleAcademyList(params);
    if (response.code === 200) {
      dataSource.value = response.data.list;
      pagination.total = response.data.total;
    } else {
      message.error(response.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取资讯列表失败:', error);
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchCattleAcademyList();
};

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchCattleAcademyList();
};

// 新增资讯
const handleNewInfo = () => {
  Object.assign(currentInfo, {
    id: '',
    title: '',
    coverImage: '',
    content: '',
    summary: '',
    category: '',
    sort: 0,
    status: true,
    author: '',
    publishTime: new Date(),
    isTop: false,
    isRecommend: false,
    remarks: ''
  });
  isModalOpen.value = true;
};

// 编辑资讯
const handleEdit = (record) => {
  Object.assign(currentInfo, {
    ...record,
    publishTime: record.publishTime ? new Date(record.publishTime) : new Date()
  });
  isModalOpen.value = true;
};

// 查看详情
const handleView = async (record) => {
  try {
    const response = await cattleAcademyApi.getCattleAcademyById(record.id);
    if (response.code === 200) {
      Object.assign(detailData, response.data);
      isDetailModalOpen.value = true;
    } else {
      message.error(response.message || '获取详情失败');
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    message.error('获取详情失败');
  }
};

// 删除资讯
const handleDelete = async (record) => {
  try {
    const response = await cattleAcademyApi.deleteCattleAcademy(record.id);
    if (response.code === 200) {
      message.success('删除成功');
      fetchCattleAcademyList();
    } else {
      message.error(response.message || '删除失败');
    }
  } catch (error) {
    console.error('删除资讯失败:', error);
    message.error('删除失败');
  }
};

// 切换状态
const handleToggleStatus = async (record, checked) => {
  try {
    const response = await cattleAcademyApi.toggleCattleAcademyStatus(record.id, checked);
    if (response.code === 200) {
      message.success('状态更新成功');
      fetchCattleAcademyList();
    } else {
      message.error(response.message || '状态更新失败');
    }
  } catch (error) {
    console.error('切换状态失败:', error);
    message.error('状态更新失败');
  }
};

// 保存资讯
const handleSave = async () => {
  try {
    await formRef.value.validate();
    modalLoading.value = true;
    
    const data = {
      ...currentInfo,
      publishTime: currentInfo.publishTime ? currentInfo.publishTime.toISOString() : new Date().toISOString()
    };
    
    let response;
    if (currentInfo.id) {
      response = await cattleAcademyApi.updateCattleAcademy(currentInfo.id, data);
    } else {
      response = await cattleAcademyApi.createCattleAcademy(data);
    }
    
    if (response.code === 200 || response.code === 201) {
      message.success(currentInfo.id ? '更新成功' : '创建成功');
      isModalOpen.value = false;
      fetchCattleAcademyList();
    } else {
      message.error(response.message || '保存失败');
    }
  } catch (error) {
    console.error('保存资讯失败:', error);
    message.error('保存失败');
  } finally {
    modalLoading.value = false;
  }
};

// 取消
const handleCancel = () => {
  isModalOpen.value = false;
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCattleAcademyList();
});
</script>

<style scoped>
.cattle-academy-container {
  padding: 24px;
}

.header {
  margin-bottom: 16px;
}

.cover-image {
  width: 100px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}
</style>