<template>
  <el-dialog
    :title="titleValue"
    width="1500px"
    :model-value="modelValue"
    append-to-body
    @close="closed"
  >
    <div class="table_class">
      <div style="width: 48%">
        <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
          <el-tab-pane
            v-for="tab in tabs"
            :key="tab.dm"
            :label="tab.label"
            :name="tab.dm"
          >
            <!-- 添加 v-if 条件 -->
            <template v-if="activeTab !== '03'">
              <el-button
                v-for="(it, idx) in props.dic.D_GS_BQ_LB"
                :key="idx"
                :type="type == it.zdmc ? 'success' : ''"
                @click="chooseListType(it.zdmc)"
              >
                <span style="vertical-align: middle">{{ it.zdmc }}</span>
              </el-button>
            </template>
            <el-table
              v-loading="loading"
              ref="multipleUserRef"
              @selection-change="handleSelectionChange"
              :data="tableData"
              border
              :row-key="keyid"
              style="width: 100%"
            >
              <el-table-column
                type="selection"
                width="55"
                :reserve-selection="true"
              />
              <el-table-column prop="bqMc" align="center" label="标签名称" />

              <el-table-column prop="bqDm" align="center" label="标签代码" />
              <el-table-column prop="bqZl" align="center" label="标签种类">
                <template #default="{ row }">
                  <DictTag
                    :value="row.bqZl"
                    :tag="false"
                    :options="props.dic.D_GS_BQ_ZL"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="bqLx" align="center" label="标签类型">
                <template #default="{ row }">
                  <DictTag
                    :value="row.bqLx"
                    :tag="false"
                    :options="props.dic.D_GS_BQ_LX"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="bqLb" align="center" label="标签类别">
                <template #default="{ row }">
                  <DictTag
                    :value="row.bqLb"
                    :tag="false"
                    :options="props.dic.D_GS_BQ_LB"
                  />
                </template>
              </el-table-column>
            </el-table>
            <div class="fenye">
              <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>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div style="width: 48%">
        <div class="selected-tabBox">
          <el-table
            :data="selectedData"
            border
            :row-key="keyid"
            style="width: 100%"
          >
            <el-table-column prop="bqDm" align="center" label="标签代码" />
            <el-table-column prop="bqLb" align="center" label="标签类别">
              <template #default="{ row }">
                <DictTag
                  :value="row.bqLb"
                  :tag="false"
                  :options="props.dic.D_GS_BQ_LB"
                />
              </template>
            </el-table-column>
            <el-table-column prop="bqLx" align="center" label="标签类型">
              <template #default="{ row }">
                <DictTag
                  :value="row.bqLx"
                  :tag="false"
                  :options="props.dic.D_GS_BQ_LX"
                />
              </template>
            </el-table-column>
            <el-table-column prop="bqMc" align="center" label="标签名称" />
            <el-table-column prop="bqZl" align="center" label="标签种类">
              <template #default="{ row }">
                <DictTag
                  :value="row.bqZl"
                  :tag="false"
                  :options="props.dic.D_GS_BQ_ZL"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  type="danger"
                  @click="handleRemoveFromSelectedData(row)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="fenye">
          <el-pagination
            class="pagination"
            @size-change="handleSizeChangeRight"
            @current-change="handleCurrentChangeRight"
            :current-page="listQuery.current"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="listQuery.sizeRight"
            layout="total, sizes, prev, pager, next, jumper"
            :total="selectedData.length"
          ></el-pagination>
        </div>
      </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, onMounted, nextTick } from "vue";
import { qcckGet } from "@/api/qcckApi.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  dic: {
    type: Object,
    default: () => {}
  },
  bqDl: {
    type: String,
    default: "01"
  },
  bqLx: {
    type: String,
    default: "01"
  },
  titleValue: {
    type: String,
    default: "选择大类"
  },
  LeaderType: {
    type: String,
    default: ""
  },
  // 是否单选
  Single: {
    type: Boolean,
    default: false
  },
  roleIds: {
    type: Array,
    default: []
  }
});

const tabs = ref([]);
const activeTab = ref("");
const total = ref(0);
const listQuery = ref({
  current: 1,
  size: 20,
  bqZl: activeTab.value
});
const loading = ref(false);
const tableData = ref([]);
const selectedData = ref([]);
const multipleUserRef = ref(null);
const emits = defineEmits(["update:modelValue", "chooseDate"]);
const type = ref("标签大类");
onMounted(() => {
  console.log(props.dic.D_GS_BQ_ZL, "props.dic.D_GS_BQ_ZL");
  tabs.value = props.dic.D_GS_BQ_ZL;
  activeTab.value = tabs.value?.[0]?.dm || "01";
  handleFilter();
});
// 选择列表的大类和细类
const chooseListType = (val) => {
  type.value = val;
  listQuery.current = 1;
  getDataList();
};
const closed = () => {
  emits("update:modelValue", false);
};

