<template>
  <BodyPanlHeader>
    <a-button type="primary" @click="addMaterial()">新建备注</a-button>
    <div>
      <a-input-search
        v-model:value="filterName"
        style="width: 280px"
        placeholder="请输入笔记名称"
        @search="updateMaterials"
      />
    </div>
  </BodyPanlHeader>

  <BodyPanlBody>
    <a-table
      :data-source="materials"
      :columns="materialColumns"
      :pagination="pagination"
    >
      <template #bodyCell="{ column }">
        <template v-if="column.key === 'action'">
          <div class="table-actions">
            <a>查看</a>
          </div>
        </template>
      </template>
    </a-table>
  </BodyPanlBody>
</template>

<script lang="ts" setup>
import EditMember from './edit.vue'
import { ref, reactive, computed } from 'vue'
import { BodyPanlHeader, BodyPanlBody } from '@/layout/panl'
import { useRealtime } from '@/hook'
import { router } from '@/router'
import { renderModal } from '@/helper'
import { materialColumns as baseColumns } from './columns'
import {
  fetchMembers,
  checkMemberUserName,
  addMember,
  updateMember
} from '@/api'

import type { Member } from '@/api'

const materialColumns = [
  ...baseColumns,
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action'
  }
]

const filterName = ref('')
const projectId = computed(() => Number(router.currentRoute.value.params.id))
const pagination = reactive({
  current: 1,
  total: 0,
  pageSize: 12,
  onChange: (current: number) => {
    pagination.current = current
    updateMaterials()
  }
})

const [materials, updateMaterials] = useRealtime(async () => {
  const result = await fetchMembers({
    userName: filterName.value,
    projectId: projectId.value,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  })
  pagination.total = result.total
  return result.list
}, [])

const addMaterial = () => {
  renderModal(EditMember, {
    async onSave(member) {
      if (member.teamId) {
        await updateMember(member as Member)
      } else {
        await checkMemberUserName(member.userName)
        await addMember(projectId.value, member)
      }
      await updateMaterials()
    }
  })
}
</script>
