<script setup>
import { ref, watch, onMounted, reactive, computed, toRefs } from "vue";
import { raiInterface } from "@/api/api.js";
import { onBeforeRouteLeave, useRouter, useRoute } from "vue-router";
import { Search } from "@element-plus/icons-vue";
import mPage from "@/components/mPage.vue";
import { ElMessageBox, ElMessage } from "element-plus";

import ApplyDialog from "../components/apply/applyDialog.vue";
import ParticularsDialog from "../components/apply/particularsDialog.vue";
import AtcParticulars from "../components/atcParticulars.vue";
import GenerationAsk from "../components/generationAsk.vue";
import SummaryRemind from "../components/apply/summaryRemind.vue";
import { ListTitle, purchaserListTitle, TableApplyColums, StatusSelect, PublishSelect } from "../components/apply/applyTableColums";
import TemplateMessage from "../components/apply/templateMessage.vue";

const $route = useRoute();
const $router = useRouter();

const pageState = reactive({
  tabsSelectionOne: true,
  dataList: [], //表格的列表
  page_no: sessionStorage.getItem("interviewListBack") ? JSON.parse(sessionStorage.getItem("interviewListBack")).page_no : 1,
  total: 0, //条数
  PageSize: 10, //每页显示几条
  industry: "", //行业
  cactivityTypeVal: "", //活动
  issueTime: "", //时间
  selectList: "", //新增外呼人员的id
  chartPermissionList: [], //行业的数组
  cactivityTypeList: [], //活动类型
  addDialogVisible: false, //新增外呼的弹框
  particularsDialogVisible: false, //报名详情弹框
  subscribe: "", //预约外呼弹框的tittle
  titleValue: "", //标题关键词
  tabsPitchonType: 1,
  dialogVisible: false, //文章详情
  detailData: {}, //文章详情数据
  dialogVisibleId: "", //弹框id
  reminder: false, //提示
  generaitondialogVisib: false, //代问的弹框
  generaitonId: "",
  generaitonType: "报名",
  numberFull: false, //
  tableApplyColums: [],
  signUpAdd: "",
  minimumSummation: "",
  numberLimi: false, //
  addDialogType: "新增外呼人员",
  summaryRemindDlg: false, //预约纪要、会议提醒
  isShowAppointment: true, //是 预约纪要、会议提醒
  activityTypeName: [],
  cactivityStatus: 1,
  publishStatus: "1", //发布状态
  messageDialogVisible: false, //发送消息模版
  isResearchPoints: false, //
});

// 弘则 研选 是否是研选
const isResearch = computed(() => {
  return $route.path.indexOf("purchaser") != -1 ? true : false;
});

const listTitle = computed(() => {
  return !isResearch.value ? ListTitle : purchaserListTitle;
});

const statusSelect = computed(() => {
  return StatusSelect;
});

const publishSelect = computed(() => {
  return PublishSelect;
});

const tabsBtnName = computed(() => {
  return pageState.tabsPitchonType == 1 ? "新增报名" : "新增外呼人员";
});

watch(
  () => pageState.titleValue,
  () => {
    pageState.page_no = 1;
    init();
    getsDataList();
  }
);

