<template>
  <div class="scroll">
    <div class="middle">
      <div class="filter">
        <div class="condition">
          <span>活动名称 :</span>
          <el-input
            clearable
            v-model.trim="searchInput.theme"
            class="w-50 m-2"
            placeholder="请输入活动名称"
            style="width: 180px"
          />
        </div>
        <div class="condition">
          <span>活动状态 :</span>
          <el-select
            clearable
            v-model="searchInput.statuId"
            placeholder="请选择活动状态"
          >
            <el-option
              v-for="i in statusData"
              :key="i.id"
              :label="i.name"
              :value="i.id"
            />
          </el-select>
        </div>
        <div class="condition">
          <span>活动时间 :</span>
          <el-date-picker
            v-model="searchInput.createTime"
            unlink-panels
            type="datetimerange"
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择日期"
          />
        </div>
        <el-button
          style="margin-left: 20px"
          color="rgba(38, 151, 255, 1)"
          type="primary"
          class="search"
          @click="searchBtn"
          ><span>查询</span></el-button
        >
        <el-button @click="resetBtn" plain color="rgba(43, 153, 255, 1)"
          >重置</el-button
        >
      </div>
      <!-- 按钮列表 -->
      <div class="gongneng">
        <el-button
          type="primary"
          style="margin-left: 0"
          color="rgba(38, 151, 255, 1)"
          @click="addlist"
          >创建活动</el-button
        >
      </div>
    </div>
    <div class="footer" v-loading="tableLoading">
      <el-table
        :row-class-name="tableRowClassName"
        :data="tableData.list"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        :header-cell-style="{
          background: 'rgba(240, 243, 247, 1)',
          height: '50px',
          border: 0,
        }"
      >
        <!-- <el-table-column type="selection" align="center" width="55" /> -->
        <el-table-column type="index" align="center" label="序号" width="60" />
        <el-table-column align="center" prop="theme" label="活动名称" />
        <el-table-column prop="timeStr" align="center" label="活动时间">
          <template #default="{ row }">
            <span>{{ row.startTime }} ~ {{ row.endTime }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="活动地点" />
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="themeDetail"
          label="活动详情"
        >
          <template #default="{ row }">
            <div
              class="html-content"
              style="color: #2697ff; cursor: pointer"
              @click="handleTooltipShow(row.themeDetail)"
            >
              详情
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sex" label="报名截止时间">
          <template #default="{ row }">
            <span>{{ row.signsTime }} ~ {{ row.signeTime }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="orgName" label="所属组织" />
        <el-table-column align="center" prop="publisherName" label="发起人" />
        <el-table-column align="center" prop="createTime" label="创建时间" />
        <el-table-column
          align="center"
          prop="activityStatuName"
          label="活动状态"
        />
        <el-table-column
          align="center"
          prop="reportNumber"
          label="已报名人数"
        />
        <el-table-column align="center" label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button type="primary" @click="updateS(row)" link
              >编辑</el-button
            >
            <el-button type="danger" @click="deleteS(row)" link>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="pageSize">
        <span></span>
        <el-pagination
          background
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total,sizes, prev, pager, next, jumper, slot"
          :total="total"
          @size-change="handleSizeChange"
          @update:current-page="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加账号弹窗 -->
    <el-dialog
      class="addStaff"
      v-model="addDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="dialongTitle"
      align-center
      width="780"
      :before-close="cancelAdd"
      destroy-on-close
      draggable
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        label-position="right"
        status-icon
      >
        <el-form-item label="活动名称 :" prop="theme">
          <el-input
            clearable
            v-model.trim="ruleForm.theme"
            class="w-50 m-2"
            placeholder="请输入活动名称"
          />
        </el-form-item>
        <el-form-item label="所属组织 :" prop="orgId">
          <!-- <el-select
            v-model="ruleForm.orgId"
            clearable
            placeholder="请搜索或选择所属组织"
            popper-class="club-select"
            ref="selectRef"
            :loading="loading"
            :filterable="true"
            @filter-change="handleFilter"
          >
            <el-option
              v-for="i in clubData"
              :key="i.id"
              :label="i.name"
              :value="`${i.name},${i.id}`"
            />
            加载提示/无更多提示
            <div v-if="clubData.length" class="select-loading">
              <span v-if="loading">加载中...</span>
              <span v-else-if="noMore">已加载全部数据</span>
            </div>
          </el-select> -->
          <el-select
            v-model="ruleForm.orgId"
            filterable
            clearable
            remote
            reserve-keyword
            placeholder="请搜索或选择所属组织"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="i in clubData"
              :key="i.id"
              :label="i.name"
              :value="`${i.name},${i.id}`"
            />
          </el-select>
          <!-- <el-button @click="resetOrgId" plain color="rgba(43, 153, 255, 1)"
            >重置</el-button
          > -->
        </el-form-item>
        <el-form-item label="活动详情 :" prop="themeDetail">
          <!-- <el-input
            v-model.trim="ruleForm.themeDetail"
            placeholder="请输入活动详情"
            clearable
            :autosize="{ minRows: 4 }"
            type="textarea"
          /> -->
          <Richtext
            @richtextClick="richtextClick"
            :fatherMessage="fatherMessage"
          ></Richtext>
        </el-form-item>
        <el-form-item label="活动时间 :" prop="activeTime" style="width: 520px">
          <el-date-picker
            v-model="ruleForm.activeTime"
            unlink-panels
            type="datetimerange"
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择日期"
          />
        </el-form-item>
        <el-form-item label="活动地点 :" prop="address">
          <el-input
            clearable
            v-model.trim="ruleForm.address"
            class="w-50 m-2"
            placeholder="请输入活动地点"
          />
        </el-form-item>
        <el-form-item
          label="报名截止时间 :"
          prop="signTime"
          style="width: 520px"
        >
          <el-date-picker
            v-model="ruleForm.signTime"
            unlink-panels
            type="datetimerange"
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择日期"
          />
        </el-form-item>
        <el-form-item label="报名总人数 :" prop="totalNumber">
          <el-input
            clearable
            v-model.trim="ruleForm.totalNumber"
            class="w-50 m-2"
            placeholder="请输入报名总人数"
          />
        </el-form-item>
        <el-form-item class="options">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button
            color="rgba(0, 97, 255, 1)"
            class="queding"
            type="primary"
            @click="submitAdd(ruleFormRef)"
          >
            确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      class="tooltips"
      v-model="tooltipVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="活动详情"
      align-center
      width="800"
      destroy-on-close
      draggable
    >
      <span v-html="tooltipContent"></span>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  watch,
  reactive,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { genFileId, ElMessage, ElMessageBox } from "element-plus";
import { dayjs } from "element-plus";
import lodash from "lodash";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import { storeToRefs } from "pinia";
import { useCounterStore } from "@/stores/index";
import { api as viewerApi } from "v-viewer";

import Richtext from "./Richtext.vue";

import {
  queryStatus,
  queryActivityPages,
  insertActivity,
  queryClubDatas,
  updateActivity,
  deleteActivityById,
} from "@/api/alumni-activity.js";

const router = useRouter();
const store = useCounterStore();

// 为避免解构时失去响应性
const { name, age, isCollapse, realAge, collegeRole } = storeToRefs(store);

const fatherMessage = ref({
  data: "",
  flag: false,
});
// 富文本传过来的数据
const richtextClick = (data) => {
  console.log(data, "富文本传过来的数据");
  // params.value.safetyNotice = data.html;
  fatherMessage.value.data = data.html;
  ruleForm.themeDetail = data.html;
  // accountRuleForm.contentText = data.text;
};

// 表格数据
const tableLoading = ref(false);
const tableData = reactive({
  list: [{}],
});
const dialongTitle = ref("新增账号"); // 弹窗标题

const searchInput = reactive({
  theme: "",
  statuId: "",
  createTime: "",
}); // 搜索按钮数据

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(0); // 当前总数
const selectIds = ref([]); // 勾选的全部数据

const statusData = ref();

// 下拉数据相关
const selectRef = ref(null); // select组件ref
const clubData = ref([]); // 已加载的组织列表
const loading = ref(false); // 加载状态
const pageParams = reactive({
  pageNum: 1, // 当前页
  pageSize: 500, // 每页条数
  keyword: "", // 搜索关键词（可选）
});

const addDialogVisible = ref(false); // 控制添加账号弹窗

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  theme: "",
  orgId: "",
  themeDetail: "",
  activeTime: "",
  address: "",
  signTime: "",
  totalNumber: "",
  id: "",
});
// 表单验证
const rules = reactive({
  theme: [{ required: true, message: "活动名称不能为空", trigger: "blur" }],
  orgId: [{ required: true, message: "所属组织不能为空", trigger: "blur" }],
  themeDetail: [
    { required: true, message: "活动详情不能为空", trigger: "blur" },
  ],
  activeTime: [
    { required: true, message: "活动时间不能为空", trigger: "blur" },
  ],
  address: [{ required: true, message: "活动地点不能为空", trigger: "blur" }],
  signTime: [
    { required: true, message: "报名截止时间不能为空", trigger: "blur" },
  ],
  totalNumber: [
    { required: true, message: "报名总人数不能为空", trigger: "blur" },
  ],
});

