<script>
import { defineComponent } from "vue";

export default defineComponent({
  beforeRouteEnter(to, from, next) {
    if (from.path !== "/addResearch" && from.path !== "/determineTravel" && from.path !== "/editResearch") {
      sessionStorage.removeItem("specialResearchListBack");
    }
    next();
  },
});
</script>

<script setup>
import { ref, watch, onMounted, reactive, computed, toRefs } from "vue";
import { raiInterface, raiSpecial } from "@/api/api.js";
import mPage from "@/components/mPage.vue";
import { inAdvanceOptions, tableColums, TabsTop, ConfirmOptions } from "../components/special/optionsTabs";
import ParticalDialog from "../components/particalDialog.vue";
import ApplyDialog from "../components/apply/applyDialog.vue";
import ParticularsAll from "./specialResearch/particularsAll.vue";
import SpecialResearchDlg from "../components/special/specialResearchDlg.vue";
import TemplateMessage from "../components/apply/templateMessage.vue";

import { ElMessageBox, ElMessage } from "element-plus";
import moment from "moment";

import { Search } from "@element-plus/icons-vue";

import { onBeforeRouteLeave, useRouter, useRoute } from "vue-router";
const $route = useRoute();
const $router = useRouter();

const pageState = reactive({
  status: "",
  industryValue: "",
  chartPermissionList: [],
  themeVal: "",
  dataList: [],
  page_no: 1,
  total: 0,
  dialogVisibleActivity: false,
  dialogTitle: "",
  activityDetail: {},
  previewList: [],
  interestData: [], //感兴趣人数
  exportInterest: "",
  tableColums: [],
  tabsActive: 1,
  offlineId: 0, //提交的ID
  dialogVisiblepartica: false, //到会详情的隐现
  particlaDlg: {
    isSpecial: true,
    title: "到会详情",
  }, //提交的标题
  submitDialog: false, //提交到会情况的隐现
  addDialogVisible: false,
  signUpAdd: "专项",
  addDialogType: "新增报名",

  particularsDialogVisible: false,
  dialogVisibleList: {},
  specialDetailId: 0,
  selectList: [],
  messageDialogVisible: false, // 发送模版消息
  selectionArr: {},
});

const options = computed(() => {
  return pageState.tabsActive == 1 ? inAdvanceOptions : ConfirmOptions;
});

const tabsTop = computed(() => {
  return TabsTop;
});

