<template>
  <BodyPanlHeader>
    <a-button type="primary" @click="setMember()">新增成员</a-button>
    <div>
      <a-input-search
        v-model:value="params.userName"
        style="width: 280px"
        placeholder="请输入成员名称"
        allow-clear
        @search="updateList"
      />
    </div>
  </BodyPanlHeader>

  <BodyPanlBody>
    <a-table
      :data-source="list"
      :columns="memberColumns"
      :pagination="pagination"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div class="table-actions">
            <a @click="setMember(record)">修改</a>
            <!-- <a>查看</a> -->
            <a class="warn" @click="delMemberHandler(record)">删除</a>
          </div>
        </template>
      </template>
    </a-table>
  </BodyPanlBody>
</template>

<script lang="ts" setup>
import EditMember from './edit.vue'
import { computed, reactive, watchEffect } from 'vue'
import { BodyPanlHeader, BodyPanlBody } from '@/layout/panl'
import { usePaging } from '@/hook'
import { router } from '@/router'
import { renderModal } from '@/helper'
import { memberColumns as baseColumns } from './columns'
import { Modal } from 'ant-design-vue'
import {
  fetchMembers,
  checkMemberUserName,
  addMember,
  updateMember,
  deleteMember
} from '@/api'

import type { Member } from '@/api'

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

const params = reactive({
  userName: '',
  projectId: computed(() => Number(router.currentRoute.value.params.id))
})

const { list, pagination, updateList } = usePaging(fetchMembers, params, {
  pageSize: 7
})

const setMember = (member?: Member) => {
  renderModal(EditMember, {
    member,
    async onSave(member) {
      if (member.teamId) {
        await updateMember(member as Member)
      } else {
        await checkMemberUserName(member.userName)
        await addMember(params.projectId, member)
      }
      await updateList()
    }
  })
}
const delMemberHandler = (member: Member) => {
  Modal.confirm({
    content: '确定要删除此用户？',
    title: '系统提示',
    width: '400px',
    okText: '删除',
    icon: null,
    cancelText: '取消',
    onOk: async () => {
      await deleteMember(member.teamId)
      await updateList()
    }
  })
}
</script>