// Tooltip 相关响应式变量
const tooltipVisible = ref(false);
const tooltipContent = ref("");

// 处理 Tooltip 显示（判断是否溢出 + 更新内容）
const handleTooltipShow = (htmlContent) => {
  tooltipVisible.value = true;
  tooltipContent.value = htmlContent;
};

// 获取账户列表
const getList = async () => {
  tableLoading.value = true;
  let params = {
    currentPage: currentPage.value, // 当前页
    pageCount: pageSize.value, // 一页数据条数
    theme: searchInput.theme,
    statuId: searchInput.statuId,
  };
  if (searchInput.createTime) {
    params.startTime = searchInput.createTime[0];
    params.endTime = searchInput.createTime[1];
  }
  queryActivityPages(params).then((res) => {
    console.log(res, "获取活动分页数据");
    if (res.code == 200) {
      tableData.list = res.data.list;
      total.value = res.data.totalCount;
      tableLoading.value = false;
    } else {
      tableLoading.value = false;
      ElMessage({
          type: "error",
          showClose: true,
          message: res.message,
          center: true,
        });
    }
  });
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  currentPage.value = 1;
  getList();
}, 300);
const resetBtn = lodash.debounce(async () => {
  searchInput.theme = "";
  searchInput.statuId = "";
  searchInput.createTime = "";
  currentPage.value = 1;
  getList();
}, 300);

