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

export default defineComponent({
  beforeRouteEnter(to, from, next) {
    if (from.path !== "/editActivity") {
      sessionStorage.removeItem("backRoadShowListPage");
    }
    next();
  },
});
</script>

<script setup>
import { ref, watch, onMounted, reactive, computed, toRefs } from "vue";

import { raiInterface, raiVideoApi } from "@/api/api.js";
import { tableColums, TopTabs } from "./roadShow/tableTabs";
import { PublishSelect } from "../components/apply/applyTableColums";
import mPage from "@/components/mPage.vue";
import playDetails from "./roadShow/components/playDetailsDlg.vue";
import addVideoDlg from "./roadShow/components/addVideoDlg.vue";
import moment from "moment";
import AtcParticulars from "../components/atcParticulars.vue";
import GenerationAsk from "../components/generationAsk.vue";
import ReleaseAudio from "./roadShow/components/releaseAudio.vue";

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

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

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

const pageState = reactive({
  tableColums: [],
  dataList: [],
  tabActive: 1, //tabs 选中
  chartPermissionList: [], //行业的数组
  chartPermissionId: "", //行业的id
  issueTime: "", //活动时间
  cactivityTypeVal: "", //活动类型
  cactivityTypeList: [],
  publishStatus: "", //发布状态
  fileName: "", //文件名称
  total: 0, //条数
  PageSize: 10, //每页显示几条
  page_no: 1, //页码
  playDetailsVisible: false, //播放详情的弹框
  playDetailsList: {}, //播放详情的数据//编辑的详情
  editDetails: {}, //播放详情的数据//编辑的详情
  addEditdialogVisib: false, //添加视频的弹框
  sortType: "",
  detailData: [],
  dialogVisible: false,
  generaitondialogVisib: false, //代问的弹框
  generaitonId: "",
  generaitonType: "微路演",
  addEditdialogReleaseAudio: false,
});

const topTabs = computed(() => {
  return TopTabs;
});

//发布状态
const publishSelect = computed(() => {
  return PublishSelect;
});

onMounted(() => {
  if (sessionStorage.getItem("backRoadShowListPage")) {
    let { page_no, fileName, chartPermissionId, cactivityTypeVal, issueTime, tabActive } = JSON.parse(sessionStorage.getItem("backRoadShowListPage"));
    pageState.page_no = page_no;
    pageState.fileName = fileName;
    pageState.chartPermissionId = chartPermissionId;
    pageState.cactivityTypeVal = cactivityTypeVal;
    pageState.issueTime = issueTime;
    pageState.tabActive = tabActive;
  }

  pageState.tableColums = tableColums(pageState.tabActive);
  chartPermission();
  activityType();
  getVideoList();
});

function topTabsHandler(item) {
  pageState.tabActive = item.value;
  pageState.tableColums = tableColums(pageState.tabActive);
  pageState.publishStatus = "";
  pageState.cactivityTypeVal = "";
  pageState.page_no = 1;
  getVideoList();
}
//获取行业
async function chartPermission() {
  const res = await raiInterface.chartPermission({
    IsHideResearch: true,
  });
  if (res.Ret === 200) {
    pageState.chartPermissionList = res.Data.List;
  }
}
//活动类型
async function activityType() {
  const res = await raiInterface.getActivityType();
  if (res.Ret === 200) {
    pageState.cactivityTypeList = res.Data.List;
  }
}
async function getVideoList() {
  let params = {
    PageSize: pageState.PageSize,
    CurrentIndex: pageState.page_no,
    KeyWord: pageState.fileName,
    StartDate: pageState.issueTime ? pageState.issueTime[0] : "",
    EndDate: pageState.issueTime ? pageState.issueTime[1] : "",
    PublishStatus: pageState.publishStatus ? Number(pageState.publishStatus) : "",
    ChartPermissionId: pageState.chartPermissionId,
    ActivityTypeId: pageState.cactivityTypeVal,
    SortType: pageState.sortType,
    SortParam: "videoCounts",
    SearchType: pageState.tabActive,
  };
  const res =
    pageState.tabActive == 4
      ? await raiVideoApi.videoList(params)
      : pageState.tabActive == 1
      ? await raiVideoApi.activityVoiceAndVideoList(params)
      : pageState.tabActive == 3
      ? await raiVideoApi.askserie_videoList(params)
      : await raiVideoApi.activityVoiceAndVideoList(params);
  if (res.Ret === 200) {
    pageState.dataList = res.Data.List;
    pageState.total = res.Data.Paging.Totals;
  }
}
//select 筛选条件后的事件
function selectChangeHandle() {
  pageState.page_no = 1;
  getVideoList();
}
//文件名称的搜索
function fileNameHandle() {
  pageState.issueTime = "";
  pageState.publishStatus = "";
  pageState.chartPermissionId = "";
  pageState.page_no = 1;
  getVideoList();
}
/* 点击表格的排序 */
function sortChangeHandle({ prop, order }) {
  pageState.sortType = order == "ascending" ? "asc" : order == "descending" ? "desc" : "";
  getVideoList();
}
//分页
function handleCurrentChange(page) {
  pageState.page_no = page;
  getVideoList();
}
/*
    表格三件套
    */
