<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 }"
      style="padding-bottom: 10px"
    >
      <base-form
        ref="formRef"
        class="full-w"
        size="small"
        :label-width="'60px'"
        :disabled="loading"
        :model="model"
        :transition="false"
        :rows="rows"
        :items="formItems"
      >
        <template #form-item-button-group>
          <el-button :loading="loading" 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="'220px'"
            hide-icon
            title="是否重置选中用户密码?"
            @confirm="handleResetPwd"
          >
            <template #reference>
              <el-button size="small" type="primary">重置密码</el-button>
            </template>
          </el-popconfirm> -->
          <el-button size="small" type="primary" @click="checkSelected('reset', 'mult')">重置密码</el-button>
          <el-popconfirm
            v-if="hasSelected"
            :width="'220px'"
            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>
          <el-upload
            ref="upload"
            v-model:file-list="fileList"
            :limit="1"
            :show-file-list="false"
            :on-exceed="onExceed"
            :auto-upload="false"
          >
            <el-button size="small" custom-1 class="m-l-base" :loading="importUsersLoading">导入姓名</el-button>
          </el-upload>
          <!-- <el-link class="m-l-base" type="primary" @click="downTpl">导入姓名模板下载</el-link> -->
        </div>
        <base-table
          ref="tableRef"
          border
          stripe
          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-button type="primary" link @click="onSingleResetUserPwd(row)">重置密码</el-button>

            <!-- <el-popconfirm :width="'220px'" hide-icon title="确认重置用户密码?" @confirm="onSingleResetUserPwd(row)">
              <template #reference>
                <el-button type="primary" link>重置密码</el-button>
              </template>
            </el-popconfirm> -->
            <el-popconfirm
              :width="'220px'"
              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="380" title="导入/导出" destroy-on-close>
      <template #footer>
        <confirm-button @confirm="handleResetPwd" @cancel="() => {}"></confirm-button>
      </template>
    </base-dialog>
    <base-dialog
      v-model="showResetPwdDialog"
      :width="300"
      title="重置密码"
      class="reset-pwd"
      destroy-on-close
      @close="newPwd = ''"
    >
      <el-input v-model="newPwd" type="password" placeholder="请输入新的密码" clearable></el-input>
      <template #footer>
        <confirm-button
          :disabled="!newPwd"
          @confirm="handleResetPwd"
          @cancel="showResetPwdDialog = false"
        ></confirm-button>
      </template>
    </base-dialog>
  </div>
</template>

<script setup lang="ts" name="UserManage">
/** 用户管理 */
import { ref, reactive, watch } from 'vue'
import {
  ElButton,
  ElPopconfirm,
  ElCard,
  ElIcon,
  ElPagination,
  ElMessage,
  ElInput,
  ElLink,
  ElUpload,
} 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 useUploadFile from '@/hooks/useUploadFile'

import useVW from '@/hooks/useVW'

import type { ExtractMultipleApiResponse } from '@/api/api'
const newPwd = ref('')
const { push } = useRouter()
const { fileList, upload, percentage, setPercentage, onExceed } = useUploadFile()
const { fetch: importUsersFile, loading: importUsersLoading } = useFetch('importUsersFile')
const importUsersModel = reactive<any>({
  file: void 0,
})
watch(
  fileList,
  () => {
    importUsersModel.file = fileList.value?.[0]?.raw
    importUsersFile(importUsersModel).then((res: any) => {
      // ElMessage.success('导入用户成功')
      if (!res.hasError) {
        ElMessage.success('导入用户成功')
      } else {
        ElMessage.error('导入失败，详见“任务信息报告”')
      }
      onSearch()
    })
  },
  { deep: true }
)
const { formRef, model, items: formItems, rows, expand, toggleExpand } = useUserManageFilter()

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

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

/** 查询按钮 */
function onSearch() {
  fetchTable()
}

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

/** 批量新增按钮 */
function onBulkAddUser() {
  push({ name: 'BulkAddUser' })
}
const showResetPwdDialog = ref(false)
const resetPwdType = ref<any>('')

function checkSelected(type: 'reset' | 'disabled', resetType?: string) {
  if (!selectedList.length) {
    return ElMessage.warning(`请选择需要${type === 'reset' ? '重置密码' : '禁用'}的用户`)
  }
  if (type === 'reset') {
    showResetPwdDialog.value = true
    resetPwdType.value = resetType
  }
}
/** 重置密码 */
async function handleResetPwd() {
  if (!selectedList.length) {
    return void ElMessage.warning(`请选择需要重置密码的用户`)
  }
  /** valid password */

  /** submit */
  try {
    await resetPwdFetch({ userIds: selectedList.map((d) => d.id), password: newPwd.value })
    ElMessage.success(`修改成功`)
    if (resetPwdType.value === 'single') {
      onSectionChange(selectionSelectedList)
    }
    showResetPwdDialog.value = false
  } catch (error) {
    console.error(error)
    if (resetPwdType.value === 'single') {
      onSectionChange(selectionSelectedList)
    }
  }
}

/** 禁用用户 */
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(model)
}

function onImportUsers() {
  alert(1)
}
function downTpl() {
  useFetch('importUsersTemplate', 'get').fetch()
}
/** table column 修改用户 */
function onEditUser(row: ExtractMultipleApiResponse<'getUserList'>) {
  push({ name: 'EditUser', params: { id: row.id } })
}

let selectionSelectedList = selectedList.slice(0)

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

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

onSearch()
</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);
    }
  }
  :deep(.el-form-item--small) {
    margin-bottom: 10px;
  }
}
</style>