function init() {
  pageState.issueTime = "";
  pageState.industry = "";
  pageState.cactivityTypeVal = "";
}
//头部tabs
function tabsBoxBtn(item, index) {
  pageState.tabsPitchonType = item.ChartPermissionId;
  pageState.tableApplyColums = TableApplyColums(item.ChartPermissionId);
  pageState.cactivityTypeVal = "";
  pageState.isResearchPoints = false;
  pageState.tabsSelectionOne = item.ChartPermissionId == 2 || item.ChartPermissionId == 5 ? false : true;
  pageState.page_no = 1;
  getsDataList();
}
//列表表格
function getsDataList() {
  raiInterface
    .activitySignup({
      CurrentIndex: pageState.page_no,
      PageSize: pageState.PageSize,
      StartDate: pageState.issueTime[0],
      EndDate: pageState.issueTime[1],
      KeyWord: pageState.titleValue,
      SearchType: pageState.tabsPitchonType,
      ChartPermissionId: pageState.industry,
      ActivityTypeId: pageState.cactivityTypeVal,
      ActiveState: pageState.cactivityStatus,
      PublishStatus: pageState.publishStatus ? Number(pageState.publishStatus) : 2,
      IsResearch: isResearch.value,
    })
    .then((res) => {
      if (res.Ret !== 200) return;
      pageState.dataList = res.Data.List;
      pageState.total = res.Data.Paging.Totals;
    });
}
//添加新增外呼人员
function addOutbound(type) {
  if (!pageState.selectList) {
    ElMessage.warning("请先选择活动");
  } else if (pageState.tabsPitchonType == 1 && pageState.isGenre) {
    return ElMessage.warning("活动类型不同，无法同时新增报名");
  } else {
    if (type == "新增外呼人员") {
      if (pageState.reminder && pageState.tabsPitchonType !== 1) return ElMessage.warning("当前活动无法新增外呼人员");
      pageState.addDialogVisible = true;
    } else {
      if (!pageState.isShowAppointment && type === "新增预约纪要") return ElMessage.error("该活动无法预约纪要");
      pageState.addDialogVisible = true;
    }
    pageState.addDialogType = type;
  }
}
//表格选择复选框的事件
function selectChange(selection, row) {
  const arr = [];
  const num = [];
  const summation = [];
  const genre = [];
  let minimum = [];
  let isResearch = [];
  pageState.selectionArr = selection;
  selection.forEach((item) => {
    arr.push(item.ActivityId);
    num.push(item.LimitPeopleNum);
    summation.push(item.SignupPeopleNum);
    genre.push(item.ActivityTypeName);
    isResearch.push(item.IsResearchPoints);
    minimum.push(item.LimitPeopleNum - item.SignupPeopleNum);
  });
  pageState.activityTypeName = genre;
  pageState.isShowAppointment = selection.every((item) => item.IsShowAppointment == true);
  const str = arr.join(",");
  pageState.reminder = num.some((item) => item > 0);
  pageState.selectList = str;
  pageState.isGenre = new Set(genre).size > 1 ? true : false;
  if (pageState.tabsPitchonType !== 1 && (selection[0] ? selection[0].LimitPeopleNum > 0 : true)) {
    num.forEach((item) => {
      pageState.numberFull = summation.some((key) => key >= item);
    });
  }
  if (pageState.tabsPitchonType !== 1) {
    pageState.tabsPitchonType == 3 && isResearchHandler(isResearch);
    pageState.minimumSummation = Math.min(...minimum);
    pageState.numberLimi = num.includes(0) && num.some((item) => item > 0);
  }
}
// 公司调研下的判断
function isResearchHandler(isResearch) {
  if (isResearch && isResearch.length > 1) {
    for (let i = 0; i < isResearch.length - 1; i++) {
      if (isResearch[i] !== isResearch[i + 1]) {
        pageState.isResearchPoints = true;
        break;
      }
    }
  } else {
    pageState.isResearchPoints = false;
  }
}
//报名详情的弹框
function particularsBtn(val, id) {
  pageState.dialogVisibleId = id;
  pageState.subscribe = val;
  if (val === "会议提醒人数" || val === "纪要预约人数") {
    pageState.summaryRemindDlg = true;
  } else {
    pageState.particularsDialogVisible = true;
  }
}
//change事件
function conditionChange() {
  pageState.page_no = 1;
  getsDataList();
}
//获取行业
function chartPermission() {
  raiInterface.chartPermission({ IsHideResearch: !isResearch.value }).then((res) => {
    if (res.Ret === 200) {
      pageState.chartPermissionList = res.Data.List;
    }
  });
}
//活动类型
function activityType() {
  raiInterface
    .activitySignuplistSearch({
      SearchType: pageState.tabsPitchonType,
    })
    .then((res) => {
      if (res.Ret === 200) {
        pageState.cactivityTypeList = res.Data.List;
      }
    });
}
//分页
function handleCurrentChange(page) {
  pageState.page_no = page;
  getsDataList();
}
//点击标题的弹框
function titleBtnClick(id) {
  raiInterface.activityDetail({ ActivityId: Number(id) }).then((res) => {
    if (res.Ret == 200) {
      pageState.detailData = res.Data;
    }
  });
  pageState.dialogVisible = true;
}
//点击代问的弹框
function inquireBtn(id) {
  pageState.generaitondialogVisib = true;
  pageState.generaitonId = id;
}
//新增报名
function addapply() {
  if (!pageState.selectList) {
    return ElMessage.warning("请先选择活动");
  } else if (pageState.isGenre) {
    return ElMessage.warning("活动类型不同，无法同时新增报名");
  } else if (pageState.isResearchPoints && pageState.tabsPitchonType == 3) {
    return ElMessage.warning("所选活动无法同时新增报名");
  } else {
    if (pageState.numberLimi && pageState.tabsPitchonType !== 4) {
      return ElMessage.warning("不限人数的电话会请新增外呼人员，限制人数的电话会请新增报名");
    } else if (pageState.numberFull && pageState.tabsPitchonType !== 4) {
      return ElMessage.warning("新增失败，活动人数超限。");
    }
    pageState.signUpAdd = pageState.activityTypeName.includes("公司调研电话会（易董）") ? "易董" : pageState.tabsPitchonType == 4 ? "c类" : "报名";
    pageState.addDialogType = "新增报名";
    pageState.addDialogVisible = true;
  }
}
/* 表格行的样式 */
function handleRowStyle(key, row) {
  if (["ActivityName", "SignupPeopleNum", "AppointmentPeopleNum", "AskNum"].includes(key)) {
    return row.PublishStatus == 3 ? "cursor: pointer" : "color: #409eff; cursor: pointer";
  }
  return "";
}
/* 表格行的点击事件 */
function handleRowClick(row, key) {
  switch (key) {
    case "ActivityName":
      titleBtnClick(row.ActivityId);
      break;
    case "SignupPeopleNum":
      particularsBtn("报名详情", row.ActivityId);
      break;
    case "AppointmentPeopleNum":
      particularsBtn("纪要预约人数", row.ActivityId);
      break;
    case "AskNum":
      inquireBtn(row.ActivityId);
      break;
    default:
      "";
  }
}
/* 表格行的数据处理 */
function handleRowContent(row, key) {
  if (["LimitPeopleNum"].includes(key)) {
    return row[key] > 0 && !row.YidongActivityId ? row[key] : "--";
  } else if (key == "ActiveState") {
    let status = row[key] == 1 ? "未开始" : row[key] == 2 ? "进行中" : "已结束";
    return status;
  } else if (key == "PublishStatus") {
    let status = row["PublishStatus"] == 1 ? "已发布" : row["PublishStatus"] == 2 ? "未发布" : "已取消";
    return status;
  } else {
    return row[key];
  }
}
// 发送模版消息
function sendMessage() {
  if (pageState.selectList && pageState.selectList.split(",").length === 1) {
    pageState.messageDialogVisible = true;
  } else {
    ElMessage.error("请选择一个活动");
  }
}

