<template>
  <el-dialog title="人员选择"
    v-model="showFlag"
    :modal= false
    width="80%"
    center
  >
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="treeRef"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <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="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </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-form-item>
        </el-form>
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" ref="tableRef">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />
          <el-table-column label="用户名称" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
          <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible" width="120" />
          <el-table-column label="状态" align="center" key="status" v-if="columns[5].visible">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>         
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <template #footer>
        <div class="dialog-footer">
            <el-button type="primary" @click="confirmSelect">确 定</el-button>
            <el-button @click="handleCancel">取 消</el-button>
        </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, watch, onMounted } from 'vue'
import { listUser } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";

// 定义v-model
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'onSelected'])

// 获取组件实例
const { proxy } = getCurrentInstance()

// 定义字典
const {
  sys_normal_disable,
  sys_user_sex
} = proxy.useDict("sys_normal_disable", "sys_user_sex" )

// 定义变量
const showFlag = ref(false)
const loading = ref(true)
const ids = ref([])
const selectedRows = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const userList = ref([])
const title = ref("")
const deptOptions = ref(undefined)
const open = ref(false)
const deptName = ref(undefined)
const dateRange = ref([])
const postOptions = ref([])
const roleOptions = ref([])
const treeRef = ref(null)
const queryRef = ref(null)
const tableRef = ref(null)

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  showFlag.value = newVal
  // 当对话框打开时，清除之前的选择
  if (newVal && tableRef.value) {
    tableRef.value.clearSelection()
    ids.value = []
    selectedRows.value = []
  }
})

// 监听showFlag变化
watch(showFlag, (newVal) => {
  emit('update:modelValue', newVal)
  // 无论对话框打开还是关闭，都重置选择
  if (tableRef.value) {
    tableRef.value.clearSelection()
    ids.value = []
    selectedRows.value = []
  }
})

// 默认属性
const defaultProps = {
  children: "children",
  label: "label"
}

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: undefined,
  phonenumber: undefined,
  status: undefined,
  deptId: undefined
})

// 列信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
])

// 监听部门名称变化
watch(deptName, (val) => {
  treeRef.value.filter(val);
})

// 组件挂载时查询数据
onMounted(() => {
  getList();
  getTreeselect();
})

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(proxy.addDateRange(queryParams, dateRange.value)).then(response => {
      userList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}

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

// 筛选节点
function filterNode(value, data) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

// 节点单击事件
function handleNodeClick(data) {
  queryParams.deptId = data.id;
  handleQuery();
}

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

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId);
  selectedRows.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

//确定选中
function confirmSelect(){
    if(selectedRows.value == null || selectedRows.value.length == 0){
        proxy.$notify({
            title:'提示',
            type:'warning',
            message: '请至少选择一条数据!'
        });
        return;
    }
    emit('onSelected', selectedRows.value);
    showFlag.value = false;
}

// 取消按钮
function handleCancel() {
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
  ids.value = []
  selectedRows.value = []
  showFlag.value = false
}
</script>