<template>
  <div class="column-table-container no-background-container auto-height-container" :class="{ 'fullscreen-container': isFullscreen }">
    <el-row :gutter="20">
      <el-col :lg="5" :md="24" :sm="24" :xl="4" :xs="24">
        <vab-card class="auto-height-card">
          <el-input v-model="deptName" clearable placeholder="请输入部门名称" prefix-icon="Search" style="margin-bottom: 10px" />
          <el-tree
            ref="deptTreeRef"
            :data="deptOptions"
            default-expand-all
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            node-key="id"
            :props="{ label: 'label', children: 'children' }"
            @node-click="handleNodeClick"
          />
        </vab-card>
      </el-col>
      <el-col :lg="19" :md="24" :sm="24" :xl="20" :xs="24">
        <vab-card class="auto-height-card">
          <vab-query-form>
            <vab-query-form-top-panel>
              <el-form ref="queryRef" inline label-width="70px" :model="queryForm" @submit.prevent>
                <el-form-item label="用户名称" prop="userName">
                  <el-input
                    v-model="queryForm.userName"
                    clearable
                    placeholder="请输入用户名称"
                    style="width: 240px"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
                <el-form-item v-show="!fold" label="手机号码" prop="phonenumber">
                  <el-input
                    v-model="queryForm.phonenumber"
                    clearable
                    placeholder="请输入手机号码"
                    style="width: 240px"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
                <el-form-item v-show="!fold" label="状态" prop="status">
                  <el-select v-model="queryForm.status" clearable placeholder="用户状态" style="width: 240px">
                    <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item v-show="!fold" label="创建时间" prop="dateRange" style="width: 308px">
                  <el-date-picker
                    v-model="queryForm.dateRange"
                    end-placeholder="结束日期"
                    range-separator="-"
                    start-placeholder="开始日期"
                    type="daterange"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button icon="Search" :loading="listLoading" native-type="submit" type="primary" @click="handleQuery">查询</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                  <el-button class="hidden-xs-only" text type="primary" @click="handleFold">
                    <span v-if="fold">展开</span>
                    <span v-else>合并</span>
                    <vab-icon class="vab-dropdown" :class="{ 'vab-dropdown-active': fold }" icon="arrow-up-s-line" />
                  </el-button>
                </el-form-item>
              </el-form>
            </vab-query-form-top-panel>
            <vab-query-form-left-panel>
              <el-button icon="Plus" type="primary" @click="handleAdd">添加</el-button>
              <el-button icon="Delete" type="danger" @click="handleDelete">删除</el-button>
              <el-button icon="Upload" plain type="warning" @click="handleExport">导出</el-button>
            </vab-query-form-left-panel>
            <vab-query-form-right-panel>
              <div class="custom-table-right-tools">
                <el-button @click="handleQuery">
                  <vab-icon icon="refresh-line" />
                </el-button>
                <el-button @click="clickFullScreen">
                  <vab-icon :icon="isFullscreen ? 'fullscreen-exit-fill' : 'fullscreen-fill'" />
                </el-button>
                <el-popover popper-class="custom-table-checkbox">
                  <template #reference>
                    <el-button>
                      <vab-icon icon="settings-line" />
                    </el-button>
                  </template>
                  <vab-draggable v-model="columns" :animation="600" target=".el-checkbox-group">
                    <el-checkbox-group v-model="checkList">
                      <el-checkbox
                        v-for="item in columns"
                        :key="item.label"
                        :disabled="item.disableCheck"
                        :label="item.label"
                        :value="item.label"
                      >
                        {{ item.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </vab-draggable>
                </el-popover>
              </div>
            </vab-query-form-right-panel>
          </vab-query-form>

          <el-table ref="tableRef" v-loading="listLoading" border :data="list" @selection-change="setSelectRows">
            <el-table-column align="center" type="selection" width="50" />
            <!-- <el-table-column key="userId" align="center" label="用户编号" min-width="120" prop="userId" />
            <el-table-column key="userName" align="center" label="用户名称" min-width="160" prop="userName" :show-overflow-tooltip="true" />
            <el-table-column key="nickName" align="center" label="用户昵称" min-width="160" prop="nickName" :show-overflow-tooltip="true" />
            <el-table-column
              key="deptName"
              align="center"
              label="部门"
              min-width="160"
              prop="dept.deptName"
              :show-overflow-tooltip="true"
            />
            <el-table-column key="phonenumber" align="center" label="手机号码" prop="phonenumber" width="120" />
            <el-table-column key="status" align="center" label="状态">
              <template #default="scope">
                <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" prop="createTime" width="160" /> -->
            <el-table-column
              v-for="(item, index) in finallyColumns"
              :key="index"
              align="center"
              :fixed="item.fixed"
              :label="item.label"
              :min-width="item.minWidth || 160"
              :prop="item.prop"
              show-overflow-tooltip
              :sortable="item.sortable"
            >
              <template #default="scope">
                <span v-if="item.label === '状态'">
                  <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)" />
                </span>
                <span v-else-if="item.label === '部门'">
                  {{ scope.row.dept.deptName }}
                </span>
                <span v-else>{{ scope.row[item.prop] }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="240">
              <template #default="scope">
                <div v-if="scope.row.userId !== 1" class="table-operation-button">
                  <el-button icon="Edit" link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
                  <el-button icon="Delete" link type="primary" @click="handleDelete(scope.row)">删除</el-button>
                  <el-dropdown style="margin-left: 12px" @command="(command) => handleCommand(command, scope.row)">
                    <el-button icon="DArrowRight" link type="primary">更多</el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="handleResetPwd" icon="Key">重置密码</el-dropdown-item>
                        <el-dropdown-item command="handleAuthRole" icon="CircleCheck">分配角色</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty class="vab-data-empty" description="暂无数据" />
            </template>
          </el-table>
          <vab-pagination
            :current-page="queryForm.pageNum"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </vab-card>
      </el-col>
    </el-row>

    <user-management-edit2 ref="editRef" :dept-options="deptOptions" @fetch-data="fetchData" />
  </div>
</template>

<script lang="ts" setup>
import type { TableInstance } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { VueDraggable as VabDraggable } from 'vue-draggable-plus'
import { deptTreeSelect } from '/@/api/departmentManagement'
import { changeUserStatus, doDelete, getList, resetUserPwd } from '/@/api/userManagement'

defineOptions({
  name: 'UserManagement',
})

const router = useRouter()
const { proxy } = getCurrentInstance() as any
const { sys_normal_disable } = proxy.useDict('sys_normal_disable')

const { exit, enter, isFullscreen: _isFullscreen } = useFullscreen()

const deptName = ref<string>('')
const deptOptions = ref<any>([])
const tableRef = ref<TableInstance>()
const fold = ref<boolean>(true)
const editRef = ref<any>(null)
const list = ref<any>([])
const listLoading = ref<boolean>(true)
const isFullscreen = ref<boolean>(false)

const total = ref<number>(0)
const selectRows = ref<any>([])
const checkList = ref<any>([])
const queryForm = reactive<any>({
  pageNum: 1,
  pageSize: 20,
  userName: undefined,
  phonenumber: undefined,
  status: undefined,
  deptId: undefined,
  dateRange: [],
})

const columns = ref<any>([
  { label: '用户编号', prop: 'userId', minWidth: 120, checked: true },
  { label: '用户名称', prop: 'userName', minWidth: 160, checked: true },
  { label: '部门', prop: 'deptName', minWidth: 160, checked: true },
  { label: '手机号码', prop: 'phonenumber', minWidth: 120, checked: true },
  { label: '状态', prop: 'status', minWidth: 120, checked: true },
  { label: '创建时间', prop: 'createTime', minWidth: 160, checked: true },
])
const finallyColumns = computed(() => columns.value.filter((item: any) => checkList.value.includes(item.label)))

/** 根据名称筛选部门树 */
watch(deptName, (val) => {
  proxy.$refs['deptTreeRef'].filter(val)
})

watch(
  _isFullscreen,
  () => {
    if (_isFullscreen.value) isFullscreen.value = true
    else isFullscreen.value = false
  },
  { immediate: true }
)

onActivated(() => {
  tableRef.value?.doLayout()
})

onBeforeMount(() => {
  columns.value.forEach((item: any) => {
    if (item.checked) checkList.value.push(item.label)
  })

  getDeptTree()
  fetchData()
})

/** 通过条件过滤节点  */
const filterNode = (value: any, data: any) => {
  if (!value) return true
  return data.label.includes(value)
}

/** 节点单击事件 */
function handleNodeClick(data: any) {
  queryForm.deptId = data.id
  console.log(queryForm)
  handleQuery()
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data
  })
}