onMounted(() => {
  pageState.tableApplyColums = TableApplyColums(1);
  !isResearch.value && chartPermission();
  getsDataList();
});

const {
  tabsSelectionOne,
  dataList, //表格的列表
  page_no,
  total, //条数
  PageSize, //每页显示几条
  industry, //行业
  cactivityTypeVal, //活动
  issueTime, //时间
  selectList, //新增外呼人员的id
  chartPermissionList, //行业的数组
  cactivityTypeList, //活动类型
  addDialogVisible, //新增外呼的弹框
  particularsDialogVisible, //报名详情弹框
  subscribe, //预约外呼弹框的tittle
  titleValue, //标题关键词
  tabsPitchonType,
  dialogVisible, //文章详情
  detailData, //文章详情数据
  dialogVisibleId, //弹框id
  reminder, //提示
  generaitondialogVisib, //代问的弹框
  generaitonId,
  generaitonType,
  numberFull, //
  tableApplyColums,
  signUpAdd,
  minimumSummation,
  numberLimi, //
  addDialogType,
  summaryRemindDlg, //预约纪要、会议提醒
  isShowAppointment, //是 预约纪要、会议提醒
  activityTypeName,
  cactivityStatus,
  publishStatus, //发布状态
  messageDialogVisible, //发送消息模版
  isResearchPoints, //
} = toRefs(pageState);
</script>

