<template>
  <BodyPanlHeader>
    <a-button type="primary" @click="setMember()">{{
      $t('material.add')
    }}</a-button>
    <div>
      <a-input-search
        v-model:value="params.userName"
        style="width: 280px"
        :placeholder="$t('material.ruleNickName')"
        allow-clear
        @search="updateList"
      />
    </div>
  </BodyPanlHeader>

  <BodyPanlBody>
    <a-table
      :data-source="list"
      :columns="memberColumns"
      :pagination="pagination"
      :scroll="{ x: '100%', y: 350 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div class="table-actions">
            <a @click="setMember(record)">{{ $t('sys.update') }}</a>
            <!-- <a>查看</a> -->
            <a class="warn" @click="delMemberHandler(record)">{{
              $t('sys.del')
            }}</a>
          </div>
        </template>
      </template>
    </a-table>
  </BodyPanlBody>
</template>

<script lang="ts" setup>
import EditMember from './edit.vue'
import { computed, onDeactivated, reactive, toRaw, watch } 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'
import { ui18n } from '@/lang'
import sys from '@/lang/en/sys'

const memberColumns = [
  ...baseColumns,
  {
    title: ui18n.t('sys.oper'),
    dataIndex: 'action',
    key: 'action'
  }
]

const params = reactive({
  userName: '',
  projectId: computed(() => Number(router.currentRoute.value.params.id))
})
onDeactivated(() => {
  params.userName = ''
})
const { list, pagination, updateList } = usePaging(fetchMembers, params)

watch(
  () => params.userName,
  () => (pagination.current = 1),
  { flush: 'sync' }
)
const setMember = (member?: Member) => {
  renderModal(EditMember, {
    member: member && {
      ...member,
      roles: member.roles.map(role => role.roleId)
    },
    async onSave(member) {
      if (member.teamId) {
        await updateMember({ ...member, teamId: member.teamId })
      } else {
        await checkMemberUserName(member.userName)
        await addMember({ ...member, projectId: params.projectId })
      }
      await updateList()
    }
  })
}
const delMemberHandler = (member: Member) => {
  Modal.confirm({
    content: ui18n.t('material.delTip'),
    title: ui18n.t('sys.tipTitle'),
    width: '400px',
    okText: ui18n.t('sys.del'),
    icon: null,
    cancelText: ui18n.t('sys.cancel'),
    onOk: async () => {
      try {
        await deleteMember(member.teamId)
        await updateList()
      } catch {}
    }
  })
}
</script>
