<template>
  <div>
    <!-- 搜索条件：主题、会议状态、会议时间（时间段）、选择OKR节点 -->
    <el-form :model="searchForm" inline label-width="0">
      <el-form-item>
        <el-input
          v-model="searchForm.meetingSubject"
          placeholder="会议主题"
          style="width: 200px"
          clearable
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="searchForm.creator"
          placeholder="发起人"
          style="width: 120px"
          clearable
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="searchForm.status"
          placeholder="会议状态"
          style="width: 150px"
          @change="handleSearch"
        >
          <el-option label="未开始" value="1" />
          <el-option label="已结束" value="2" />
          <el-option label="已取消" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="会议时间"
          end-placeholder="会议时间"
          @change="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-tree-select
          v-model="searchForm.nodeId"
          :data="peroidList"
          :props="defaultProps"
          :render-after-expand="false"
          :default-expand-all="false"
          check-strictly
          placeholder="选择OKR节点"
          style="width: 300px"
          clearable
          @change="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearch">查询</el-button>
        <el-button type="primary" @click="handleAdd">预约会议</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableList" v-loading="loading" border stripe>
      <el-table-column prop="meetingSubject" label="会议主题" />
      <el-table-column prop="startTime" label="会议时间" width="170px" />
      <el-table-column prop="meetingRoom" label="会议地点" width="140px" />
      <el-table-column prop="expectEndTime" label="预计结束时间" width="170px" />
      <el-table-column prop="expectUserName" label="预约参会人员" />
      <el-table-column prop="actualUserName" label="实际参会人员" />
      <el-table-column prop="nodeName" label="关联OKR节点" width="150px" />
      <el-table-column prop="status" label="会议状态" width="100px">
        <template #default="{ row }">
          <el-tag :type="['', 'info', 'success', 'warning'][row.status]" size="small">
            {{ ['', '未开始', '已结束', '已取消'][row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="140">
        <template #default="{ row }">
          <template v-if="row.status == 1 && row.creator == currentUserId">
            <el-button type="primary" style="padding: 0" text @click="handleEdit(row.meetingId)">
              修改
            </el-button>
            <el-button type="danger" text style="padding: 0" @click="handleCancel(row)">
              取消
            </el-button>
          </template>
          <el-button
            v-else
            type="primary"
            style="padding: 0"
            text
            @click="handleDetail(row.meetingId)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="searchForm.pageSize"
      v-model:page="searchForm.pageNo"
      :total="total"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="Meeting">
import { listToTree } from '@/utils/tree'
import { useUserStore } from '@/store/modules/user'
import { getAllNodeTree } from '@/api/okr/okr'
import * as MeetingApi from '@/api/okr/meeting'

const currentUserId = useUserStore().getUser.id

const defaultProps = {
  value: 'nodeId',
  label: 'nodeName',
  children: 'children'
}
const message = useMessage()

const searchForm = ref({
  meetingSubject: undefined,
  creator: undefined,
  status: '1',
  dateRange: [],
  nodeId: undefined,
  pageNo: 1,
  pageSize: 50
})
const total = ref(0)

onMounted(() => {
  getOptions()
  handleSearch()
})

const peroidList = ref([])
function getOptions() {
  // 获取OKR节点数据
  getAllNodeTree().then((resp) => {
    peroidList.value = listToTree(resp?.tree || [], {
      id: 'nodeId',
      pid: 'parentId',
      children: 'children'
    })
  })
}

const loading = ref(false)
const tableList = ref([])
const handleSearch = () => {
  searchForm.value.pageNo = 1
  getList()
}

function getList() {
  loading.value = true
  // 获取会议列表
  try {
    const params = { ...searchForm.value }
    if (params.dateRange && params.dateRange.length) {
      params.startTime = params.dateRange[0] + ' 00:00:00'
      params.endTime = params.dateRange[1] + ' 23:59:59'
      delete params.dateRange
    } else {
      delete params.startTime
      delete params.endTime
    }
    MeetingApi.getMeetingPage(params)
      .then((resp) => {
        tableList.value = resp.list || []
        total.value = resp.total || 0
      })
      .finally(() => {
        loading.value = false
      })
  } catch (error) {
    console.error('获取会议列表失败:', error)
    loading.value = false
  }
}

const router = useRouter()

const handleAdd = () => {
  router.push({ name: 'MeetingInfo', params: { id: 0 } })
}

const handleEdit = (id) => {
  router.push({
    name: `MeetingInfo`,
    params: {
      id
    }
  })
}

const handleDetail = (id) => {
  router.push({
    name: `MeetingInfo`,
    params: {
      id
    },
    query: {
      isDetail: 1
    }
  })
}

const handleCancel = async (row) => {
  try {
    await message.confirm('是否确认取消该会议？')
    // 取消会议操作
    await MeetingApi.cancelMeeting({ meetingId: row.meetingId })
    message.success('会议取消成功')
    getList() // 刷新列表
  } catch (error) {
    console.log('取消操作被用户拒绝', error)
  }
}
</script>

<style lang="scss" scoped></style>