<template>
  <div class="container-apply">
    <!-- 头部el-card -->
    <div class="top-wrap" style="margin-bottom: 20px">
      <div class="top-card-box">
        <div class="tabs-box">
          <span v-for="(item, index) in listTitle" :key="item.ChartPermissionId" @click="tabsBoxBtn(item, index)" :class="item.ChartPermissionId == tabsPitchonType ? 'pitch' : ''">{{
            item.PermissionName
          }}</span>
        </div>
        <div>
          <el-input v-model="titleValue" style="width: 521px" placeholder="请输入活动名称" clearable :prefix-icon="Search"> </el-input>
        </div>
      </div>
    </div>
    <!-- 内容el-card -->
    <el-card>
      <!-- 选择部分 -->
      <div class="screen-box">
        <div class="screen-button">
          <template v-if="tabsPitchonType !== 3">
            <el-button type="primary" v-if="tabsSelectionOne && tabsPitchonType !== 4" @click="addOutbound(tabsBtnName)">{{ tabsBtnName }}</el-button>
            <el-button v-if="tabsPitchonType !== 1" type="primary" @click="addapply">新增报名</el-button>
          </template>
          <!-- 公司调研下的单独按钮 -->
          <template v-if="tabsPitchonType === 3">
            <!-- <el-tooltip class="item" effect="dark" content="不限人数的公司调研电话会请点此" placement="bottom">
              <el-button type="primary" v-if="tabsSelectionOne" @click="addOutbound('新增外呼人员')">新增外呼人员</el-button>
            </el-tooltip> -->
            <el-tooltip class="item" effect="dark" content="公司线下调研、限制人数的公司调研电话会请点此" placement="bottom">
              <el-button v-if="tabsPitchonType !== 1" type="primary" @click="addapply">新增报名</el-button>
            </el-tooltip>
          </template>
          <el-button type="primary" @click="addOutbound('新增预约纪要')">新增预约纪要</el-button>
          <el-button type="primary" @click="sendMessage">发送模板消息</el-button>
        </div>
        <div>
          <el-select placeholder="行业" clearable v-model="industry" @change="conditionChange" style="margin-bottom: 20px" v-if="!isResearch">
            <el-option v-for="item in chartPermissionList" :label="item.PermissionName" :key="item.ChartPermissionId" :value="item.ChartPermissionId"></el-option>
          </el-select>
          <el-select placeholder="活动类型" clearable @focus="activityType" v-model="cactivityTypeVal" @change="conditionChange" style="margin-bottom: 20px">
            <el-option v-for="item in cactivityTypeList" :label="item.ActivityTypeName" :key="item.ActivityTypeId" :value="item.ActivityTypeId"></el-option>
          </el-select>
          <date-picker v-model="issueTime" type="date" range placeholder="活动时间" value-type="format" @change="conditionChange"> </date-picker>
          <el-select placeholder="活动状态" clearable v-model="cactivityStatus" @change="conditionChange" style="margin-bottom: 20px">
            <el-option v-for="item in statusSelect" :label="item.name" :key="item.value" :value="item.value"></el-option>
          </el-select>
          <el-select placeholder="发布状态" clearable v-model="publishStatus" @change="conditionChange" style="margin-bottom: 20px">
            <el-option v-for="item in publishSelect" :label="item.name" :key="item.value" :value="item.value"></el-option>
          </el-select>
        </div>
      </div>
      <!-- 表格部分 -->
      <el-table @selection-change="selectChange" :data="dataList" style="width: 100%; margin-top: 15px" border ref="multipleTable">
        <el-table-column type="selection" align="center" key="ActivityId"></el-table-column>
        <el-table-column v-for="item in tableApplyColums" :key="item.label" :label="item.label" :width="item.widthsty" :min-width="item.minwidthsty" align="center">
          <template #header>
            <span>{{ item.label }}</span>
            <el-tooltip
              :content="`总报名人数已满、单机构报名人数满2人、爽约次数超限，仍点击${item.label === '预约失败人数' ? '预约外呼' : '报名'}的客户`"
              placement="top-start"
              v-if="item.key === 'SignupFailPeopleNum'"
            >
              <i class="el-icon-info" />
            </el-tooltip>
          </template>
          <template #default="{ row }">
            <div v-if="item.key == 'ReminderPeopleNum'">
              <span v-if="row.ReminderPeopleNum > 0" class="editsty" @click="particularsBtn('会议提醒人数', row.ActivityId)">{{ row.ReminderPeopleNum }}</span>
              <span v-else>--</span>
            </div>
            <div v-else-if="item.key == 'SignupFailPeopleNum'">
              <span v-if="row.SignupFailPeopleNum == 0">--</span>
              <span v-else class="editsty" @click="particularsBtn('报名失败详情', row.ActivityId)">{{ row.SignupFailPeopleNum }}</span>
            </div>
            <span v-else @click="handleRowClick(row, item.key)" :style="handleRowStyle(item.key, row)">{{ handleRowContent(row, item.key) }}</span>
          </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>
    <!-- 详情弹框 -->
    <atc-particulars v-model:dialogVisible="dialogVisible" v-model:detailData="detailData" />
    <!-- 新增外呼的弹框 -->
    <apply-dialog
      v-model:addDialogVisible="addDialogVisible"
      :dialogVisibleId="dialogVisibleId"
      :selectList="selectList"
      :signUpAdd="signUpAdd"
      :addDialogType="addDialogType"
      :tabsPitchonType="tabsPitchonType"
      :minimumSummation="minimumSummation"
      :selectionArr="selectionArr"
      @getsDataList="getsDataList"
    />
    <!-- 报名详情弹框 -->
    <particulars-dialog @getsDataList="getsDataList" :dialogVisibleId="dialogVisibleId" v-model:particularsDialogVisible="particularsDialogVisible" :subscribe="subscribe" />
    <generation-ask :generaitonType="generaitonType" v-model:generaitondialogVisib="generaitondialogVisib" :generaitonId="generaitonId" />
    <summary-remind :dialogVisibleId="dialogVisibleId" v-model:summaryRemindDlg="summaryRemindDlg" :subscribe="subscribe" @getsDataList="getsDataList" />
    <template-message v-model:messageDialog="messageDialogVisible" :selectionArr="selectionArr" />
  </div>
</template>

<style scoped lang="scss">
.container-apply {
  .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);
  }
  .top-card-box {
    display: flex;
    justify-content: space-between;
    .tabs-box {
      span {
        display: inline-block;
        padding: 9px 24px;
        background-color: #e9f4ff;
        border: 1px solid #b3d8ff;
        border-radius: 4px;
        margin-right: 30px;
        margin-bottom: 20px;
        color: #409eff;
        cursor: pointer;
      }
      .pitch {
        background-color: #409eff;
        border: none;
        color: #fff;
      }
    }
  }
  .screen-box {
    display: flex;
    :first-child {
      margin-right: 10px;
    }
    .el-select {
      margin-right: 25px;
    }
  }
  .mx-datepicker {
    width: 220px !important;
    margin-right: 25px;
  }
  .screen-button {
    display: flex;
    flex-wrap: wrap;
    .el-button {
      height: 40px;
      margin-right: 20px;
      margin-left: 0;
    }
  }
}
</style>
