<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>
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </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 slot-scope="{ 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 :dialogVisible.sync="dialogVisible" :detailData.sync="detailData" />
    <!-- 新增外呼的弹框 -->
    <apply-dialog
      :addDialogVisible.sync="addDialogVisible"
      :dialogVisibleId="dialogVisibleId"
      :selectList="selectList"
      :signUpAdd="signUpAdd"
      :addDialogType="addDialogType"
      :tabsPitchonType="tabsPitchonType"
      :minimumSummation="minimumSummation"
      :selectionArr="selectionArr"
    />
    <!-- 报名详情弹框 -->
    <particulars-dialog :dialogVisibleId="dialogVisibleId" :particularsDialogVisible.sync="particularsDialogVisible" :subscribe="subscribe" />
    <generation-ask :generaitonType="generaitonType" :generaitondialogVisib.sync="generaitondialogVisib" :generaitonId="generaitonId" />
    <summary-remind :dialogVisibleId="dialogVisibleId" :summaryRemindDlg.sync="summaryRemindDlg" :subscribe="subscribe" />
    <template-message :messageDialog.sync="messageDialogVisible" :selectionArr="selectionArr" />
  </div>
</template>

<script>
import { raiInterface } from "@/api/api.js";
import mPage from "@/components/mPage.vue";
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";
export default {
  name: "",
  components: { ApplyDialog, ParticularsDialog, mPage, AtcParticulars, GenerationAsk, SummaryRemind, TemplateMessage },
  props: {},
  data() {
    return {
      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, //
    };
  },
  computed: {
    // 弘则 研选 是否是研选
    isResearch() {
      return this.$route.path.indexOf("purchaser") != -1 ? true : false;
    },
    listTitle() {
      return !this.isResearch ? ListTitle : purchaserListTitle;
    },
    statusSelect() {
      return StatusSelect;
    },
    publishSelect() {
      return PublishSelect;
    },
    tabsBtnName() {
      return this.tabsPitchonType == 1 ? "新增报名" : "新增外呼人员";
    },
  },
  watch: {
    titleValue() {
      this.page_no = 1;
      this.init();
      this.getsDataList();
    },
  },
  created() {},
  mounted() {
    this.tableApplyColums = TableApplyColums(1);
    !this.isResearch && this.chartPermission();
    this.getsDataList();
  },
  methods: {
    init() {
      this.issueTime = "";
      this.industry = "";
      this.cactivityTypeVal = "";
    },
    //头部tabs
    tabsBoxBtn(item, index) {
      this.tabsPitchonType = item.ChartPermissionId;
      this.tableApplyColums = TableApplyColums(item.ChartPermissionId);
      this.cactivityTypeVal = "";
      this.isResearchPoints = false;
      this.tabsSelectionOne = item.ChartPermissionId == 2 || item.ChartPermissionId == 5 ? false : true;
      this.page_no = 1;
      this.getsDataList();
    },
    //列表表格
    getsDataList() {
      raiInterface
        .activitySignup({
          CurrentIndex: this.page_no,
          PageSize: this.PageSize,
          StartDate: this.issueTime[0],
          EndDate: this.issueTime[1],
          KeyWord: this.titleValue,
          SearchType: this.tabsPitchonType,
          ChartPermissionId: this.industry,
          ActivityTypeId: this.cactivityTypeVal,
          ActiveState: this.cactivityStatus,
          PublishStatus: this.publishStatus ? Number(this.publishStatus) : 2,
          IsResearch: this.isResearch,
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          this.dataList = res.Data.List;
          this.total = res.Data.Paging.Totals;
        });
    },
    //添加新增外呼人员
    addOutbound(type) {
      if (!this.selectList) {
        this.$message.warning("请先选择活动");
      } else if (this.tabsPitchonType == 1 && this.isGenre) {
        return this.$message.warning("活动类型不同，无法同时新增报名");
      } else {
        if (type == "新增外呼人员") {
          if (this.reminder && this.tabsPitchonType !== 1) return this.$message.warning("当前活动无法新增外呼人员");
          this.addDialogVisible = true;
        } else {
          if (!this.isShowAppointment && type === "新增预约纪要") return this.$message.error("该活动无法预约纪要");
          this.addDialogVisible = true;
        }
        this.addDialogType = type;
      }
    },
    //表格选择复选框的事件
    selectChange(selection, row) {
      const arr = [];
      const num = [];
      const summation = [];
      const genre = [];
      let minimum = [];
      let isResearch = [];
      this.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);
      });
      this.activityTypeName = genre;
      this.isShowAppointment = selection.every((item) => item.IsShowAppointment == true);
      const str = arr.join(",");
      this.reminder = num.some((item) => item > 0);
      this.selectList = str;
      this.isGenre = new Set(genre).size > 1 ? true : false;
      if (this.tabsPitchonType !== 1 && (selection[0] ? selection[0].LimitPeopleNum > 0 : true)) {
        num.forEach((item) => {
          this.numberFull = summation.some((key) => key >= item);
        });
      }
      if (this.tabsPitchonType !== 1) {
        console.log(isResearch, isResearch.length);
        this.tabsPitchonType == 3 && this.isResearchHandler(isResearch);
        this.minimumSummation = Math.min(...minimum);
        this.numberLimi = num.includes(0) && num.some((item) => item > 0);
      }
    },
    // 公司调研下的判断
    isResearchHandler(isResearch) {
      if (isResearch && isResearch.length > 1) {
        for (let i = 0; i < isResearch.length - 1; i++) {
          if (isResearch[i] !== isResearch[i + 1]) {
            this.isResearchPoints = true;
            break;
          }
        }
      } else {
        this.isResearchPoints = false;
      }
    },
    //报名详情的弹框
    particularsBtn(val, id) {
      this.dialogVisibleId = id;
      this.subscribe = val;
      if (val === "会议提醒人数" || val === "纪要预约人数") {
        this.summaryRemindDlg = true;
      } else {
        this.particularsDialogVisible = true;
      }
    },
    //change事件
    conditionChange() {
      this.page_no = 1;
      this.getsDataList();
    },
    //获取行业
    chartPermission() {
      raiInterface.chartPermission({ IsHideResearch: !this.isResearch }).then((res) => {
        if (res.Ret === 200) {
          this.chartPermissionList = res.Data.List;
        }
      });
    },
    //活动类型
    activityType() {
      raiInterface
        .activitySignuplistSearch({
          SearchType: this.tabsPitchonType,
        })
        .then((res) => {
          if (res.Ret === 200) {
            this.cactivityTypeList = res.Data.List;
          }
        });
    },
    //分页
    handleCurrentChange(page) {
      this.page_no = page;
      this.getsDataList();
    },
    //点击标题的弹框
    titleBtnClick(id) {
      raiInterface.activityDetail({ ActivityId: Number(id) }).then((res) => {
        if (res.Ret == 200) {
          this.detailData = res.Data;
        }
      });
      this.dialogVisible = true;
    },
    //点击代问的弹框
    inquireBtn(id) {
      this.generaitondialogVisib = true;
      this.generaitonId = id;
    },
    //新增报名
    addapply() {
      if (!this.selectList) {
        return this.$message.warning("请先选择活动");
      } else if (this.isGenre) {
        return this.$message.warning("活动类型不同，无法同时新增报名");
      } else if (this.isResearchPoints && this.tabsPitchonType == 3) {
        return this.$message.warning("所选活动无法同时新增报名");
      } else {
        if (this.numberLimi && this.tabsPitchonType !== 4) {
          return this.$message.warning("不限人数的电话会请新增外呼人员，限制人数的电话会请新增报名");
        } else if (this.numberFull && this.tabsPitchonType !== 4) {
          return this.$message.warning("新增失败，活动人数超限。");
        }
        this.signUpAdd = this.activityTypeName.includes("公司调研电话会（易董）") ? "易董" : this.tabsPitchonType == 4 ? "c类" : "报名";
        this.addDialogType = "新增报名";
        this.addDialogVisible = true;
      }
    },
    /* 表格行的样式 */
    handleRowStyle(key, row) {
      if (["ActivityName", "SignupPeopleNum", "AppointmentPeopleNum", "AskNum"].includes(key)) {
        return row.PublishStatus == 3 ? "cursor: pointer" : "color: #409eff; cursor: pointer";
      }
      return "";
    },
    /* 表格行的点击事件 */
    handleRowClick(row, key) {
      switch (key) {
        case "ActivityName":
          this.titleBtnClick(row.ActivityId);
          break;
        case "SignupPeopleNum":
          this.particularsBtn("报名详情", row.ActivityId);
          break;
        case "AppointmentPeopleNum":
          this.particularsBtn("纪要预约人数", row.ActivityId);
          break;
        case "AskNum":
          this.inquireBtn(row.ActivityId);
          break;
        default:
          "";
      }
    },
    /* 表格行的数据处理 */
    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];
      }
    },
    // 发送模版消息
    sendMessage() {
      if (this.selectList && this.selectList.split(",").length === 1) {
        this.messageDialogVisible = true;
      } else {
        this.$message.error("请选择一个活动");
      }
    },
  },
};
</script>
<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;
      }
      .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>
