<template>
  <BodyPanlHeader>
    <a-button type="primary" @click="addMaterial()">{{
      $t('material.addMertial')
    }}</a-button>
    <div>
      <a-input-search
        v-model:value="filterName"
        style="width: 280px"
        :placeholder="$t('material.filterName')"
        @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>{{ $t('sys.query') }}</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,
  SetMemberProps
} from '@/api'

import type { Member } from '@/api'
import { ui18n } from '@/lang'

const materialColumns = [
  ...baseColumns,
  {
    title: ui18n.t('sys.oper'),
    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 params = reactive({
  userName: '',
  projectId: computed(() => Number(router.currentRoute.value.params.id))
})

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