<template>
  <div class="flex direction-column full user-manage">
    <div
      class="flex items-center p-l-base p-r-base p-t-medium-base fill-blank filter-form"
      :class="{ 'is-expand': expand }"
    >
      <base-form
        ref="formRef"
        class="full-w"
        size="small"
        :label-width="useVW(60)"
        :disabled="loading"
        :model="model"
        :transition="false"
        :rows="rows"
        :items="formItems"
      >
        <template #form-item-button-group>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <span class="m-l-auto">
            <el-button link custom-1 @click="toggleExpand">
              更多
              <el-icon class="collapse-icon">
                <arrow-right />
              </el-icon>
            </el-button>
          </span>
        </template>
      </base-form>
    </div>
    <div class="flex-1 p-base">
      <el-card table>
        <div class="flex items-center m-b-base">
          <el-button size="small" type="primary" @click="onAddUser">新增</el-button>
          <el-button size="small" type="primary" @click="onBulkAddUser">批量新增</el-button>
          <el-popconfirm
            v-if="hasSelected"
            :width="useVW(220)"
            hide-icon
            title="是否重置选中用户密码?"
            @confirm="handleResetPwd"
          >
            <template #reference>
              <el-button size="small" type="primary">重置密码</el-button>
            </template>
          </el-popconfirm>
          <el-button v-else size="small" type="primary" @click="checkSelected('reset')">重置密码</el-button>
          <el-popconfirm
            v-if="hasSelected"
            :width="useVW(220)"
            hide-icon
            title="是否禁用选中用户?"
            @confirm="handleDisableUsers"
          >
            <template #reference>
              <el-button size="small" type="primary">禁用</el-button>
            </template>
          </el-popconfirm>
          <el-button v-else size="small" type="primary" @click="checkSelected('disabled')">禁用</el-button>
          <el-button size="small" custom-1 @click="onExportUsers">导出</el-button>
        </div>
        <base-table
          ref="tableRef"
          size="small"
          :columns="columns"
          :data="data"
          height="-webkit-fill-available"
          @selection-change="onSectionChange"
        >
          <template #column-operation="{ row }">
            <el-button type="primary" link @click="onEditUser(row)">修改</el-button>
            <el-popconfirm :width="useVW(220)" hide-icon title="确认重置用户密码?" @confirm="onSingleResetUserPwd(row)">
              <template #reference>
                <el-button type="primary" link>重置密码</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm
              :width="useVW(220)"
              hide-icon
              :title="`确认${row.enable ? '禁用' : '启用'}用户?`"
              @confirm="onDisableUser(row)"
            >
              <template #reference>
                <el-button type="primary" link>
                  {{ row.enable ? '禁用' : '启用' }}
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </base-table>
        <el-pagination v-bind="pagination" v-model:current-page="currentPage" background right></el-pagination>
      </el-card>
    </div>
    <base-dialog :width="useVW(380)" title="导入/导出" destroy-on-close>
      <template #footer>
        <confirm-button @confirm="handleResetPwd" @cancel="() => {}"></confirm-button>
      </template>
    </base-dialog>
  </div>
</template>

<script setup lang="ts" name="UserManage">
/** 用户管理 */
import { reactive, ref, computed } from 'vue'
import { ElButton, ElPopconfirm, ElCard, ElIcon, ElPagination, ElMessage } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import BaseDialog from '@/components/element/BaseDialog.vue'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import useFetch from '@/hooks/useFetch'
import useUserManageFilter from './hooks/useUserManageFilter'
import useUserManageTable from './hooks/useUserManageTable'
import useVW from '@/hooks/useVW'
import type { ModelType, MultipleResponseType } from '@/hooks/useTable'

const { push } = useRouter()

const { formRef, model, items: formItems, rows, expand, toggleExpand } = useUserManageFilter()

const requestModel = reactive<ModelType<'getUserList'>>({})

const {
  pagination,
  currentPage,
  loading,
  data,
  columns,
  onSectionChange,
  hasSelected,
  selectedList,
  fetchTable,
  tableRef,
} = useUserManageTable(requestModel)

const { fetch: resetPwdFetch } = useFetch('resetUsersPwd')
const { fetch: toggleFetch } = useFetch('toggleEnableUsers')

/** 查询按钮 */
function onSearch() {
  Object.assign(requestModel, { ...model })
}

/** 新增按钮 */
function onAddUser() {
  push({ name: 'EditUser' })
}

/** 批量新增按钮 */
function onBulkAddUser() {
  push({ name: 'BulkAddUser' })
}

function checkSelected(type: 'reset' | 'disabled') {
  if (!selectedList.length) {
    return ElMessage.warning(`请选择需要${type === 'reset' ? '重置密码' : '禁用'}的用户`)
  }
}

/** 重置密码 */
async function handleResetPwd() {
  if (!selectedList.length) {
    return void ElMessage.warning(`请选择需要重置密码的用户`)
  }
  /** valid password */

  /** submit */
  try {
    await resetPwdFetch({ userIds: selectedList.map((d) => d.id) })
    ElMessage.success(`修改成功`)
  } catch (error) {
    console.error(error)
  }
}

/** 禁用用户 */
async function handleDisableUsers() {
  if (!selectedList.length) {
    return void ElMessage.warning(`请选择需要禁用的用户`)
  }
  /** submit */
  try {
    await toggleFetch({ ids: selectedList.map((d) => d.id), enable: false })
    ElMessage.success(`禁用成功`)
    fetchTable()
  } catch (error) {
    console.error(error)
  }
}

/** 导出按钮 */
function onExportUsers() {
  useFetch('exportUser').fetch(requestModel)
}

/** table column 修改用户 */
function onEditUser(row: MultipleResponseType<'getUserList'>) {
  push({ name: 'EditUser', params: { id: row.id } })
}

let selectionSelectedList = selectedList.slice(0)

/** table column 重置密码 */
function onSingleResetUserPwd(row: MultipleResponseType<'getUserList'>) {
  selectionSelectedList = selectedList.slice(0)
  onSectionChange([row])
  handleResetPwd().finally(() => {
    onSectionChange(selectionSelectedList)
  })
}

/** table column 禁用 */
function onDisableUser(row: MultipleResponseType<'getUserList'>) {
  row.id && toggleFetch({ enable: !row.enable, ids: [row.id] }).then(fetchTable)
}
</script>

<style scoped lang="scss">
.user-manage {
  .filter-form {
    border-bottom: $OnePixelLine;
  }
  .collapse-icon {
    transition: transform var(--el-transition-duration);
    font-weight: 300;
  }
  .is-expand {
    .collapse-icon {
      transform: rotate(90deg);
    }
  }
}
</style>