//点击了头部切换
function tabsHandle(item) {
  pageState.tabsActive = item.id;
  pageState.tableColums = tableColums(pageState.tabsActive);
  pageState.status = "";
  pageState.page_no = 1;
  getsDataList();
}
//change 变化
function changeHandel() {
  pageState.page_no = 1;
  getsDataList();
}
//分页
function handleCurrentChange(page) {
  pageState.page_no = page;
  getsDataList();
}
//获取表格
async function getsDataList() {
  const res = await raiSpecial.getSpecialList({
    PageSize: 10,
    CurrentIndex: pageState.page_no,
    PublishStatus: pageState.status ? Number(pageState.status) : 2,
    ChartPermissionId: pageState.industryValue,
    IsTrip: pageState.tabsActive == 2,
    KeyWord: pageState.themeVal,
  });
  if (res.Ret === 200) {
    pageState.dataList = res.Data.List;
    pageState.total = res.Data.Paging.Totals;
  }
}
//获取行业
function chartPermission() {
  raiInterface.getActivitySpecial().then((res) => {
    if (res.Ret === 200) {
      pageState.chartPermissionList = res.Data.List;
    }
  });
}
//获取调研主题详情
async function themeDetails(id) {
  pageState.specialDetailId = id;
  pageState.dialogVisibleActivity = true;
  pageState.dialogTitle = "活动详情";

  return;
  const res = await raiSpecial.specialDetail({ ActivityId: id });
  if (res.Ret === 200) {
    pageState.previewList = [];
    pageState.activityDetail = res.Data;
    pageState.previewList.push(pageState.tabsActive == 1 ? pageState.activityDetail.TripImgLink : pageState.activityDetail.TripImgLinkFix);
  }
}
//感兴趣人数
async function interestDetails(id) {
  pageState.specialDetailId = id;
  pageState.dialogTitle = "感兴趣人数";
  pageState.dialogVisibleActivity = true;
  return;
  const res = await raiSpecial.specialInterested({ ActivityId: id });
  if (res.Ret === 200) {
    pageState.exportInterest = `${import.meta.env.VITE_APP_API_ROOT}/cygx/special/export?${localStorage.getItem("auth") || ""}&ActivityId=${id}`;
    nextTick(() => {
      pageState.interestData = res.Data.List;
    });
  }
}
//发布、取消发布 、删除、下线、重新发布、取消发布
function applyHandleAllOperate(id, value) {
  ElMessageBox.confirm(`确定${value}该活动吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res =
        value == "删除"
          ? await raiSpecial.specialDelete({
              ActivityId: id,
            })
          : value == "发布"
          ? await raiSpecial.specialPublishAndCancel({
              ActivityId: id,
            })
          : value == "下线"
          ? await await raiSpecial.postSpecialOffline({
              ActivityId: id,
            })
          : value == "取消发布"
          ? await raiSpecial.specialPublishAndCancel({
              ActivityId: id,
            })
          : value == "重新发布" && pageState.tabsActive == 1
          ? await await await raiSpecial.postSpecialOffline({
              ActivityId: id,
            })
          : await await raiSpecial.specialPublishAndCancel({
              ActivityId: id,
            });

      if (res.Ret !== 200) return;
      ElMessage.success(`${value}成功!`);
      if (value == "删除") {
        let page_num = Math.ceil((pageState.total - 1) / 10);
        if (pageState.page_no > page_num) {
          pageState.page_no = page_num;
        }
      }
      getsDataList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: `已取消${value}`,
      });
    });
}
//点击了编辑
function editBtn(id, show, type = "") {
  type == ""
    ? $router.push({
        path: "/editResearch",
        query: { id, isShow: show },
      })
    : $router.push({
        path: "/determineTravel",
        query: { id },
      });
}
//提交到会情况
function particularsSubmit(id) {
  pageState.offlineId = id;
  pageState.submitDialog = true;
}
//到会详情
function particulars(id) {
  pageState.offlineId = id;
  pageState.dialogVisiblepartica = true;
}
function handleCloseSubject() {
  pageState.dialogTitle = "";
  pageState.exportInterest = "";
  pageState.activityDetail = {};
  pageState.dialogVisibleActivity = false;
}
//感兴趣人数总览
function interestHandler() {
  let routeUrl = $router.resolve("/interestAllPreview");
  window.open(routeUrl.href, "_blank");
}
function applyNum(item) {
  pageState.particularsDialogVisible = true;
  pageState.dialogVisibleList = item;
}
/* 表格行的样式 */
function handleRowStyle(key) {
  const style = {
    ResearchTheme: "color: #409eff; cursor: pointer",
    InterestedNum: "color: #409eff; cursor: pointer",
    SignupPeopleNum: "color: #409eff; cursor: pointer",
  };
  return style[key] ? style[key] : "";
}
/* 表格行的点击事件 */
function handleRowClick(row, key) {
  if (key === "ResearchTheme") {
    themeDetails(row.ActivityId);
  } else if (key === "InterestedNum") {
    interestDetails(row.ActivityId);
  } else if (key === "SignupPeopleNum") {
    applyNum(row);
  }
}
/* 表格行的数据处理 */
function handleRowContent(row, key) {
  if (key == "SpecialType") {
    return row[key] == 1 ? "线上" : `线下(${row["City"]})`;
  } else if (key == "PublishStatus") {
    return row[key] == 1
      ? "已发布"
      : row[key] == 0 && pageState.tabsActive == 1
      ? "未发布"
      : row[key] == 0 && pageState.tabsActive == 2
      ? "已取消"
      : row[key] == 3
      ? "已下线"
      : row[key] == 4
      ? "已确定行程"
      : "";
  } else if (key == "InterestedNum") {
    return row[key] ? row[key] : "";
  } else {
    return row[key];
  }
}
// 新增活动报名
function addapply() {
  if (!this.selectList) returnElMessage.error("请先选择活动");
  pageState.addDialogVisible = true;
}
// 新增活动报名的表格选择
function selectChange(selection) {
  pageState.selectionArr = selection;
  let arr = [];
  selection.forEach((item) => {
    arr.push(item.ActivityId);
  });
  pageState.selectList = arr.join(",");
}
// 判断活动时间对比当前时间
function isStart(val) {
  return moment().isBefore(val);
}
// 主题名称的输入框
function themeInput() {
  pageState.page_no = 1;
  pageState.status = "";
  pageState.industryValue = "";
  getsDataList();
}
// 发送模版消息
function sendMessage() {
  if (pageState.selectList && pageState.selectList.split(",").length === 1) {
    pageState.messageDialogVisible = true;
  } else {
    ElMessage.error("请选择一个活动");
  }
}

onMounted(() => {
  if (sessionStorage.getItem("specialResearchListBack")) {
    let { tabsActive, page, status, industryValue, themeVal } = JSON.parse(sessionStorage.getItem("specialResearchListBack"));
    pageState.themeVal = themeVal;
    pageState.page_no = page;
    pageState.tabsActive = tabsActive;
    pageState.status = status;
    pageState.industryValue = industryValue;
  }
  chartPermission();
  getsDataList();
  pageState.tableColums = tableColums(pageState.tabsActive);
});

onBeforeRouteLeave((to, from, next) => {
  let obj = {
    page: pageState.page_no,
    tabsActive: pageState.tabsActive,
    status: pageState.status,
    industryValue: pageState.industryValue,
    themeVal: pageState.themeVal,
  };
  sessionStorage.setItem("specialResearchListBack", JSON.stringify(obj));
  next();
});

const {
  status,
  industryValue,
  chartPermissionList,
  themeVal,
  dataList,
  page_no,
  total,
  dialogVisibleActivity,
  dialogTitle,
  activityDetail,
  previewList,
  interestData, //感兴趣人数
  exportInterest,
  tableColums,
  tabsActive,
  offlineId, //提交的ID
  dialogVisiblepartica, //到会详情的隐现
  particlaDlg, //提交的标题
  submitDialog, //提交到会情况的隐现
  addDialogVisible,
  signUpAdd,
  addDialogType,
  particularsDialogVisible,
  dialogVisibleList,
  specialDetailId,
  selectList,
  messageDialogVisible, // 发送模版消息
  selectionArr,
} = toRefs(pageState);
</script>

<template>
  <div class="container special-research">
    <div class="top-wrap">
      <div class="tabs-content">
        <span @click="tabsHandle(item)" :class="['item', tabsActive == item.id && 'active-item']" v-for="item in tabsTop" :key="item.id">{{ item.name }}</span>
      </div>
    </div>
    <div class="top-wrap">
      <div>
        <el-button v-if="tabsActive == 2" type="primary" style="margin-right: 20px" @click="addapply">新增报名</el-button>
        <el-button v-if="tabsActive == 2" type="primary" @click="sendMessage" style="margin-right: 20px">发送模板消息</el-button>
        <el-select placeholder="请选择行业" clearable v-model="industryValue" @change="changeHandel" style="margin: 0 20px 20px 0">
          <el-option v-for="item in chartPermissionList" :label="item.PermissionName" :key="item.ChartPermissionId" :value="item.ChartPermissionId"></el-option>
        </el-select>
        <el-select placeholder="发布状态" clearable v-model="status" @change="changeHandel" style="margin: 0 30px 20px 0">
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <template v-if="tabsActive == 1">
          <el-button style="margin-bottom: 20px" type="primary" @click="$router.push('/addResearch')">添加活动</el-button>
          <el-button style="margin-bottom: 20px" type="primary" @click="interestHandler">客户兴趣总览</el-button>
        </template>
      </div>
      <div style="width: 520px">
        <el-input v-model="themeVal" @input="themeInput" placeholder="请输入主题名称" clearable :prefix-icon="Search"> </el-input>
      </div>
    </div>
    <el-card>
      <el-table @selection-change="selectChange" :data="dataList" style="width: 100%; margin-top: 20px" border>
        <el-table-column v-if="tabsActive == 2" align="center" type="selection" width="55"> </el-table-column>
        <el-table-column v-for="item in tableColums" :key="item.label" :label="item.label" :width="item.widthsty" :min-width="item.minwidthsty" align="center">
          <template #default="{ row }">
            <span @click="handleRowClick(row, item.key)" :style="handleRowStyle(item.key)">{{ handleRowContent(row, item.key) }}</span>
          </template>
        </el-table-column>
        <el-table-column width="230" prop="" align="center" label="操作">
          <template #default="{ row }">
            <div v-if="tabsActive == 1">
              <template v-if="row.PublishStatus !== 4">
                <span class="editsty" v-if="row.PublishStatus == 1" @click="applyHandleAllOperate(row.ActivityId, '下线')">下线 &nbsp;&nbsp;</span>
                <span class="editsty" v-if="row.PublishStatus == 3" @click="applyHandleAllOperate(row.ActivityId, '重新发布')">重新发布 &nbsp;&nbsp;</span>
                <span v-if="row.PublishStatus == 0" class="editsty" @click="applyHandleAllOperate(row.ActivityId, '发布')">发布 &nbsp;&nbsp;</span>
                <span class="editsty" @click="editBtn(row.ActivityId, row.PublishStatus, '')">编辑 &nbsp;&nbsp;</span>
                <span class="editsty" v-if="row.PublishStatus == 1" @click="editBtn(row.ActivityId, row.PublishStatus, '行程')">确定行程</span>
                <span class="deletesty" v-if="row.PublishStatus == 0" @click="applyHandleAllOperate(row.ActivityId, '删除')">删除</span>
              </template>
            </div>
            <div v-else>
              <span class="editsty" v-if="row.PublishStatus == 1 && isStart(row.ActivityTime)" @click="applyHandleAllOperate(row.ActivityId, '取消发布')">取消发布 &nbsp;&nbsp;</span>
              <span class="editsty" v-if="row.PublishStatus !== 1" @click="applyHandleAllOperate(row.ActivityId, '重新发布')">重新发布 &nbsp;&nbsp;</span>
              <span class="editsty" @click="editBtn(row.ActivityId, row.PublishStatus, '行程')">编辑 &nbsp;&nbsp;</span>
              <span class="editsty" v-if="row.IsShowUpdateMeeting" @click="particularsSubmit(row.ActivityId)"> 修改到会情况 </span>
              <span class="editsty" v-if="row.IsShowSubmitMeeting" @click="particularsSubmit(row.ActivityId)"> 提交到会情况 </span>
              <span class="editsty" v-if="row.IsShowAttendanceDetails" @click="particulars(row.ActivityId)">&nbsp;&nbsp;到会详情</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-col :span="24" class="toolbar">
        <m-page :total="total" :page_no="page_no" :pageSize="10" @handleCurrentChange="handleCurrentChange" />
      </el-col>
    </el-card>
    <special-research-dlg :specialDetailId="specialDetailId" v-model:dialogVisibleActivity="dialogVisibleActivity" :dialogTitle="dialogTitle" :tabsActive="tabsActive" />
    <partical-dialog @getsDataList="getsDataList" @particulars="particulars" :offlineId="offlineId" v-model:dialogVisiblepartica="dialogVisiblepartica" :particlaDlg="particlaDlg" v-model:submitDialog="submitDialog" />
    <apply-dialog v-model:addDialogVisible="addDialogVisible" :selectList="selectList" :signUpAdd="signUpAdd" :addDialogType="addDialogType" @getsDataList="getsDataList" />
    <particulars-all v-model:particularsDialogVisible="particularsDialogVisible" :dialogVisibleList="dialogVisibleList"  @getsDataList="getsDataList"/>
    <template-message v-model:messageDialog="messageDialogVisible" :selectionArr="selectionArr" typeMessage="确定行程" />
  </div>
</template>

<style scoped lang="scss">
.special-research {
  .top-wrap {
    margin-bottom: 28px;
    padding: 20px 30px 0;
    background: #fff;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-between;
  }
  .tabs-content {
    display: flex;
    padding-bottom: 20px;
    .item {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 18px;
      height: 40px;
      background: #ecf5ff;
      border-radius: 4px 4px 4px 4px;
      border: 1px solid #b3d8ff;
      margin-right: 20px;
      color: #3385ff;
      font-size: 16px;
      cursor: pointer;
    }
    .active-item {
      height: 40px;
      background: #409eff;
      color: #fff;
    }
  }
  .rai-detail-wrap {
    .activity-top {
      width: 100%;
      height: 55px;
      background: #f4f4f4;
      border-radius: 4px 4px 4px 4px;
      opacity: 1;
      line-height: 55px;
      padding-left: 23px;
      margin-bottom: 30px;
    }
    p {
      margin-bottom: 20px;
      padding-left: 10px;
    }
    .arrange {
      margin: 50px auto 20px;
      cursor: pointer;
      text-align: center;
      color: #3385ff;
    }
    .text-box {
      display: flex;
      padding-left: 10px;
      span {
        display: block;
        margin-bottom: 10px;
      }
    }
  }
  .dialog-footer {
    text-align: center;
    margin-bottom: 20px;
  }
}
</style>