function handleRowContent(row, key) {
  if (key == "PublishStatus") {
    let status = row["PublishStatus"] == 1 ? "已发布" : row["PublishStatus"] == 3 ? "已取消" : "未发布";
    return status;
  } else if (key == "VideoDuration" || key == "VoicePlaySeconds") {
    let m = parseInt(row[key] / 60);
    let s = parseInt(row[key] % 60);
    let ms = `${m > 9 ? m : "0" + m}分${s > 9 ? s : "0" + s}秒`;
    return ms;
  } else {
    return row[key];
  }
}
function handleRowStyle(key) {
  const style = {
    VideoCounts: "color: #409eff; cursor: pointer",
    VoiceCounts: "color: #409eff; cursor: pointer",
    CommentNum: "color: #409eff; cursor: pointer",
  };
  return style[key] ? style[key] : "";
}
//
function handleRowClick(row, key) {
  if (key == "VideoCounts" || key == "VoiceCounts") {
    pageState.playDetailsVisible = true;
    pageState.playDetailsList = row;
  } else if (key == "CommentNum") {
    pageState.generaitondialogVisib = true;
    pageState.generaitonId = pageState.tabActive == 1 || pageState.tabActive == 2 ? row.ActivityId : pageState.tabActive == 3 ? row.AskserieVideoId : row.VideoId;
  }
}
/*
    表格三件套
    */