const reset = () => {
  listQuery.value = { current: 1, size: 20, bqZl: activeTab.value };
  getDataList();
};

const keyid = (row) => {
  return row.id;
};

// 为用户分配角色
const onComfirm = () => {
  emits("chooseDate", selectedData.value);
  let data = { type: props.LeaderType, userList: selectedData.value };
  emits("chooseDateLeader", data);
  closed();
};
//数据回显
const setValues = (list) => {
  selectedData.value = list.map((item) => {
    // 统一id字段处理逻辑
    if (item.bqId) {
      return { ...item, id: item.bqId };
    }

    return item;
  });

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

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.current = currentPage;
  getDataList();
};

// 查询标签组合列表
const getDataList = () => {
  listQuery.value.bqZl = activeTab.value;
  loading.value = true;
  //根据顶部标签切换不同的接口
  let url =
    activeTab.value == "01"
      ? "/mosty-gsxt/tbGsxtBqgl/selectPage"
      : activeTab.value == "02"
      ? "/mosty-gsxt/tbGsxtBqgl/selectPage"
      : "/mosty-gsxt/tbGsxtBqzh/selectPage";
  let params = {};
  console.log(activeTab.value, "activeTab.value");
  if (activeTab.value === "01") {
    params.bqLx = "01";
  } else if (activeTab.value === "02") {
    params.bqLx = "02";
  } // activeTab.value 等于 "03" 时不传递参数
  if (type.value === "标签大类") {
    params.bqLb = "01";
  } else if (type.value === "标签细类") {
    params.bqLb = "02";
  }
  qcckGet(params, url).then((res) => {
    // 添加 bqZl 字段
    tableData.value = res?.records?.map((item) => ({
      bqDm: item.bqDm,
      bqId: item.id ? item.id : item.bqId ? item.bqId : row.bqDlId,
      bqLb: item.bqLb,
      bqLx: item.bqLx,
      bqMc: item.bqMc,
      bqZl: activeTab.value
    }));
    total.value = Number(res.total);
    loading.value = false;
    //确保在这里调用 multipleUser
    multipleUser();
  });
};

// 修改 multipleUser 函数
function multipleUser() {
  nextTick(() => {
    if (multipleUserRef.value && tableData.value.length > 0) {
      tableData.value.forEach((item) => {
        if (selectedData.value.some((selected) => selected.bqId == item.bqId)) {
          // 因为 multipleUserRef 是数组，需要确定正确的索引
          // 如果你只有一个表格，可以使用 [0]
          multipleUserRef.value[0]?.toggleRowSelection(item, true);
        }
      });
    }
  });
}

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

  getDataList();
};

const handleTabClick = () => {
  reset();
};

const handleAddToSelectedData = (row) => {
  console.log(row, selectedData.value, "handleAddToSelectedData row");
  if (selectedData.value.some((item) => item.bqId === row.bqId)) {
    return;
  }
  if (props.Single && selectedData.value.length > 0) {
    selectedData.value = [];
  }
  selectedData.value.push({
    bqDm: row.bqDm,
    bqId: row.id ? row.id : row.bqId ? row.bqId : row.bqDlId,
    bqLb: row.bqLb,
    bqLx: row.bqLx,
    bqMc: row.bqMc,
    bqZl: activeTab.value
  });
};

const handleRemoveFromSelectedData = (row) => {
  const index = selectedData.value.findIndex((item) => item.bqId === row.bqId);
  if (index !== -1) {
    selectedData.value.splice(index, 1);
  }
  // 取消左侧表格中对应行的选中状态
  multipleUserRef.value.toggleRowSelection(row, false);
};

const multipleSelectionUser = ref([]);
const handleSelectionChange = (val) => {
  multipleSelectionUser.value = val;
  multipleSelectionUser.value.forEach((row) => {
    handleAddToSelectedData(row);
  });
};
// 必须暴露方法父组件才能调用
defineExpose({
  setValues
});
</script>

<style lang="scss" scoped>
@import "@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";

.selected-tabBox {
  margin-top: 56px;
}
</style>

<style>
.tabBoxRadio .el-checkbox__inner {
  border-radius: 50% !important;
}
.tabBoxRadio .el-table__header-wrapper .el-checkbox {
  display: none;
}
:deep(.el-dialog) {
  background: #fff !important;
  border-radius: 8px !important;
  /* 其他样式 */
}
.table_class {
  display: flex;
  justify-content: space-between;
}
</style>
