<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.mc" clearable></el-input>
        </el-form-item>
        <el-form-item label="计算规则">
          <el-input placeholder="请输入计算规则" v-model="listQuery.jsgz" 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' : ''" style="margin-top: 0px">
        <el-table ref="multipleUserRef" @selection-change="handleSelectionChange" :data="tableData" border
          :row-key="keyid" style="width: 100%" height="450">
          <el-table-column type="selection" width="55" :reserve-selection="true" />
          <el-table-column prop="mc" align="center" label="系数名称" />
          <el-table-column prop="sjbl" align="center" label="衰减比例" />
          <el-table-column prop="jsgz" align="center" label="计算规则" />
        </el-table>
      </div>
      <div class="fenye" :style="{ top: tableHeight + 'px' }">
        <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.current" :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </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 * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import { defineProps, watch, ref, onMounted, nextTick } from "vue";
import { selectUnAccreditPage, selectUserDeptPage } from "@/api/user-manage";
import { sjxsglGetPageList } from "@/api/sjxsgl.js";
import { qcckPost } from "@/api/qcckApi.js";
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  titleValue: {
    type: String,
    default: "选择配置"
  },
  LeaderType: {
    type: String,
    default: ""
  },
  //是否单选
  Single: {
    type: Boolean,
    default: true
  },
  roleIds: {
    type: Array,
    default: []
  }, url: {
    type: String,
    default: ""
  }, bh: {
    type: String,
    default: ""
  },
  chooseJfBh: {
    type: String,
    default: ""
  }
});
const total = ref(0);
const listQuery = ref({
  current: 1,
  size: 20
});
const form = ref({});
const tableData = ref([]);
const emits = defineEmits(["update:modelValue", "choosedUsers"]);
onMounted(() => {
});

watch(() => props.modelValue, (val) => {
  if (val) {
    nextTick(() => {
      getListData();
    });
  }
}, {
  immediate: true
});

// 监听 roleIds 变化，实时更新选择状态
watch(() => props.roleIds, (newVal, oldVal) => {
  console.log('roleIds变化:', newVal, oldVal);
  // 只要roleIds有变化，就尝试回显，不需要等待modelValue为true
  // 因为可能是在对话框打开后roleIds才变化
  nextTick(() => {
    multipleUser();
  });
}, { deep: true });
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 reset = () => {
  listQuery.value = {
    current: 1,
    size: 20,
    loginName: "",
    phone: ""
  };
  getListData();
};

const keyid = (row) => {
  return row.id;
};
// 为用户分配角色
const onComfirm = () => {
  const userList = multipleSelectionUser.value;
  console.log(userList);
  let promes = {
    list: userList.map(item => {
      return {
        xsid: item.id,
        mc: item.mc,
        sjbl: item.sjbl,
      }
    }),
    id: props.chooseJfBh
  }
  qcckPost(promes, `/mosty-gsxt${props.url}`).then(res => {
    ElMessage.success('操作成功');
  })

  closed();
};
/**
 * pageSize 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.size = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.current = currentPage;
  getListData();
};
const getListData = () => {
  const params = listQuery.value;
  sjxsglGetPageList(params).then((res) => {
    tableData.value = res?.records;
    total.value = Number(res.total);
    // 使用 nextTick 确保表格已经渲染完成后再执行回显
    nextTick(() => {
      multipleUser();
    });
  });
};

// 列表回显
function multipleUser() {
  // 确保表格引用和数据都存在
  if (!multipleUserRef.value || !tableData.value || tableData.value.length === 0) {
    console.log('表格引用或数据不存在，无法回显');
    return;
  }

  // 先清空之前的选择，确保选择状态的准确性
  tableData.value.forEach(item => {
    multipleUserRef.value.toggleRowSelection(item, false);
  });

  console.log('开始回显，roleIds:', props.roleIds);
  console.log('表格数据:', tableData.value);

  // 根据 roleIds 进行回显，确保类型一致
  tableData.value.forEach((item) => {
    const itemId = String(item.id);
    if (props.roleIds.some((id) => String(id) === itemId)) {
      console.log('回显选择:', item);
      multipleUserRef.value.toggleRowSelection(item, true);
    }
  });
}

const handleFilter = () => {
  listQuery.value.current = 1;
  getListData();
};

const multipleUserRef = ref(null);
const multipleSelectionUser = ref([]);
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;
  }
};
</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>