//点击标题的弹框
function titleBtnClick(id) {
  raiInterface.activityDetail({ ActivityId: Number(id) }).then((res) => {
    if (res.Ret == 200) {
      pageState.detailData = res.Data;
    }
  });
  pageState.dialogVisible = true;
}
//发布或者取消发布
function handlePublish(item) {
  let str = pageState.tabActive == 3 ? "音频" : "视频";
  ElMessageBox.confirm(item.PublishStatus == 1 ? `确认取消发布该${str}吗？` : `确认发布该${str}吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res =
        pageState.tabActive == 3
          ? await raiVideoApi.askseriePublishAndcancel({
              AskserieVideoId: item.AskserieVideoId,
              PublishOrCancle: item.PublishStatus == 1 ? 0 : 1,
            })
          : await raiVideoApi.videoPublish({
              VideoId: item.VideoId,
              PublishOrCancle: item.PublishStatus == 1 ? 0 : 1,
            });
      if (res.Ret === 200) {
        ElMessage.success("操作成功！");
        getVideoList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
}
//编辑
function handleEditVideo(item, type) {
  if (type == "活动") {
    $router.push({
      path: "/editActivity",
      query: {
        id: item.ActivityId,
        isShow: 1,
      },
    });
  } else {
    pageState.editDetails = item;
    if (pageState.tabActive == 3) {
      pageState.addEditdialogReleaseAudio = true;
    } else {
      pageState.addEditdialogVisib = true;
    }
  }
}

onBeforeRouteLeave((to, from, next) => {
  let backData = {
    page_no: pageState.page_no,
    fileName: pageState.fileName,
    chartPermissionId: pageState.chartPermissionId,
    cactivityTypeVal: pageState.cactivityTypeVal,
    issueTime: pageState.issueTime,
    tabActive: pageState.tabActive,
  };
  sessionStorage.setItem("backRoadShowListPage", JSON.stringify(backData));
  next();
});

const {
  tableColums,
  dataList,
  tabActive, //tabs 选中
  chartPermissionList, //行业的数组
  chartPermissionId, //行业的id
  issueTime, //活动时间
  cactivityTypeVal, //活动类型
  cactivityTypeList,
  publishStatus, //发布状态
  fileName, //文件名称
  total, //条数
  PageSize, //每页显示几条
  page_no, //页码
  playDetailsVisible, //播放详情的弹框
  playDetailsList, //播放详情的数据//编辑的详情
  editDetails, //播放详情的数据//编辑的详情
  addEditdialogVisib, //添加视频的弹框
  sortType,
  detailData,
  dialogVisible,
  generaitondialogVisib, //代问的弹框
  generaitonId,
  generaitonType,
  addEditdialogReleaseAudio,
} = toRefs(pageState);
</script>

<template>
  <div class="container container-road-show">
    <div class="top-wrap">
      <div style="display: flex">
        <span @click="topTabsHandler(item)" :class="['item', tabActive === item.value && 'active']" v-for="item in topTabs" :key="item.value">
          {{ item.name }}
        </span>
      </div>
      <el-input v-model="fileName" @input="fileNameHandle" placeholder="请输入文件名称" clearable style="display: inline-block; width: 350px" :prefix-icon="Search"> </el-input>
    </div>

    <!-- // 筛选 表格 -->
    <el-card style="margin-top: 20px">
      <div class="select-content">
        <div>
          <el-select style="margin-bottom: 20px" placeholder="行业" v-model="chartPermissionId" clearable @change="selectChangeHandle">
            <el-option v-for="item in chartPermissionList" :label="item.PermissionName" :key="item.ChartPermissionId" :value="item.ChartPermissionId"> </el-option>
          </el-select>
          <el-select v-if="tabActive == 1 || tabActive == 2" placeholder="活动类型" clearable v-model="cactivityTypeVal" @change="selectChangeHandle">
            <el-option v-for="item in cactivityTypeList" :label="item.ActivityTypeName" :key="item.ActivityTypeId" :value="item.ActivityTypeId"> </el-option>
          </el-select>
          <date-picker
            style="margin-bottom: 20px"
            v-model="issueTime"
            type="date"
            range
            :placeholder="tabActive == 4 || tabActive == 3 ? '发布时间' : '活动时间'"
            value-type="format"
            @change="selectChangeHandle"
          >
          </date-picker>
          <el-select v-if="tabActive == 4 || tabActive == 3" placeholder="发布状态" clearable v-model="publishStatus" @change="selectChangeHandle" 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-button type="primary" v-if="tabActive === 4" @click="addEditdialogVisib = true"> 添加视频 </el-button>
          <el-button type="primary" v-if="tabActive === 3" @click="addEditdialogReleaseAudio = true"> 发布问答 </el-button>
        </div>
      </div>
      <el-table :data="dataList" style="width: 100%" border @sort-change="sortChangeHandle">
        <el-table-column
          v-for="item in tableColums"
          :key="item.label"
          :label="item.label"
          :width="item.widthsty"
          :min-width="item.minwidthsty"
          align="center"
          :sortable="item.key === 'VideoCounts' || item.key === 'VoiceCounts' ? 'custom' : false"
        >
          <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 align="center" prop="LastUpdatedTime" width="170" label="操作">
          <template #default="{ row }">
            <div v-if="tabActive === 4 || tabActive === 3">
              <span class="editsty" @click="handlePublish(row)">
                {{ row.PublishStatus == 1 ? "取消发布" : "发布" }}
              </span>
              &nbsp;&nbsp;
              <span class="editsty" @click="handleEditVideo(row, '产业')"> 编辑 </span>
            </div>
            <template v-else>
              <span class="editsty" @click="titleBtnClick(row.ActivityId)"> 活动详情 </span>
              <span class="editsty" @click="handleEditVideo(row, '活动')"> &nbsp;&nbsp;&nbsp;&nbsp;编辑活动 </span>
            </template>
          </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>
    <playDetails v-model:playDetailsVisible="playDetailsVisible" v-model:playDetailsList="playDetailsList" :tabActive="tabActive" />
    <addVideoDlg @getVideoList="getVideoList" v-model:addEditdialogVisib="addEditdialogVisib" :chartPermissionList="chartPermissionList" v-model:playDetailsList="editDetails" />
    <atc-particulars v-model:dialogVisible="dialogVisible" v-model:detailData="detailData" />
    <generation-ask v-model:generaitondialogVisib="generaitondialogVisib" :generaitonId="generaitonId" :generaitonType="generaitonType" :tabActiveRoadshow="tabActive" />
    <release-audio @getVideoList="getVideoList" v-model:addEditdialogReleaseAudio="addEditdialogReleaseAudio" :chartPermissionList="chartPermissionList" v-model:playDetailsList="editDetails" />
  </div>
</template>

<style scoped lang="scss">
.container-road-show {
  .top-wrap {
    margin-bottom: 28px;
    padding: 20px;
    background: #fff;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
    .item {
      display: flex;
      width: 100px;
      height: 40px;
      background: #ecf5ff;
      border-radius: 4px;
      border: 1px solid #b3d8ff;
      color: #3385ff;
      font-size: 16px;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
      cursor: pointer;
    }
    .active {
      border: none;
      background-color: #409eff;
      color: #fff;
    }
  }
  .select-content {
    display: flex;
    justify-content: space-between;
    .el-select {
      width: 220px;
      margin-right: 20px;
    }
    .mx-datepicker {
      width: 220px !important;
      margin-right: 20px !important;
    }
  }
}
</style>
