<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true">
      <el-form-item label="账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入账号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入姓名"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否超级管理员" prop="isSuperAdmin">
        <el-select
          v-model="queryParams.isSuperAdmin"
          placeholder="是否超级管理员"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_no_yes"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="用户状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_user_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="userList">
      <el-table-column label="账号" prop="userName" />
      <el-table-column label="姓名" prop="realName" />
      <el-table-column label="昵称" prop="nickName" />
      <el-table-column label="邮箱" prop="email" />
      <el-table-column label="手机号" prop="mobile" />
      <el-table-column prop="gender" label="性别">
        <template #default="scope">
          <dict-tag :options="sys_gender" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="val => handleStatusChange(scope.row, $event)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="isSuperAdmin" label="是否超级管理员">
        <template #default="scope">
          <dict-tag :options="sys_no_yes" :value="scope.row.isSuperAdmin" />
        </template>
      </el-table-column>
      <el-table-column label="最后登录IP" prop="lastLoginIp" />
      <el-table-column label="最后登录时间" align="center" prop="lastLoginTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastLoginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改密码时间" align="center" prop="lastPasswordTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastPasswordTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200px"
      >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button link type="primary" icon="Edit" @click="handleResetPwd(scope.row)"
            >重置密码</el-button
          >
          <!--              <el-button link type="primary" icon="View" @click="handleUpdate(scope.row)" >详情</el-button>-->
          <!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="userRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.userBizId">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <!-- <el-form-item label="用户属性">
          <el-select v-model="form.attribute" placeholder="请输入">
            <el-option
              v-for="item in sys_user_attribute"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio
              v-for="dict in sys_gender"
              :key="Number(dict.value)"
              :value="Number(dict.value)"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_status"
              :key="Number(dict.value)"
              :value="Number(dict.value)"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="form.avatar" placeholder="请输入头像" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import {
  listUser,
  getUser,
  updateUser,
  addUser,
  changeUserStatus,
  resetUserPwd
} from '@/api/system/user'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const { sys_status, sys_scope, sys_no_yes, sys_user_status, sys_gender, sys_user_attribute } =
  proxy.useDict(
    'sys_status',
    'sys_scope',
    'sys_no_yes',
    'sys_user_status',
    'sys_gender',
    'sys_user_attribute'
  )

const userList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const total = ref(0)
const title = ref('')

const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
    userName: undefined,
    realName: undefined,
    mobile: undefined,
    status: undefined,
    isSuperAdmin: undefined
  },
  rules: {
    userName: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
    realName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    nickName: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
    email: [
      { required: true, message: '邮箱不能为空', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    mobile: [
      { required: true, message: '手机号不能为空', trigger: 'blur' },
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    avatar: [{ required: true, message: '头像URL不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
      { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
    ]
  }
})
const { queryParams, form, rules } = toRefs(data)

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(queryParams.value).then(response => {
    userList.value = response.data.records
    total.value = response.data.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.roleId || ids.value
  proxy.$modal
    .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?')
    .then(function () {
      return delRole(roleIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 用户状态修改 */
function handleStatusChange(row, event) {
  debugger
  let text = row.status === 0 ? '停用' : '启用'
  const userName = row.userName
  proxy.$modal
    .confirm(`确认要${text}"${userName}"用户吗?`)
    .then(() => changeUserStatus({ userBizId: row.userBizId, status: row.status }))
    .then(() => proxy.$modal.msgSuccess(`${text}成功`))
    .catch(() => {
      // 操作取消时恢复原状态
      row.status = row.status === 0 ? 1 : 0
    })
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
    userBizId: undefined,
    userName: undefined,
    password: undefined,
    realName: undefined,
    nickName: undefined,
    avatar: undefined,
    email: undefined,
    mobile: undefined,
    gender: 0,
    status: 1
  }
  proxy.resetForm('userRef')
}

/** 添加用户 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加用户'
}

/** 修改用户弹框 */
function handleUpdate(row) {
  reset()
  const userBizId = row.userBizId
  getUser(userBizId).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改项目'
  })
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      inputValidator: value => {
        if (/<|>|"|'|\||\\/.test(value)) {
          return '不能包含非法字符：< > " \' \\\ |'
        }
      }
    })
    .then(({ value }) => {
      resetUserPwd({ userBizId: row.userBizId, password: value }).then(response => {
        getList()
        proxy.$modal.msgSuccess('修改成功，新密码是：' + value)
      })
    })
    .catch(() => {})
}

/** 添加和修改用户提交按钮 */
function submitForm() {
  proxy.$refs['userRef'].validate(valid => {
    console.log('valid', valid)
    if (valid) {
      if (form.value.userBizId) {
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addUser(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

getList()
</script>
