<template>
    <div class="p-2">
      <el-row :gutter="20"> 
        <el-col :lg="24" :xs="24">
          <transition>
            <div class="mb-[10px]" v-show="showSearch">
              <el-card shadow="hover">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
                  <el-form-item label="用户名称" prop="name">
                    <el-input v-model="queryParams.name" placeholder="请输入用户名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="手机号码" prop="telephone">
                    <el-input
                      v-model="queryParams.telephone"
                      placeholder="请输入手机号码"
                      clearable
                      style="width: 240px"
                      @keyup.enter="handleQuery"
                    />
                  </el-form-item>
  
                  <el-form-item label="状态" prop="employee_type">
                    <el-select v-model="queryParams.employee_type" placeholder="用户状态" clearable 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 label="创建时间" style="width: 308px;">
                    <el-date-picker
                      v-model="dateRange"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                       :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleQuery" icon="Search">搜索</el-button>
                    <el-button @click="resetQuery" icon="Refresh">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
          </transition>
  
          <el-card shadow="hover">
            <template #header>
              <el-row :gutter="10">
                <!-- <el-col :span="1.5">
                  <el-button type="primary" plain @click="handleAdd()" icon="Plus">新增</el-button>
                </el-col>   -->
              </el-row>
            </template> 
            <el-table v-loading="loading" :data="userList" width='100%'>
              <el-table-column label="用户编号" align="center" prop="uid" />
              <el-table-column label="用户名称" align="center" prop="name" :show-overflow-tooltip="true" /> 
              <el-table-column label="部门" align="center" prop="organization"  :show-overflow-tooltip="true"/>
              <el-table-column label="手机号码" align="center" prop="telephone"/>
              <el-table-column label="邮箱" align="center" prop="email"/>
              <el-table-column label="状态" align="center" prop="employee_type">
                <template #default="scope"> 
                  <el-switch v-model="scope.row.employee_type" active-value="1" inactive-value="0" @change="handleStatusChange(scope.row)"></el-switch>
                </template>
              </el-table-column> 
              <el-table-column label="创建时间" align="center" prop="create_timestamp">
                <template #default="scope">
                  <span>{{ (scope.row.create_timestamp).toString().split('T')[0] }}</span>
                </template>
              </el-table-column> 
              <el-table-column label="操作" fixed="right" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-tooltip content="修改" placement="top">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                  </el-tooltip>  
                  <el-tooltip content="分配角色" placement="top">
                    <el-button link type="primary" icon="CircleCheck" @click="handleAuthRole(scope.row)"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table> 
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.page"
              v-model:limit="queryParams.page_size"
              @pagination="getList"
            />
          </el-card>
        </el-col>
      </el-row>
  
      <!-- 添加或修改用户配置对话框 -->
      <el-dialog ref="formDialogRef" :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body @close="closeDialog">
        <el-form :model="form" :rules="rules" ref="userFormRef" label-width="80px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="用户编号" prop="uid">
              <!-- maxlength="30" -->
                <el-input v-model="form.uid" placeholder="用户编号" :disabled='true'/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="用户名称" prop="name"> 
                    <el-input v-model="form.name" placeholder="用户名称" :disabled='true'/>
                </el-form-item>
            </el-col> 
            <el-col :span="24">
                <el-form-item label="部门" prop="organization"> 
                    <el-input v-model="form.organization" placeholder="部门" :disabled='true'/>
                </el-form-item>
            </el-col> 
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="手机号码" prop="telephone">
                <el-input v-model="form.telephone" placeholder="请输入手机号码" maxlength="11" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row> 
          <el-row> 
            <el-col :span="24">
              <el-form-item label="状态">
                <el-radio-group v-model="form.employee_type">
                  <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{
                    dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>  
        </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="userManagement">
  import api from "@/api/user.js"   
  import { ElMessage ,ElMessageBox} from "element-plus"; 
  const router = useRouter();
  const userList = ref();
  const loading = ref(true);
  const showSearch = ref(true);
  const total = ref(0);
  const dateRange = ref(['', '']);   
  const sys_normal_disable = ref([
    {
      label: '启用',
      value: '1'
    },
    {
      label: '停用',
      value: '0'
    }
  ])

   
  const queryFormRef = ref();
  const userFormRef = ref(); 
  const formDialogRef = ref();
  
  const dialog = reactive({
    visible: false,
    title: ''
  });
  
  const initFormData = {
    uid: undefined,
    telephone: undefined,
    organization: undefined, 
    name: undefined, 
    email: undefined, 
    employee_type: "0",  
  }
  const data = reactive({
    form: { ...initFormData },
    queryParams: {
      page: 1,
      page_size: 10,
      name: '',
      telephone: '',
      employee_type: '',
      create_timestamp_start: '',
      create_timestamp_end: '',
    },
    rules: { 
      email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
      telephone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
    }
  })
  
  const { queryParams, form, rules } = toRefs(data)

  
  /** 查询用户列表 */
  const getList = async () => {
    loading.value = true;
    queryParams.value.create_timestamp_start = dateRange.value[0];
    queryParams.value.create_timestamp_end = dateRange.value[1];
    const res = await api.listUser(queryParams.value);
    loading.value = false;

    userList.value = res.data.users.map(item => ({
        ...item,
        // 如果 employee_type 为空，默认设为 0（关闭状态）
        employee_type: item.employee_type == '' ? '0' : '1'
    }));

    // userList.value = res.data.users;
    total.value = res.data.total_count;
  }

  /** 跳转角色分配 */
const handleAuthRole = (row) => {
  const userId = row.uid;
  router.push("/user-auth/role/" + userId);
}
  
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.page = 1
    getList()
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    dateRange.value = ['', '']
    queryFormRef.value?.resetFields();
    queryParams.value.page = 1; 
    handleQuery();
  } 
  
  /** 用户状态修改  */
  const handleStatusChange = async (row) => { 
    // employee_type 0:停用 1:启用
    let text = row.employee_type === "1" ? "启用" : "停用"; 
    try { 
        await ElMessageBox.confirm(
            `确认要"${text}" "${row.name}" 用户吗?`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ); 
        const res = await api.updateUser(row); 
        if(res.meta.code !== 200){
            ElMessage.error(res.data.message);
            return;
        }
        ElMessage.success(`${row.name}${text}成功`);
        
    } catch (err) {
        // 如果用户点击取消或者 API 调用失败，恢复原来的状态
        row.employee_type = row.employee_type === "0" ? "1" : "0";
        ElMessage.success(`${row.name}${text}失败`);
    }
}
  
  
  /** 重置操作表单 */
  const reset = () => {
    form.value = { ...initFormData };
    userFormRef.value?.resetFields();
  }
  /** 取消按钮 */
  const cancel = () => {
    dialog.visible = false;
    reset();
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row) => {
    reset(); 
    const userId = row?.userId 
    dialog.visible = true;
    dialog.title = "修改用户"; 
    Object.assign(form.value, row);   
  }
  
  /** 提交按钮 */
  const submitForm = () => {
    userFormRef.value?.validate(async (valid) => {
      if (valid) {
        await api.updateUser(form.value)
        ElMessage.success("操作成功");
        dialog.visible = false;
        await getList();
      }
    })
  }
  
  
  /**
   * 关闭用户弹窗
   */
  const closeDialog = () => {
    dialog.visible = false;
    resetForm();
  }
  
  /**
   * 重置表单
   */
  const resetForm = () => {
    userFormRef.value?.resetFields();
    userFormRef.value?.clearValidate(); 
    form.value.id = undefined;
    form.value.status = '1';
  }
  onMounted(() => { 
    getList()
  });
  </script>
  
  <style lang="scss" scoped></style>
  