<template>
  <Page :left="leftFuns">
    <UserForm ref="formIns" :status="formStatus"/>
  </Page>
</template>

<script lang="ts" setup>
import Page from '@/components/page/Page.vue'
import Nav from '@/common/router/nav.ts'
import Toast from '@/components/toast'
import UserForm from '@/pages/sys/user/user-form/UserForm.vue'
import UserApi from '@/pages/sys/user/user-api.ts'
import { useUserDetailStore } from '@/pages/sys/user/user-detail/user-detail-store.ts'

const detailStore = useUserDetailStore()

const formIns = ref<InstanceType<typeof UserForm> | null>(null)

const formStatus = computed<'create' | 'view' | 'edit'>(() => {
  return detailStore.edit ? 'edit' : 'view'
})

const leftFuns = computed<PageTypes.Fun[]>(() => {
  return [
    {
      title: '查看列表',
      mode: 'text',
      icon: 'view-list',
      onClick() {
        Nav.open('user')
      }
    },
    {
      title: detailStore.edit ? '提交' : '编辑',
      mode: 'text',
      icon: detailStore.edit ? 'check' : 'edit',
      onClick() {
        if (!detailStore.edit) {
          detailStore.$patch({edit: true})
          return
        }
        const value = formIns.value!.getValue()
        if (value == null) return
        const toastId = Toast.loading('正在提交')
        UserApi
            .modify({...value, id: detailStore.id!})
            .then(_ => {
              Toast.success('修改成功')
            })
            .finally(() => {
              Toast.close(toastId)
            })
      }
    },
  ]
})

onMounted(() => {
  UserApi.detail(detailStore.id!)
      .then(res => {
        formIns.value!.setValue(res.data)
      })
})
</script>

<style lang="stylus" scoped>

</style>
