<template>
  <Page :left="leftFuns">
    <IxForm :control="searchForm" class="search-form" layout="inline" @submit.prevent="searchHandler">
      <IxFormItem :gutter="[0, 10]" align="center" label="用户昵称">
        <IxInput control="nickname" placeholder="请输入用户昵称"></IxInput>
      </IxFormItem>
      <IxFormItem :gutter="[0, 10]" label="账号">
        <IxInput control="username" placeholder="请输入账号"></IxInput>
      </IxFormItem>
      <button style="display: none" type="submit"/>
    </IxForm>
    <IxTable
        v-model:selectedRowKeys="selectedRowKeys"
        :columns="columns"
        :dataSource="datasource"
        :pagination="false"
        :scroll="{height:'50rem'}"
        :spin="tableSpin"
        class="list-table">
      <template #action="{record}">
        <IxButtonGroup :gap="16" mode="link">
          <IxButton @click="lookup(record)">查看</IxButton>
          <IxButton @click="modify(record)">修改</IxButton>
          <IxPopconfirm :title="'是否删除用户：【' + (record.nickname ?? record.username )+ '】？'" placement="top" @ok="del(record)">
            <IxButton>删除</IxButton>
          </IxPopconfirm>
        </IxButtonGroup>
      </template>
      <template #avatar="{record}">
        <img v-if="!record.avatar" :src="defaultAvatar" alt="头像" style="width: 2rem">
        <img v-else :src="AppApi.fileUrl(record.avatar)" alt="头像" style="width: 2rem">
      </template>
    </IxTable>
    <IxRow justify="end">
      <IxPagination v-model:pageIndex="pagination.current" v-model:pageSize="pagination.size" :total="pagination.total"
          class="pagination"
          show-quick-jumper
          show-size-changer show-total @change="pagingChangeHandler"/>
    </IxRow>
    <IxModal v-model:visible="visibleDialog" title="删除提醒" type="confirm" @ok="confirmDelHandler">
      <p>是否删除已选数据？</p>
    </IxModal>
  </Page>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

import { VKey } from '@idux/cdk/utils'
import { TableColumn } from '@idux/components/table'
import Page from '@/components/page/Page.vue'
import { useFormGroup } from '@idux/cdk'
import nav from '@/common/router/nav.ts'
import { TreeSelectNode } from '@idux/components/tree-select/src/types'
import Toast from '@/components/toast'
import UserApi from '@/pages/sys/user/user-api.ts'
import defaultAvatar from '@/assets/images/avatar.png'
import { useUserDetailStore } from '@/pages/sys/user/user-detail/user-detail-store.ts'
import AppApi from '@/common/app/app-api.ts'

const searchForm = useFormGroup<UserTypes.SearchForm>({
  nickname: [ undefined ],
  username: [ undefined ],
})
const visibleDialog = ref(false)
const tableSpin = ref(false)
const selectedRowKeys = ref<VKey[]>([])
const pagination = reactive<G.Pagination>({
  current: 1,
  size: 100,
  total: 0,
})
const datasource = ref<TreeSelectNode[]>()

const columns: TableColumn<UserTypes.SysUser>[] = [
  {
    type: 'selectable',
  },
  {
    title: '头像',
    dataKey: 'avatar',
    customCell: 'avatar'
  },
  {
    title: '用户昵称',
    dataKey: 'nickname',
  },
  {
    title: '性别',
    dataKey: 'genderTxt',
  },
  {
    title: '用户名',
    dataKey: [ 'account', 'username' ],
  },
  {
    title: '手机号',
    dataKey: [ 'account', 'phone' ],
  },
  {
    title: '邮箱',
    dataKey: [ 'account', 'email' ],
  },
  {
    title: '操作',
    key: 'action',
    customCell: 'action',
  },
]
const leftFuns = computed<PageTypes.Fun[]>(() => {
  return [
    {
      title: '删除',
      mode: 'text',
      icon: 'delete',
      danger: true,
      disabled: selectedRowKeys.value.length === 0,
      onClick() {
        visibleDialog.value = true
      }
    },
    {
      title: '新建',
      mode: 'text',
      icon: 'plus',
      onClick() {
        nav.open('user-create')
      }
    },
    {
      title: '搜索',
      mode: 'text',
      icon: 'search',
      onClick() {
        pageList()
      }
    },
    {
      title: '重置',
      mode: 'text',
      icon: 'search',
      onClick() {
        searchForm.reset()
        searchHandler()
      }
    },
    {
      title: '刷新',
      mode: 'text',
      icon: 'reload',
      onClick() {
        searchHandler()
      }
    },
  ]
})

function searchHandler() {
  pageList()
}

function confirmDelHandler() {
  const recode = selectedRowKeys.value.map(it => ({id: it as string}))
  del(...recode)
}

function pageList() {
  tableSpin.value = true
  UserApi.paging({...searchForm.getValue(), ...pagination})
      .then(res => {
        pagination.current = res.data.current
        pagination.size = res.data.size
        pagination.total = res.data.total
        datasource.value = res.data.records.map(it => {
          return {
            key: it.id,
            ...it
          }
        })
      })
      .finally(() => {
        tableSpin.value = false
      })
}

function pagingChangeHandler() {
  pageList()
}

function del(...recode: { id: string }[]) {
  const toastId = Toast.loading('正在提交')
  UserApi.del(recode.map(it => it.id))
      .then(_ => {
        Toast.success('删除成功')
        pageList()
      })
      .finally(() => {
        Toast.close(toastId)
      })
}


const detailStore = useUserDetailStore()


function modify(recode: UserTypes.SysUser) {
  detailStore.$patch({
    id: recode.id,
    edit: true
  })
  nav.open('user-detail')
}

function lookup(recode: UserTypes.SysUser) {
  detailStore.$patch({
    id: recode.id,
    edit: false
  })
  nav.open('user-detail')
}

pageList()

</script>

<style lang="stylus" scoped>
.search-form {
  padding 1rem
  margin 1rem 0
}

.list-table {
  margin 1rem

}


.pagination {
  margin-right: 1rem;
}
</style>