// 添加账号
const addlist = () => {
  dialongTitle.value = "创建活动";
  addDialogVisible.value = true;
  ruleForm.theme = "";
  ruleForm.orgId = "";
  ruleForm.themeDetail = "";
  ruleForm.address = "";
  ruleForm.signTime = "";
  ruleForm.totalNumber = "";
  ruleForm.id = "";
  fatherMessage.value.data = "";
};
// 添加账号
const updateS = (row) => {
  console.log(row);
  dialongTitle.value = "编辑活动";
  addDialogVisible.value = true;
  ruleForm.theme = row.theme;
  pageParams.keyword=row.orgName
  clubList().then(() => {
    ruleForm.orgId = `${row.orgName},${row.orgId}`;
  })
  ruleForm.themeDetail = row.themeDetail;
  ruleForm.activeTime = [row.startTime, row.endTime];
  ruleForm.address = row.address;
  ruleForm.signTime = [row.signsTime, row.signeTime];
  ruleForm.totalNumber = row.totalNumber;
  ruleForm.id = row.id;
  fatherMessage.value.data = row.themeDetail;
};
const deleteS = async (row) => {
  ElMessageBox.confirm("是否删除此数据?", "提示!!!", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let params = {
        id: row.id,
      };
      let res = await deleteActivityById(params);
      if (res.code == 200) {
        getList();
        ElMessage({
          type: "success",
          showClose: true,
          message: res.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.message,
          center: true,
        });
      }
    })
    .catch(() => {
      tableLoading.value = false;
    });
};

// 确认添加员工
const submitAdd = lodash.debounce(async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        theme: ruleForm.theme,
        orgId: ruleForm.orgId.split(",")[1],
        orgName: ruleForm.orgId.split(",")[0],
        themeDetail: ruleForm.themeDetail,
        startTime: ruleForm.activeTime[0],
        endTime: ruleForm.activeTime[1],
        address: ruleForm.address,
        signsTime: ruleForm.signTime[0],
        signeTime: ruleForm.signTime[1],
        totalNumber: ruleForm.totalNumber,
      };
      let res = "";
      if (dialongTitle.value == "创建活动") {
        res = await insertActivity(data);
      } else {
        data.id = ruleForm.id;
        res = await updateActivity(data);
      }
      if (res.code == 200) {
        addDialogVisible.value = false;
        ElMessage({
          type: "success",
          showClose: true,
          message: res.message,
          center: true,
        });
        getList();
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.message,
          center: true,
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
}, 1000);

const cancelAdd = () => {
  addDialogVisible.value = false;
};

// 多选框功能
const handleSelectionChange = (val) => {
  // console.log(val);
  selectIds.value = val.map((i) => i.id);
  console.log(selectIds.value);
};

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 每页显示条数
const handleSizeChange = (value) => {
  console.log(value, "每页显示条数");
  pageSize.value = value;
  getList();
};
// 分页
const handleCurrentChange = (value) => {
  // console.log(value);
  currentPage.value = value;
  getList();
};

