<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getUserListApi,
  saveUserApi,
  delUserListApi,
  delUserApi,
  queryUserApi,
  resetPassword,
  resetPasswordbatch,
  getUserDictApi
} from '@/api/auth/user'
import { TableData } from '@/api/auth/user/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  ElButton,
  ElLink,
  ElLoading,
  ElTag,
  ElMessageBox,
  ElMessage,
  ElPopconfirm
} from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import type { ListItem } from '@/api/dict/types'
import { findDictLabel, findListLabel } from '@/utils'
import { getOrganTree } from '@/api/common'

const { t } = useI18n()

const ids = ref<string[]>([])

const ORGAN_LIST = ref<any[]>([])

const SEX_DICT_LIST: ListItem[] = [
  { label: '男', value: '0' },
  { label: '女', value: '1' }
]

const { tableRegister, tableState, tableMethods } = useTable({
  fetchInitParamsApi: async () => {
    const res = await getUserDictApi()
    if (res) {
      ORGAN_LIST.value = res.data.data.ORGAN_LIST
    }
  },
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getUserListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      type: 3, // 固定参数
      ...unref(searchParams)
    })
    return {
      list: res.data.list.map((item: TableData) => {
        return {
          ...item,
          organName: findDictLabel(ORGAN_LIST.value, item.organId)
        }
      }),
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delUserListApi(unref(ids))
    return !!res
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList, refresh } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'username',
    label: t('userDemo.username')
  },
  {
    field: 'name',
    label: t('userDemo.name'),
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
              {data.row?.name}
            </ElLink>
          </>
        )
      }
    }
  },
  {
    field: 'organName',
    label: t('userDemo.organName')
  },
  {
    field: 'sex',
    label: t('userDemo.sex'),
    slots: {
      default: (data: any) => {
        return <>{findListLabel(SEX_DICT_LIST, data.row.sex)}</>
      }
    }
  },
  {
    field: 'roles',
    label: t('userDemo.roles'),
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row?.roles?.split(',').map((item: string) => (
              <ElTag class="mr-2" type="">
                {item}
              </ElTag>
            ))}
          </>
        )
      }
    }
  },
  {
    field: 'email',
    label: t('userDemo.email')
  },
  {
    field: 'mobile',
    label: t('userDemo.mobile')
  },
  {
    field: 'loginIp',
    label: t('userDemo.loginIp')
  },
  {
    field: 'logindate',
    label: t('userDemo.logindate')
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 200,
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
              {t('exampleDemo.edit')}
            </ElLink>
            <ElLink type="primary" underline={false} onClick={() => onResetPassword(data.row)}>
              {t('userDemo.resetPassword')}
            </ElLink>
            <ElPopconfirm
              title={t('common.delTableMsg')}
              width={200}
              v-slots={{
                reference: () => {
                  return (
                    <>
                      <ElLink type="primary" underline={false}>
                        {t('exampleDemo.del')}
                      </ElLink>
                    </>
                  )
                }
              }}
              onConfirm={() => onDelData(data.row)}
            ></ElPopconfirm>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'deptname',
    label: t('userDemo.deptname'),
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'key',
      props: {
        label: 'title',
        children: 'children'
      }
    },
    optionApi: async () => {
      const res = await getOrganTree()
      return res
    }
  },
  {
    field: 'username',
    label: t('userDemo.username'),
    component: 'Input'
  },
  {
    field: 'name',
    label: t('userDemo.name'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const action = async (row: any, type: string) => {
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await queryUserApi(row.id)
    .catch(() => {})
    .finally(() => {
      detailLoading.close()
    })
  detailLoading.close()
  if (res) {
    const { entry, userRoles } = res.data.data
    dialogVisible.value = true
    dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
    actionType.value = type
    let data
    if (type === 'detail') {
      // 详情
      data = { ...entry, organName: row.organName, roles: row.roles }
    } else {
      // 编辑
      data = {
        id: entry.id,
        username: entry.username,
        name: entry.name,
        organId: entry.organId,
        sex: entry.sex,
        email: entry.email,
        mobile: entry.mobile,
        roleIds: userRoles.map((item: any) => item.id)
      }
    }
    console.log(entry, data)
    currentRow.value = data
  }
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveUserApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

const delLoading = ref(false)

/** 批量删除 */
const onDelDataBatch = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

/** 删除 */
const onDelData = async (row: TableData) => {
  const res = await delUserApi(row.id)
  if (res) {
    const { code, msg } = res.data ?? res
    if (code === 1) {
      ElMessage.success('删除成功!')
      getList()
    } else {
      ElMessage.error(msg || '删除失败!')
    }
  }
}

const disabled = ref(true)

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0
}

/** 批量重置密码 */
const onResetPasswordBatch = async () => {
  const elTableExpose = await getElTableExpose()
  ids.value = elTableExpose?.getSelectionRows().map((v: TableData) => v.id)
  ElMessageBox.confirm(
    t('userDemo.resetPasswordBatchMessage'),
    t('userDemo.resetPasswordBatchReminder'),
    {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    }
  ).then(async () => {
    const res = await resetPasswordbatch(unref(ids))
    if (res) {
      const { code } = res.data
      if (code === 1) {
        ElMessage.success('重置成功!')
      } else {
        ElMessage.error('重置密码失败!')
      }
    }
  })
}

/** 重置密码 */
const onResetPassword = async (row: TableData) => {
  ElMessageBox.confirm(t('userDemo.resetPasswordMessage'), t('userDemo.resetPasswordReminder'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(async () => {
    const res = await resetPassword(row.id)
    if (res) {
      const { code } = res.data
      if (code === 1) {
        ElMessage.success('重置成功!')
      } else {
        ElMessage.error('重置密码失败!')
      }
    }
  })
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <Table
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @selection-change="onSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
    >
      <template #buttons>
        <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton>
        <ElButton
          :loading="delLoading"
          type="primary"
          :disabled="disabled"
          @click="onResetPasswordBatch()"
        >
          {{ t('userDemo.resetPassword') }}
        </ElButton>
        <ElButton
          :loading="delLoading"
          type="primary"
          :disabled="disabled"
          @click="onDelDataBatch(null)"
        >
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />

    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
