<template>
  <div class="page-container row-container">
    <!-- 左侧区域 -->
    <section class="list-part-container" style="flex: 1">
      <!-- 搜索区域 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="厂别列表" />
        <el-form-item>
          <el-button type="success" icon="Refresh" @click="handleQueryTenant">刷新</el-button>
        </el-form-item>
      </el-form>
      <!-- 列表区 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="tenantTable" v-loading="tenantLoading" :data="tenantList" row-key="id" height="100%" :indent="20" highlight-current-row default-expand-all @current-change="handleCurrentTenantChange">
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column label="Logo" align="center" width="100">
              <template #default="scope">
                <image-preview style="width: 60px; height: 60px" :src="scope.row.logo" />
              </template>
            </el-table-column>
            <el-table-column label="厂别名称" align="center" prop="orgName" />

          </el-table>
        </div>
      </div>
    </section>

    <section class="list-part-container" style="flex: 3">
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="管理员列表" />
        <el-form-item label="用户名称：" prop="userName">
          <el-input v-model.trim="queryParams.userName" :disabled="tenantList.length == 0" placeholder="请输入用户名称" clearable style="width: 130px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="手机号码：" prop="phoneNumber">
          <el-input v-model.trim="queryParams.phoneNumber" :disabled="tenantList.length == 0" placeholder="请输入手机号码" clearable style="width: 130px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <span>&emsp;&emsp;</span>
          <el-button type="info" icon="Search" :disabled="tenantList.length == 0" @click="handleQuery">搜索</el-button>
          <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
          <el-button type="primary" icon="Plus" :disabled="tenantList.length == 0" @click="handleShowFormDialog(null)" v-hasPermi="['system:user:add']">新增</el-button>
          <!-- <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']">删除</el-button> -->
        </el-form-item>
      </el-form>

      <!-- 列表区 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <!-- 渲染数据区 -->
          <el-table v-loading="adminLoading" :data="userList">
            <el-table-column label="用户名称" align="center" prop="userName" width="120" />
            <el-table-column label="用户昵称" align="center" prop="nickName" width="120" />
            <el-table-column label="手机号码" align="center" prop="phoneNumber" width="120" />
            <el-table-column label="邮箱" align="center" prop="email" width="240" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" width="220">
              <template #default="scope">
                <el-button link type="warning" icon="Edit" @click="handleShowFormDialog(scope.row.userId)" v-hasPermi="['system:user:edit']">编辑</el-button>
                <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
                <el-button link type="success" icon="Key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']">
                  重置密码
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getUserList" />
    </section>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog title="管理员信息" v-model="visible" width="400px" append-to-body draggable>
      <div class="form-container">
        <el-form class="master-container" :model="form" :rules="rules" ref="userRef" label-width="80px">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model.trim="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input v-model.trim="form.phoneNumber" placeholder="请输入手机号码" maxlength="11" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model.trim="form.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
          <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
            <el-input v-model.trim="form.userName" placeholder="请输入用户名称" maxlength="30" />
          </el-form-item>
          <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
            <el-input v-model.trim="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
          </el-form-item>
          <el-form-item label="用户性别" prop="sex">
            <el-select v-model="form.sex" placeholder="请选择">
              <el-option v-for="dict in manOrWoman" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="form.roleIds" multiple placeholder="请选择">
              <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" :disabled="item.status == 1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model.trim="form.remark" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Check" @click="handleSave">确 定</el-button>
          <el-button icon="Close" @click="handleCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { listTenantUser, resetUserPwd, delUser, getUser, updateUser, addUser, deptTreeSelect, saveAdmin } from '@/api/system/user'
import { listTenant, delTenant } from '@/api/business/tenant'
const { proxy } = getCurrentInstance()
const { sys_user_sex } = proxy.useDict('sys_normal_disable', 'sys_user_sex')

const userList = ref([])
const visible = ref(false)
const tenantLoading = ref(false)
const adminLoading = ref(false)
const ids = ref([])
const multiple = ref(true)
const total = ref(0)
const tenantRow = ref({})
const tenantList = ref([])
const roleOptions = ref([])
const manOrWoman = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]

const data = reactive({
  form: {},
  queryParams: {
    userType: '01',
    pageNum: 1,
    pageSize: 10,
    userName: '',
    phoneNumber: '',
    status: 0,
    tenantId: ''
  },
  rules: {
    // deptId: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
    userName: [
      { required: true, message: '用户名称不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
    ],
    nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
    ],
    email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    phoneNumber: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询部门下拉树结构 */
function getList() {
  tenantLoading.value = true
  listTenant(queryParams.value).then((response) => {
    tenantList.value = response.rows
    total.value = response.total
    if (tenantList.value) {
      proxy.$refs.tenantTable.setCurrentRow(tenantList.value[0])
    }
    tenantLoading.value = false
  })
}
/**左侧租户表点击事件 */
function handleCurrentTenantChange(row) {
  queryParams.value.tenantId = row.id
  queryParams.value.userType = '01'
  tenantRow.value = row
  getUserList()
}
/**用户查询 */
function getUserList() {
  adminLoading.value = true
  listTenantUser(queryParams.value).then((res) => {
    adminLoading.value = false
    userList.value = res.rows
    total.value = res.total
  })
}

/** 节点单击事件 */
function handleQueryTenant(data) {
  getList()
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  handleCurrentTenantChange(tenantRow.value)
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.value.deptId = 0
  proxy.$refs.tree.setCurrentKey(null)
  handleQuery()
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then((response) => {
        proxy.$modal.msgSuccess('修改成功，新密码是：' + value)
      })
    })
    .catch(() => {})
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: null,
    deptId: '0',
    userName: '',
    nickName: '',
    password: '',
    phoneNumber: '',
    email: '',
    sex: '',
    status: '0',
    remark: '',
    roleIds: []
  }
  proxy.resetForm('userRef')
}
/** 取消按钮 */
function handleCancel() {
  visible.value = false
  reset()
}

/** 打开表单对话框 */
function handleShowFormDialog(userId) {
  reset()
  if (userId) {
    getUser(userId).then((response) => {
      roleOptions.value = response.roles
      form.value = response.data
      form.value.roleIds = response.roleIds
    })
  } else {
    getUser().then((response) => {
      roleOptions.value = response.roles
    })
    form.value.deptId = tenantList.value[0].id
    form.value.sex = 1
  }
  visible.value = true
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value
  proxy.$modal
    .confirm('是否确认删除？')
    .then(function () {
      return delUser(userIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 提交按钮 */
function handleSave() {
  proxy.$refs['userRef'].validate((valid) => {
    if (valid) {
      form.value.tenantId = tenantRow.value.id
      form.value.userType = '01'
      if (form.value.sex == 1 || form.value.sex == '男') {
        form.value.sex = '男'
      } else {
        form.value.sex = '女'
      }
      if (form.value.userId != undefined) {
        updateUser(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          visible.value = false
          handleCurrentTenantChange(tenantRow.value)
        })
      } else {
        saveAdmin(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          visible.value = false
          handleCurrentTenantChange(tenantRow.value)
        })
      }
    }
  })
}
getList()
</script>