const statusList = async () => {
  let res = await queryStatus();
  console.log(res, "状态下拉");
  if (res.code == 200) {
    statusData.value = res.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
// 获取组织下拉列表数据
const clubList = async () => {
  loading.value = true;
  let params = {
    currentPage: pageParams.pageNum,
    pageCount: pageParams.pageSize,
    keyword: pageParams.keyword,
  };
  let res = await queryClubDatas(params);
  console.log(res, "获取组织下拉列表数据");
  if (res.code == 200) {
    loading.value = false;
    clubData.value = res.data.list;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};

const remoteMethod = (query) => {
  console.log(query);
  pageParams.keyword = query;
  loading.value = true;
  clubList().then(() =>{
    loading.value = false;
  })
};

onBeforeMount(() => {
  getList();
  statusList();
  clubList();
});
onUnmounted(() => {});
</script>

<style scoped lang="scss">
.scroll {
  width: calc(100% - 60px);
  height: calc(100% - 61px);
  margin: 0 auto;
  display: flex;
  flex-direction: column;

  .middle {
    width: calc(100%);
    color: #000;
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      .search {
        margin-left: 0 !important;
        color: #fff;
      }
      .condition {
        display: flex;
        align-items: center;
        margin: 10px 30px 10px 0;
        :deep(.el-input .el-input__inner) {
          font-size: 14px;
        }
        .el-select {
          width: 220px;
        }
        span {
          margin: 0 10px 0 0;
        }
      }
    }
    .gongneng {
      margin: 10px 0;
      .el-button {
        color: #fff;
        margin-right: 15px;
      }
    }
  }
  .footer {
    width: calc(100%);
    flex: 1;
    margin: 0 auto;
    overflow: auto;

    .el-table--fit {
      height: calc(100% - 60px);
      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 15px;
        color: #000;
        .cell {
          color: #000;
        }
      }
      :deep(.el-table__row) {
        height: 50px;
        font-size: 15px;
        color: #000;
      }
      :deep(.el-table__row td) {
        padding: 0;
        border: 0;
      }

      .el-button--primary {
        margin-left: 5px;
      }
      :deep(.el-table__body .even) {
        background-color: #fff;
      }
      :deep(.el-table__body .odd) {
        background-color: rgba(240, 243, 247, 1);
      }
    }

    .pageSize {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 0 30px;
      height: 60px;

      span {
        color: #000;
      }

      .el-pagination {
        // width: 1600px;
        :deep(.el-pagination__total) {
          color: #000;
        }

        :deep(.el-pagination__goto) {
          color: #000;
        }

        :deep(.el-pagination__classifier) {
          color: #000;
        }

        :deep(.el-input__wrapper) {
          border: 1px solid rgba(0, 0, 0, 1);
          border-radius: 5px;
          box-shadow: none;
        }

        :deep(.el-pager li) {
          margin: 0 5px;
          border: 1px solid rgba(0, 0, 0, 1);
          border-radius: 5px;
          background-color: transparent;
        }

        :deep(.el-pager li.is-active) {
          // background-color: rgba(0, 97, 255, 0.8);
          border: 1px solid rgba(0, 97, 255, 1);
          color: rgba(0, 97, 255, 1);
        }

        :deep(.btn-prev) {
          margin-right: 5px;
          border: 1px solid rgba(0, 0, 0, 1);
          border-radius: 5px;
          background-color: transparent;
        }

        :deep(.btn-next) {
          margin-left: 5px;
          border: 1px solid rgba(0, 0, 0, 1);
          border-radius: 5px;
          background-color: transparent;
        }
      }
    }
  }
}

// 添加员工弹窗样式
.addStaff {
  .el-dialog__body {
    padding: 20px 20px 10px 20px;
    .el-input {
      width: 400px;
    }
    .el-textarea {
      width: 400px;
    }
    .el-select {
      width: 400px;
    }
    .el-form-item {
      :deep(.el-form-item__content) {
        .el-cascader {
          .el-input {
            width: 400px;
          }
        }
      }
    }
  }
}

:deep(.tooltips) {
  .el-dialog__body {
    padding: 10px 20px 10px 20px;
  }
}
</style>
<style lang="scss">
/* 加载提示样式 */
.select-loading {
  padding: 8px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 优化下拉框高度，避免滚动不明显 */
.club-select {
  .el-select-dropdown__wrap {
    max-height: 250px !important; /* 限制下拉面板高度，触发滚动 */
  }
}
</style>
>