/** 点击全屏 */
const clickFullScreen = () => {
  isFullscreen.value = !isFullscreen.value
  isFullscreen.value ? enter() : exit()
}

/** 搜索条件折叠 */
const handleFold = () => {
  fold.value = !fold.value
}

/** 查询用户列表 */
const fetchData = async () => {
  listLoading.value = true
  const pp = Object.assign({}, proxy.addDateRange(queryForm, queryForm.dateRange))
  delete pp.dateRange
  const { rows, total: _total } = (await getList(pp)) as any
  list.value = rows
  total.value = _total
  listLoading.value = false
}

/** 搜索按钮操作 */
function handleQuery() {
  queryForm.pageNum = 1
  fetchData()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  queryForm.deptId = undefined
  proxy.$refs.deptTreeRef.setCurrentKey(null)
  handleQuery()
}

const handleSizeChange = (value: number) => {
  queryForm.pageNum = 1
  queryForm.pageSize = value
  fetchData()
}

const handleCurrentChange = (value: number) => {
  queryForm.pageNum = value
  fetchData()
}

const setSelectRows = (value: string) => {
  selectRows.value = value
}

/** 用户状态修改  */
function handleStatusChange(row: any) {
  const text = row.status === '0' ? '启用' : '停用'
  $baseConfirm(
    `确认要${text}“${row.userName}”用户吗?`,
    null,
    async () => {
      await changeUserStatus(row.userId, row.status)
      $baseMessage(`${text}成功`, 'success', 'hey')
    },
    () => {
      row.status = row.status === '0' ? '1' : '0'
    }
  )
}

