<template>
  <el-dialog :title="titleValue" width="1400px" :model-value="modelValue" append-to-body @close="closed">
    <div>
      <el-form :model="listQuery" class="mosty-from-wrap" :inline="true">
        <el-form-item label="性质名称">
          <el-input placeholder="请输入性质名称" v-model="listQuery.bqMc" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleFilter">查询</el-button>
          <el-button type="info" @click="reset"> 重置 </el-button>
        </el-form-item>
      </el-form>
      <div class="tabBox" :class="props.Single ? 'tabBoxRadio' : ''" :key="keyVal" style="margin-top: 0px">
        <el-table ref="multipleUserRef" @selection-change="handleSelectionChange" :data="tableData" v-loading="loading"
          border :row-key="keyid" style="width: 100%" height="450">
          <el-table-column type="selection" width="55" :reserve-selection="true" />
          <el-table-column prop="zdmc" align="center" label="性质名称" />
          <el-table-column prop="dm" align="center" label="性质代码" />
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed">取消</el-button>
        <el-button type="primary" @click="onComfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, ref, getCurrentInstance, watch } from "vue";
import { nextTick } from 'vue';
const { proxy } = getCurrentInstance();
const { D_ZDQT_QTXZ } = proxy.$dict("D_ZDQT_QTXZ"); //获取字典数据
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  titleValue: {
    type: String,
    default: "选择标签"
  },
  LeaderType: {
    type: String,
    default: ""
  },
  //是否单选
  Single: {
    type: Boolean,
    default: false
  },
  roleIds: {
    type: Array,
    default: []
  }
});
const loading = ref(false);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20
});

const keyVal = ref();
const multipleUserRef = ref(null);
const multipleSelectionUser = ref([]);
const tableData = ref([]);
const emits = defineEmits(["update:modelValue", "choosed"]);
const keyid = (row) => {
  return row.dm;
};
const closed = () => {
  // 清空选中状态
  multipleSelectionUser.value = [];
  
  // 如果表格实例存在，取消所有选中行
  if (multipleUserRef.value && tableData.value && tableData.value.length > 0) {
    tableData.value.forEach((item) => {
      multipleUserRef.value.toggleRowSelection(item, false);
    });
  }
  
  // 关闭对话框
  emits("update:modelValue", false);
};

// 为用户分配角色
const onComfirm = () => {
  const userList = multipleSelectionUser.value;
  let list = [];
  let listId = [];
  userList.forEach((val) => {
    if (listId.indexOf(val.id) == -1) {
      list.push(val);
      listId.push(val.id);
    }
  });
  emits("choosed", list);
  closed();
};

const getListData = () => {
  loading.value = true;
  try {
    tableData.value = D_ZDQT_QTXZ.value || [];
    console.log(tableData.value);
    // 数据加载完成后调用回显函数
    nextTick(() => {
      multipleUser();
    });
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
};

//列表回显
function multipleUser() {
  if (!multipleUserRef.value || !tableData.value || tableData.value.length === 0) {
    return;
  }
  
  // 先清空所有选中状态
  tableData.value.forEach((item) => {
    multipleUserRef.value.toggleRowSelection(item, false);
  });
  // 再设置需要选中的行
  if (props.roleIds && props.roleIds.length > 0) {
    const selectedItems = tableData.value.filter(item => 
      props.roleIds.some(id => id == item.id)
    );
    
    selectedItems.forEach(item => {
      multipleUserRef.value.toggleRowSelection(item, true);
    });
    
    // 更新选中的数据
    multipleSelectionUser.value = selectedItems;
  }
}

const handleFilter = () => {
  const originalData = D_ZDQT_QTXZ.value || [];
  if (listQuery.value.bqMc) {
    tableData.value = originalData.filter(item => 
      item.zdmc.includes(listQuery.value.bqMc)
    );
  } else {
    tableData.value = [...originalData];
  }
  
  // 筛选后重新回显
  nextTick(() => {
    multipleUser();
  });
};

const reset = () => {
  listQuery.value.bqMc = '';
  getListData();
};
const handleSelectionChange = (val) => {
  if (props.Single) {
    if (val.length > 1) {
      let del_row = val.shift();
      multipleUserRef.value.toggleRowSelection(del_row, false);
    }
    multipleSelectionUser.value = val;
  } else {
    multipleSelectionUser.value = val;
  }
};

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      // 重置查询条件
      reset();
      // 重新加载数据
      getListData();
    } else {
      // 关闭时清空选中状态
      multipleSelectionUser.value = [];
    }
  },
  { immediate: true }
);

// 监听roleIds变化，重新回显
watch(
  () => props.roleIds,
  () => {
    if (props.modelValue) {
      nextTick(() => {
        multipleUser();
      });
    }
  },
  { deep: true }
);

// 监听Single属性变化，确保单选模式下只保留一个选中项
watch(
  () => props.Single,
  () => {
    if (props.Single && multipleSelectionUser.value.length > 1) {
      const firstItem = multipleSelectionUser.value[0];
      multipleSelectionUser.value = [firstItem];
      // 重新设置选中状态
      nextTick(() => {
        multipleUser();
      });
    }
  }
);

// 引入nextTick

</script>

<style lang="scss" scoped>
@import "@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";
</style>
<style>
.tabBoxRadio .el-checkbox__inner {
  border-radius: 50% !important;
}

.tabBoxRadio .el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>
