<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getSysUserListApi,
  saveSysUserApi,
  delSysUserListApi,
  delSysUserApi,
  querySysUserApi,
  exportExcelApi,
  organTreeApi,
  resetPasswordbatch,
  batchUpdateUser
} from '@/api/system/SysUser'
import { TableData } from '@/api/role/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  ElButton,
  ElLink,
  ElLoading,
  ElPopconfirm,
  ElMessage,
  ElTag,
  ElMessageBox
} 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 { STATUS_DICT_LIST } from './constants'
import SM4Util from '@/utils/sm4'
import { getLoginOrganCodeByUserInfo } from '@/utils/auth';

defineOptions({
  name: 'SysUser'
})

const { t } = useI18n()

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

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getSysUserListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.body.list,
      total: res.body.total
    }
  },
  fetchDelApi: async () => {
    const res = await delSysUserListApi(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: 'username',
    label: '登录号'
  },
  {
    field: 'name',
    label: '用户姓名'
  },
  {
    field: 'organId',
    label: '机构号'
  },
  {
    field: 'orgname',
    label: '机构名称'
  },
  {
    field: 'roleName',
    label: '角色',
    formatter: (row: Recordable, __: TableColumn) => {
      return row.roleName?.split(',').map((item, i) => (
        <ElTag type="" style={i > 0 && { marginLeft: 5 }}>
          {item}
        </ElTag>
      ))
    },
    hidden:true
  },
  {
    field: 'status',
    label: '状态',
    formatter: (row: Recordable, __: TableColumn) => {
      const status = STATUS_DICT_LIST.find((item) => item.value === row.status)
      if (status) {
        return <ElTag>{status.label}</ElTag>
      }
      return '-'
    }
  },
  {
    field: 'loginIp',
    label: '最后登录IP'
  },
  {
    field: 'loginDate',
    label: '最后登录时间'
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 160,
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
              {t('tableDemo.edit')}
            </ElLink>
            <ElPopconfirm
              title={t('common.delTableMsg')}
              width={200}
              v-slots={{
                reference: () => {
                  return (
                    <>
                      <ElLink type="primary" underline={false}>
                        {t('tableDemo.del')}
                      </ElLink>
                    </>
                  )
                }
              }}
              onConfirm={() => delData(data.row)}
            ></ElPopconfirm>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
              {t('tableDemo.detail')}
            </ElLink>
          </>
        )
      }
    }
  }
])
// 获取当前用户机构号
const loginOrganCode = getLoginOrganCodeByUserInfo();
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'organId',
    label: '机构',
    component: 'TreeSelect',
    optionApi: async () => {
      const res = await organTreeApi({
        treeid: '1',
        systemCode: 'portal',
        loginOrganCode,
      })
      return res.body.result
    },
    componentProps: {
      filterable: true,
      checkStrictly: true,
      nodeKey: 'id',
      props: { children: 'childs', label: 'nodeName' }
    }
  },
  {
    field: 'name',
    label: '用户姓名',
    component: 'Input'
  },
  {
    field: 'username',
    label: '登录号',
    component: 'Input'
  },
  {
    field: 'status',
    label: '用户状态',
    component: 'Select',
    componentProps: {
      options: STATUS_DICT_LIST
    }
  }
])

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 querySysUserApi(row.id)
    .catch(() => {})
    .finally(() => {
      detailLoading.close()
    })
  detailLoading.close()
  if (res) {
    const data = res.body.result
    dialogTitle.value = t(type === 'edit' ? 'tableDemo.edit' : 'tableDemo.detail')
    actionType.value = type
    currentRow.value = data
    dialogVisible.value = true
  }
}

const AddAction = () => {
  dialogTitle.value = t('tableDemo.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) {
    // SM4加密
    const sm4 = new SM4Util()
    const sm4Val = sm4.encryptData_ECB(formData.password)
    formData.password = sm4Val
    saveLoading.value = true
    const res = await saveSysUserApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

const delLoading = ref(false)

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

/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delSysUserApi(row.id)
  if (res) {
    const { code, errMsg } = res.head
    if (code === '0') {
      ElMessage.success('删除成功!')
      getList()
    } else {
      ElMessage.error(errMsg || '删除失败!')
    }
  }
}

const disabled = ref(true)

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


/** 重置密码 */
const handleResetPassword = () => {
  ElMessageBox.confirm('确定要批量重置用户密码为“12345679”吗？', '批量重置密码', {
    type: 'warning'
  }).then(async () => {
    const tableRef = await getElTableExpose()
    const list = tableRef?.getSelectionRows().map((item) => ({ id: item.id }))
    resetPasswordbatch({ list }).then(() => {
      ElMessage.success(`批量重置密码成功！`)
      tableRef?.clearSelection()
    })
  })
}

/** 更改用户状态 */
const handleUpdateUser = async (status: '0' | '1' | '2') => {
  const tableRef = await getElTableExpose()
  const label = STATUS_DICT_LIST.find((item) => item.value === status)?.label
  ElMessageBox.confirm(`确定要批量${label}用户吗？`, `批量${label}用户`, { type: 'warning' }).then(
    () => {
      const list = tableRef?.getSelectionRows().map((item) => ({ id: item.id, status }))
      batchUpdateUser({ list }).then((result) => {
        if (result) {
          ElMessage.success(`批量${label}成功！`)
          getList()
        } else {
          ElMessage.error(`批量${label}失败！`)
        }
      })
    }
  )
}
</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('tableDemo.add') }}</ElButton>
        <!-- <Upload :url="importExcelApiUrl" :callback="getList">
          <ElButton type="primary">导入</ElButton>
        </Upload> -->
        <ElButton type="primary" @click="handleResetPassword()" :disabled="disabled"
        >重置密码</ElButton
        >
        <ElButton :loading="delLoading" type="primary" :disabled="disabled" @click="delDataBatch()">
          {{ t('tableDemo.del') }}
        </ElButton>
        <ElButton type="primary" @click="handleUpdateUser('0')" :disabled="disabled"
        >启用用户</ElButton
        >
        <ElButton type="primary" @click="handleUpdateUser('1')" :disabled="disabled"
        >冻结用户</ElButton
        >
        <!-- <ElButton type="primary" @click="handleUpdateUser('2')" :disabled="disabled"
        >注销用户</ElButton
        >
        <ElButton type="primary" @click="exportExcel()">导出</ElButton> -->
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :action-type="actionType"
    />
    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('dialogDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