/** 更多操作 */
function handleCommand(command: string, row: any) {
  switch (command) {
    case 'handleResetPwd': {
      handleResetPwd(row)
      break
    }
    case 'handleAuthRole': {
      handleAuthRole(row)
      break
    }
    default: {
      break
    }
  }
}

/** 跳转角色分配 */
function handleAuthRole(row: any) {
  const userId = row.userId
  router.push({
    name: 'AuthRole',
    params: {
      userId,
    },
  })
}

/** 重置密码按钮操作 */
const handleResetPwd = (row: any) => {
  ElMessageBox.prompt('提示', `请输入"${row.userName}"的新密码`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
    inputValidator: (value) => {
      if (/<|>|"|'|\||\\/.test(value)) {
        return String.raw`不能包含非法字符：< > " ' \ |`
      }
      return true
    },
  })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then(() => {
        $baseMessage(`修改成功，新密码是：${value}`, 'success', 'hey')
      })
    })
    .catch(() => {})
}

/** 新增按钮操作 */
const handleAdd = () => {
  editRef.value.showEdit()
}

/** 修改按钮操作 */
function handleUpdate(row: any) {
  editRef.value.showEdit(row)
}

/** 删除按钮操作 */
const handleDelete = (row: any = {}) => {
  if (row.userId) {
    $baseConfirm(`您确定要删除用户名称为${row.userName}的数据项吗`, null, async () => {
      const { msg }: any = await doDelete(row.userId)
      $baseMessage(msg, 'success', 'hey')
      await fetchData()
    })
  } else {
    if (selectRows.value.length > 0) {
      const ids = selectRows.value.map((item: { userId: any }) => item.userId)
      $baseConfirm('您确定要删除选中项吗', null, async () => {
        const { msg }: any = await doDelete(ids)
        $baseMessage(msg, 'success', 'hey')
        await fetchData()
      })
    } else {
      $baseMessage('您未选中任何行', 'warning', 'hey')
    }
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/user/export',
    {
      ...queryForm,
    },
    `user_${Date.now()}.xlsx`
  )
}
</script>
