<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <ElForm :model="searchForm" inline>
        <ElFormItem label="用户名" prop="account">
          <ElInput
            v-model="searchForm.account"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </ElFormItem>
        <ElFormItem label="状态" prop="status">
          <ElSelect
            v-model="searchForm.status"
            clearable
            style="width: 200px"
            placeholder="请选择状态"
          >
            <ElOption label="启用" :value="1"></ElOption>
            <ElOption label="禁用" :value="0"></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" @click="search">查询</ElButton>
        </ElFormItem>
        <ElFormItem>
          <ElButton @click="resetSearchForm">重置</ElButton>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="success" @click="addUser">新增</ElButton>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="danger" @click="deleteUser">删除</ElButton>
        </ElFormItem>
      </ElForm>
    </div>
    <div class="user-content flex-1 flex-column overflow-hidden">
      <div class="user-list flex-1 overflow-hidden">
        <ElTable
          :data="tableData"
          border
          default-expand-all
          style="width: 100%; height: 100%"
          @selection-change="handleSelectionChange"
        >
          <ElTableColumn
            type="selection"
            header-align="center"
            align="center"
            width="55"
          />
          <ElTableColumn
            type="index"
            header-align="center"
            align="center"
            label="序号"
            width="55"
          />
          <ElTableColumn prop="account" header-align="center" label="用户名">
            <template #default="scope">
              <div>
                <span
                  >{{ scope.row.account }}
                  <ElTooltip
                    v-if="scope.row.supperMark === 1"
                    content="超级管理员"
                    placement="top"
                  >
                    <Icon
                      v-if="scope.row.supperMark === 1"
                      name="zu54"
                      style="vertical-align: super; cursor: pointer"
                    >
                    </Icon>
                  </ElTooltip>
                </span>
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="account" header-align="center" label="功能角色">
            <template #default="scope">
              <div>
                <span>{{ getRoleName(scope.row.roleIds) }} </span>
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="factoryCode"
            header-align="center"
            label="工厂"
            align="center"
          />
          <ElTableColumn
            prop="status"
            header-align="center"
            align="center"
            label="状态"
          >
            <template #default="scope">
              <el-tooltip
                :content="scope.row.status ? '启用' : '禁用'"
                placement="top"
              >
                <ElSwitch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="(e:number) => onChangeStatus(e, scope.row)"
                ></ElSwitch>
              </el-tooltip>
            </template>
          </ElTableColumn>
          <ElTableColumn
            label="操作"
            width="130"
            header-align="center"
            align="center"
          >
            <template #default="scope">
              <el-icon
                size="24"
                title="编辑"
                color="#EF6C00"
                :disabled="
                  scope.row.firstSupperMark && scope.row.supperMark === 1
                "
                style="cursor: pointer; vertical-align: middle"
                @click="editUser(scope.row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                size="24"
                title="重置密码"
                color="#67C23A"
                style="cursor: pointer; vertical-align: middle"
                @click.stop="resetPwd(scope.row)"
                ><RefreshLeft
              /></el-icon>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[100, 200, 300, 400, 500]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 10px auto 0; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></ElPagination>
    </div>
  </div>
  <ElDialog
    v-model="dialogVisible"
    :title="editId ? '编辑用户' : '新增用户'"
    width="600px"
    :close-on-click-modal="false"
    @opened="onOpenedUserForm"
  >
    <div class="dialog-form">
      <ElForm
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="90px"
      >
        <ElFormItem label="用户名" prop="account">
          <ElInput
            v-model="editForm.account"
            placeholder="请输入用户名"
            clearable
          />
        </ElFormItem>
        <ElFormItem v-if="!editId" label="密码" prop="password">
          <ElInput
            v-model="editForm.password"
            placeholder="请输入密码"
            clearable
            type="password"
            autocomplete="off"
            :show-password="true"
          />
        </ElFormItem>
        <ElFormItem label="功能角色" prop="roleIds">
          <ElSelect
            v-model="editForm.roleIds"
            placeholder="请选择功能角色"
            multiple
            :disabled="editForm.firstSupperMark && editForm.supperMark === '1'"
            clearable
            filterable
            style="width: 100%"
          >
            <ElOption
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="状态" prop="status">
          <ElCheckbox
            v-model="editForm.status"
            label="启用"
            true-value="1"
            false-value="0"
          ></ElCheckbox>
        </ElFormItem>
        <!-- <ElFormItem label="角色" prop="supperMark">
          <ElCheckbox
            v-model="editForm.supperMark"
            label="超级管理员"
            true-value="1"
            false-value="0"
          ></ElCheckbox>
        </ElFormItem> -->
      </ElForm>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false"> 取消 </ElButton>
        <ElButton type="primary" @click="save">保存</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import {
  getUserList,
  addUserApi,
  updateUserApi,
  deleteUserApi,
  getDetailsByIdApi,
  changeUserStatusApi,
  resetPasswordApi,
} from '@/api/auth'
import Icon from '@/components/Icon.vue'
import { UserEditForm, userData, userSearchForm } from '@/types/api/user'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import { showConfirm } from '@/utils/ui'
import { Edit, RefreshLeft } from '@element-plus/icons-vue'
import type { FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
const [searchForm, resetSearchForm] = useValue<userSearchForm>({})
const [editForm, resetEditForm] = useValue<UserEditForm>({
  account: '',
  password: '',
  supperMark: '0',
  status: '1',
  roleIds: [],
  firstSupperMark: false,
})
const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getUserList(searchForm.value, page, pageSize).then((res) => res.data),
})
const dialogVisible = ref(false)
const editFormRef = ref()
const selection = ref<userData[]>([])
const rules = reactive<FormRules<UserEditForm>>({
  account: [
    {
      required: true,
      message: '请输入用户名',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
    },
  ],
  roleIds: [
    {
      required: true,
      message: '请选择功能角色',
    },
  ],
})
const editId = ref<number | undefined>(undefined)
const addUser = () => {
  editId.value = undefined
  dialogVisible.value = true
  resetEditForm()
}
const deleteUser = async () => {
  if (!selection.value.length) {
    return ElMessage({
      message: '请选择用户',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  const isDel = selection.value.some(
    (item: userData) => item.firstSupperMark && item.supperMark === 1,
  )
  if (isDel) {
    return ElMessage({
      message: '超级管理员不能删除',
      type: 'error',
      offset: window.innerHeight / 2,
    })
  }
  try {
    await showConfirm('是否删除用户', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const ids = selection.value.map((item) => item.id).join(',')
    await deleteUserApi(ids)
    ElMessage({
      message: '删除成功',
      type: 'success',
      offset: window.innerHeight / 2,
    })
    search()
  } catch (e) {
    search()
    // showError(e)
  }
}
const editUser = async (item: userData) => {
  editId.value = item.id
  try {
    const res = await getDetailsByIdApi(item.id)
    res.data.supperMark = res.data.supperMark + ''
    res.data.firstSupperMark = item.firstSupperMark
    res.data.status = res.data.status + ''
    editForm.value = res.data
    editForm.value.roleIds =
      typeof res.data.roleIds === 'string'
        ? res.data.roleIds.split(',').map(Number)
        : res.data.roleIds ?? []
    dialogVisible.value = true
  } catch (e) {
    //showError(e)
  }
}
onMounted(() => getRoleList())
import { getRoleListApi } from '@/api/role'
const roleList = ref<{ id: number; name: string }[]>([])
const getRoleList = async () => {
  try {
    const res = await getRoleListApi()
    roleList.value = res.data || []
  } catch (err) {
    console.log(err)
    return
  }
}
const getRoleName = (roleIds: number[] | string) => {
  if (!roleIds) return ''
  const ids = Array.isArray(roleIds)
    ? roleIds
    : String(roleIds).split(',').filter(Boolean).map(Number)
  return roleList.value
    .filter((item: { id: number }) => ids.includes(item.id))
    .map((item: { name: string }) => item.name)
    .join(',')
}
const save = async () => {
  try {
    await editFormRef.value.validate()
  } catch {
    return
  }
  const roleIdsStr = Array.isArray(editForm.value.roleIds)
    ? editForm.value.roleIds.join(',')
    : editForm.value.roleIds
  const hasSuper = Array.isArray(editForm.value.roleIds)
    ? editForm.value.roleIds.includes(1)
    : editForm.value.roleIds.split(',').map(Number).includes(1)
  try {
    if (!editId.value) {
      await addUserApi({
        ...editForm.value,
        roleIds: roleIdsStr,
        supperMark: hasSuper ? 1 : 0,
        status: Number(editForm.value.status),
      })
    } else {
      await updateUserApi({
        ...editForm.value,
        roleIds: roleIdsStr,
        supperMark: hasSuper ? 1 : 0,
        status: Number(editForm.value.status),
      })
    }
    ElMessage({
      message: '保存成功',
      type: 'success',
      offset: window.innerHeight / 2,
    })
    dialogVisible.value = false
    search()
  } catch (e) {
    return
  }
}
const onOpenedUserForm = async () => {
  editFormRef.value?.clearValidate()
}

const handleSelectionChange = (s: userData[]) => {
  selection.value = s
}
const onChangeStatus = async (value: number, item: userData) => {
  try {
    const res = await changeUserStatusApi(value, item.id)
    ElMessage({
      message: res.message,
      type: 'success',
      offset: window.innerHeight / 2,
    })
    search()
  } catch (e) {
    //showError(e)
  }
}
const resetPwd = async (row: userData) => {
  try {
    await showConfirm(`确认要重置用户${row.account}的密码?`, {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await resetPasswordApi(row.id)
    await ElMessageBox.alert('重置成功\n\r 新密码为：' + res.data.passWord, {
      confirmButtonText: '确定',
      type: 'warning',
    })
    search()
  } catch (e) {
    search()
  }
}
</script>

<style lang="scss" scoped>
.header-filter-form {
  margin-bottom: 20px;

  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}
.user-operate-btn {
  margin-bottom: 10px;
}
.dialog-footer {
  text-align: center;
}
</style>
