<template>
  <div class="supply-demand-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-s-comment"></i>
        供需管理
      </h2>
      <div>
        <el-tag type="danger">{{ pendingCount }}</el-tag>
        <small class="text-muted">待审核</small>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="filters" inline>
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="搜索标题" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filters.status" placeholder="全部状态" clearable>
            <el-option label="待审核" value="0"></el-option>
            <el-option label="已通过" value="1"></el-option>
            <el-option label="已拒绝" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filters.type" placeholder="全部类型" clearable>
            <el-option label="供应" value="1"></el-option>
            <el-option label="需求" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker v-model="filters.date" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-download" @click="handleExport">导出数据</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 供需列表表格 -->
    <div class="table-container">
      <el-table
        :data="list"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column label="供需信息" min-width="250">
          <template slot-scope="scope">
            <div class="supply-title">{{ scope.row.title }}</div>
            <div class="supply-desc">{{ scope.row.content }}</div>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type === 1 ? 'success' : 'primary'" size="small">
              {{ scope.row.type === 1 ? '供应' : '需求' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布者" width="150">
          <template slot-scope="scope">
            <div class="user-info">
              <div class="user-avatar">{{ (scope.row.user && scope.row.user.name && scope.row.user.name.charAt(0)) || 'U' }}</div>
              <div>
                <div class="user-name">{{ (scope.row.user && scope.row.user.name) || '-' }}</div>
                <div class="user-year">{{ (scope.row.user && scope.row.user.company_position) || '-' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" width="150">
          <template slot-scope="scope">
            <div v-if="scope.row.mobile" class="contact-info">
              <div>手机: {{ scope.row.mobile }}</div>
            </div>
            <div v-else-if="scope.row.wechat" class="contact-info">
              <div>微信: {{ scope.row.wechat }}</div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="150">
          <template slot-scope="scope">
            <div class="time-display">{{ formatDate(scope.row.created_at) }}</div>
            <div class="time-display-secondary">{{ formatTime(scope.row.created_at) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170" fixed="right">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button v-if="scope.row.status === 0 || scope.row.status === 2" type="success" size="mini" icon="el-icon-check" @click="handleApprove(scope.row)">通过</el-button>
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button v-if="scope.row.status === 0" type="danger" size="mini" icon="el-icon-close" @click="handleReject(scope.row)">拒绝</el-button>
              <el-button type="info" size="mini" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 详情弹窗 -->
    <SupplyDemandDetail
      :visible.sync="showDetailDialog"
      :detail="currentDetail"
      :readonly="true"
    />
    <SupplyDemandEdit
      :visible.sync="showEditDialog"
      :detail="currentDetail"
      @save="handleEditSave"
    />
  </div>
</template>

<script>
import { supplyDemandList, supplyDemandSave } from '@/api/student/index.js'
// 详情弹窗组件
import SupplyDemandDetail from './components/SupplyDemandDetail.vue'
import SupplyDemandEdit from './components/SupplyDemandEdit.vue'
export default {
  name: 'SupplyDemand',
  components: { SupplyDemandDetail, SupplyDemandEdit },
  data() {
    return {
      pendingCount: 0,
      filters: {
        keyword: '',
        status: '',
        type: '',
        date: ''
      },
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10
      },
      multipleSelection: [],
      showDetailDialog: false,
      currentDetail: null,
      showEditDialog: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      // 构造filter数组
      const filter = []
      if (this.filters.keyword) filter.push({ key: 'title', op: 'like', value: this.filters.keyword })
      if (this.filters.status) filter.push({ key: 'status', op: 'eq', value: this.filters.status })
      if (this.filters.type) filter.push({ key: 'type', op: 'eq', value: this.filters.type })
      if (this.filters.date) {
        let dateStr = this.filters.date
        if (dateStr instanceof Date) {
          const local = new Date(dateStr.getTime() + 8 * 60 * 60 * 1000)
          dateStr = local.toISOString().slice(0, 10)
        } else if (typeof dateStr === 'string' && dateStr.length > 10) {
          dateStr = dateStr.slice(0, 10)
        }
        filter.push({ key: 'created_at', op: 'like', value: dateStr })
      }
      // 构造扁平化参数
      const params = {
        page: this.listQuery.page,
        page_size: this.listQuery.limit
      }
      filter.forEach((item, idx) => {
        params[`filter[${idx}][key]`] = item.key
        params[`filter[${idx}][op]`] = item.op
        params[`filter[${idx}][value]`] = item.value
      })
      const res = await supplyDemandList(params)
      // 根据接口返回结构处理数据
      this.list = res.data || []
      this.total = res.total || 0
      // 计算待审核数量（status为0的项）
      this.pendingCount = this.list.filter(item => item.status === 0).length
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleExport() {
      // 可根据需要实现导出逻辑
      this.$message.info('数据导出中...')
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getStatusTagType(status) {
      const statusMap = {
        0: 'warning', // 待审核
        1: 'success', // 已通过
        2: 'danger' // 已拒绝
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusText = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝'
      }
      return statusText[status] || '未知'
    },
    async handleApprove(row) {
      try {
        await supplyDemandSave({ id: row.id, status: 1 })
        this.$message.success('审核通过成功！')
        this.getList()
      } catch (e) {
        this.$message.error('操作失败')
      }
    },
    handleEdit(row) {
      this.currentDetail = row
      this.showEditDialog = true
      this.showDetailDialog = false
    },
    async handleEditSave(form) {
      try {
        await supplyDemandSave(form)
        this.$message.success('保存成功')
        this.getList()
      } catch (e) {
        this.$message.error('保存失败')
      }
    },
    async handleReject(row) {
      try {
        await supplyDemandSave({ id: row.id, status: 2 })
        this.$message.success('已拒绝该供需信息！')
        this.getList()
      } catch (e) {
        this.$message.error('操作失败')
      }
    },
    handleView(row) {
      this.currentDetail = row
      this.showDetailDialog = true
      this.showEditDialog = false
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    formatDate(date) {
      if (!date) return '-'
      return date.split(' ')[0]
    },
    formatTime(date) {
      if (!date) return '-'
      const timePart = date.split(' ')[1]
      return timePart ? timePart.substring(0, 5) : '-'
    }
  }
}
</script>

<style lang="scss" scoped>
.supply-demand-container {
  padding: 20px;
  background-color: #fff;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #e9ecef;

  .page-title {
    font-size: 24px;
    font-weight: bold;
    color: #2c3e50;
    display: flex;
    align-items: center;
    margin: 0;

    i {
      margin-right: 10px;
      color: #3498db;
    }
  }

  .text-muted {
    margin-left: 5px;
    color: #6c757d;
  }
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.supply-title {
  font-weight: 600;
  color: #2c3e50;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.supply-desc {
  font-size: 12px;
  color: #6c757d;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  font-weight: 600;
}

.user-name {
  font-size: 12px;
  font-weight: 600;
}

.user-year {
  font-size: 11px;
  color: #666;
}

.contact-info {
  font-size: 12px;
  color: #666;
}

.time-display {
  font-size: 12px;
}

.time-display-secondary {
  font-size: 11px;
  color: #666;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;

  .el-button {
    margin: 0;
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px 0;
}
</style>
