<template>
  <!-- 活动管理页面 -->
  <div class="container-activity">
    <!-- 头部el-card -->
    <el-card 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="index == tabsPitchon ? 'pitch' : ''">{{ item.PermissionName }}</span>
        </div>
        <div style="display: flex; align-items: center">
          <el-upload v-if="isResearch" style="height: 40px" ref="imgUpload" action="#" :http-request="handleUploadImg" :show-file-list="false" accept="image/*">
            <el-button style="height: 40px" type="primary">识图建会</el-button>
          </el-upload>
          <el-button style="margin-left: 20px; height: 40px" type="primary" @click="$router.push(!isResearch ? '/addActivity' : '/addPurchaserActivity')">添加活动</el-button>
        </div>
      </div>
    </el-card>
    <!-- 内容el-card -->
    <el-card>
      <!-- 选择部分 -->
      <div class="screen-box">
        <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 v-model="cactivityTypeVal" @change="conditionChange">
            <el-option v-for="item in cactivityTypeList" :label="item.ActivityTypeName" :key="item.ActivityTypeId" :value="item.ActivityTypeId"></el-option>
          </el-select>
          <el-date-picker v-model="publishDate" type="date" placeholder="发布时间" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" @change="conditionChange"> </el-date-picker>
          <date-picker style="margin-bottom: 20px" v-model="issueTime" type="date" range placeholder="活动时间" value-type="format" @change="conditionChange"> </date-picker>
          <el-select placeholder="发布状态" clearable v-model="status" @change="conditionChange" style="margin-bottom: 20px">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-input v-model="activityLabel" @input="titleInput" placeholder="请输入活动标签" clearable style="display: inline-block; width: 220px; margin-bottom: 20px">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
        <div>
          <el-input v-model="titleValue" @input="titleInput" placeholder="请输入活动名称" clearable style="display: inline-block; width: 220px">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
      </div>
      <!-- 表格部分 -->
      <el-table :data="dataList" style="width: 100%" border>
        <el-table-column align="center" label="活动名称" min-width="285">
          <template slot-scope="{ row }">
            <span :class="row.PublishStatus == 3 ? 'grey-color' : 'editsty'" @click="titleBtnClick(row.ActivityId)">{{ row.ActivityName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ChartPermissionName" align="center" label="行业" min-width="90"></el-table-column>
        <el-table-column min-width="120" prop="ActivityTypeName" align="center" label="活动类型"></el-table-column>
        <el-table-column min-width="120" prop="Label" align="center" label="活动标签"></el-table-column>
        <el-table-column min-width="219" prop="ActivityTimeText" align="center" label="活动时间"></el-table-column>
        <el-table-column min-width="200" prop="LastUpdatedTime" align="center" label="更新时间"></el-table-column>
        <el-table-column align="center" label="发布状态" min-width="100">
          <template slot-scope="{ row }">
            {{ row.PublishStatus == 0 ? "未发布" : row.PublishStatus == 1 ? "已发布" : "已取消" }}
          </template>
        </el-table-column>
        <el-table-column v-if="tabsPitchon === 2" align="center" label="路演回放" min-width="100">
          <template slot-scope="{ row }"> {{ row.IsUpload ? "已上传" : "" }} </template>
        </el-table-column>
        <el-table-column align="center" width="156" label="操作">
          <template slot-scope="{ row }">
            <div class="operate-box">
              <p v-if="row.PublishStatus == 0 && tabsPitchon == 0" class="editsty" @click="operationBtn(row.ActivityId, '发布')">发布</p>
              <p v-if="row.PublishStatus == 3" class="grey-color" @click="operationBtn(row.ActivityId, '重新发布')">重新发布</p>
              <p v-if="row.PublishStatus == 1" class="editsty" @click="operationBtn(row.ActivityId, '取消发布')">取消发布</p>
              &nbsp;&nbsp;
              <p :class="row.PublishStatus == 3 ? 'grey-color' : 'editsty'" @click="editBtn(row.ActivityId, row.PublishStatus)">编辑</p>
              &nbsp;&nbsp;
              <p class="deletesty" v-if="row.PublishStatus == 0 && tabsPitchon == 0" @click="operationBtn(row.ActivityId, '删除')">删除</p>
              <p class="editsty" v-if="row.IsShowSigninButton" @click="handleDownLoadImg(row)">下载签到码</p>
              <p v-if="row.ChartPermissionId === 31 && tabsPitchon == 0 && row.PublishStatus == 1" class="editsty" @click="overheadHandler(row.ActivityId, '置顶')">
                &nbsp;&nbsp;{{ row.TopTime == 0 ? "置顶" : "取消置顶" }}
              </p>
            </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>
    <atc-particulars :dialogVisible.sync="dialogVisible" :detailData.sync="detailData" />
    <imgMeeting :isShowImgMeetingDlg.sync="isShowImgMeetingDlg" :imgMeetingData.sync="imgMeetingData" @childrenImgMeetingHandler="childrenImgMeetingHandler" />
  </div>
</template>

<script>
import * as OpenCC from "opencc-js";
// 将繁体中文（香港）转换为简体中文（中国大陆）
const converter = OpenCC.Converter({ from: "hk", to: "cn" });
import mPage from "@/components/mPage.vue";
import { raiInterface, sealInterence } from "@/api/api.js";
import AtcParticulars from "../components/atcParticulars.vue";
import imgMeeting from "./components/imgMeeting.vue";
export default {
  name: "",
  components: { mPage, AtcParticulars, imgMeeting },
  props: {
    Type: {
      type: String,
      emnu: ["hongze", "purchaser"], // 弘则，研选
      default: "hongze",
    },
  },
  data() {
    return {
      listTitle: [
        {
          PermissionName: "未开始",
          Id: "NotStarted",
        },
        {
          PermissionName: "进行中",
          Id: "HaveInHand",
        },
        {
          PermissionName: "已结束",
          Id: "Complete",
        },
      ],
      tabsPitchon: 0, //tabs 默认选中
      page_no: sessionStorage.getItem("cativityBack") ? JSON.parse(sessionStorage.getItem("cativityBack")).page_no : 1,
      dataList: [], //表格内容
      industry: "", //行业
      status: "", //状态
      issueTime: "", //时间
      cactivityTypeVal: "", //活动
      options: [
        { id: 1, name: "已发布" },
        { id: 0, name: "未发布" },
        { id: 3, name: "已取消" },
      ],
      titleValue: "", //标题关键词
      total: 0, //条数
      PageSize: 10, //每页显示几条
      chartPermissionList: [], //行业的数组
      cactivityTypeList: [], //活动类型
      dialogVisible: false, //弹框
      activeStateId: "NotStarted",
      detailData: {}, //
      activityLabel: "",
      publishDate: "",
      baseApi: process.env.API_ROOT,
      isShowImgMeetingDlg: false,
      imgMeetingData: [],
    };
  },
  computed: {
    sta() {
      return this.status >= 0 && typeof this.status == "number" ? this.status : 2;
    },
    // 弘则 研选 是否是研选
    isResearch() {
      return this.$route.path.indexOf("purchaser") != -1 ? true : false;
    },
  },
  created() {},
  mounted() {
    if (sessionStorage.getItem("cativityBack")) {
      const initialize = JSON.parse(sessionStorage.getItem("cativityBack"));
      this.titleValue = initialize.keyword;
      this.industry = initialize.industry;
      this.status = initialize.status;
      this.issueTime = initialize.issueTime;
      this.cactivityTypeVal = initialize.cactivityTypeVal;
      this.activeStateId = initialize.activeStateId;
      this.tabsPitchon = initialize.tabsPitchon;
      this.activityLabel = initialize.activityLabel;
      this.publishDate = initialize.publishDate;
    }
    // 研选下 没有行业的搜索框
    !this.isResearch && this.chartPermission();
    this.activityType();
    this.getsummaryManageList();
  },
  methods: {
    titleInput() {
      this.page_no = 1;
      this.init();
      this.getsummaryManageList();
    },
    init() {
      this.industry = ""; //行业
      this.status = ""; //状态
      this.issueTime = ""; //时间
      this.cactivityTypeVal = ""; //活动
      this.sta = "";
    },
    //头部tabs
    tabsBoxBtn(item, index) {
      this.activeStateId = item.Id;
      this.tabsPitchon = index;
      this.page_no = 1;
      this.getsummaryManageList();
    },
    operationBtn(id, value) {
      this.$confirm(`确定${value}该活动吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (value == "删除") {
            raiInterface
              .activityDelete({
                ActivityId: id,
              })
              .then((res) => {
                if (res.Ret !== 200) return;
                this.$message.success("删除成功！");
                let page_num = Math.ceil((this.total - 1) / this.PageSize);
                if (this.page_no > page_num) {
                  this.page_no = page_num;
                }
                this.getsummaryManageList();
              });
          } else {
            raiInterface
              .activityPublishAndCancel({
                ActivityId: id,
              })
              .then((res) => {
                if (res.Ret !== 200) return;
                this.$message.success(value + "成功！");
                this.getsummaryManageList();
              });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: `已取消${value}`,
          });
        });
    },
    //编辑
    editBtn(id, show) {
      this.$router.push({
        path: !this.isResearch ? "/editActivity" : "/editPurchaserActivity",
        query: {
          id: id,
          isShow: show,
        },
      });
    },
    //分页
    handleCurrentChange(page) {
      this.page_no = page;
      this.getsummaryManageList();
    },
    //获取行业
    chartPermission() {
      raiInterface.chartPermission({ IsHideResearch: !this.isResearch }).then((res) => {
        if (res.Ret === 200) {
          this.chartPermissionList = res.Data.List;
        }
      });
    },
    //活动类型
    activityType() {
      raiInterface.getActivityType({ IsResearch: this.isResearch }).then((res) => {
        if (res.Ret === 200) {
          this.cactivityTypeList = res.Data.List;
        }
      });
    },
    //列表
    getsummaryManageList() {
      raiInterface
        .getActivityList({
          CurrentIndex: this.page_no,
          PageSize: this.PageSize,
          PublishStatus: this.sta - 0,
          ChartPermissionId: this.industry,
          StartDate: this.issueTime[0],
          EndDate: this.issueTime[1],
          KeyWord: this.titleValue,
          ActivityTypeId: this.cactivityTypeVal,
          ActiveState: this.activeStateId,
          ActivityLabel: this.activityLabel,
          PublishStartDate: this.publishDate,
          IsResearch: this.isResearch,
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          this.dataList = res.Data.List;
          this.total = res.Data.Paging.Totals;
        });
    },
    //change事件
    conditionChange() {
      this.page_no = 1;
      this.getsummaryManageList();
    },
    //点击标题的弹框
    titleBtnClick(id) {
      raiInterface.activityDetail({ ActivityId: Number(id) }).then((res) => {
        if (res.Ret == 200) {
          this.detailData = res.Data;
        }
      });
      this.dialogVisible = true;
    },
    // 下载图片
    handleDownLoadImg(row) {
      let img = new Image();
      img.setAttribute("crossOrigin", "anonymous");
      img.src = row.SigninImg;
      img.onload = () => {
        let canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        let context = canvas.getContext("2d");
        context.drawImage(img, 0, 0, img.width, img.height);
        let dataURL = canvas.toDataURL("image/png", 1);
        const a = document.createElement("a");
        a.setAttribute("download", "签到码.png");
        a.style.display = "none";
        a.href = dataURL;
        document.body.appendChild(a);
        a.click();
      };
    },
    async handleUploadImg(params) {
      if (!params.file) return;
      const fd = new FormData();
      fd.append("file", params.file);
      try {
        const res = await sealInterence.resourceUpload(fd);
        if (res.Ret === 200) {
          const resImg = await raiInterface.activityImgToText({
            ImgUrl: res.Data.ResourceUrl,
          });
          if (resImg.Ret === 200) {
            this.isShowImgMeetingDlg = true;
            this.imgMeetingData = resImg.Data.List.map((item) => {
              return {
                ...item,
                Company: converter(item.Company),
              };
            });
          }
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 点击取消的回调事件
    childrenImgMeetingHandler() {
      this.$refs.imgUpload.clearFiles();
    },
    // 是否置顶
    async overheadHandler(id) {
      const res = await raiInterface.yanxuan_tope_change({
        ActivityId: id,
      });
      if (res.Ret !== 200) return;
      this.$message.success("操作成功！");
      this.getsummaryManageList();
    },
  },
  /* 页面跳转前记录参数 */
  beforeRouteLeave(to, form, next) {
    let backData = {
      page_no: this.page_no,
      keyword: this.titleValue,
      industry: this.industry, //行业
      status: this.status, //状态
      issueTime: this.issueTime, //时间
      cactivityTypeVal: this.cactivityTypeVal, //活动
      activeStateId: this.activeStateId, //
      tabsPitchon: this.tabsPitchon,
      activityLabel: this.activityLabel,
      publishDate: this.publishDate,
    };
    sessionStorage.setItem("cativityBack", JSON.stringify(backData));
    next();
  },
  /* 页面进入前是否清除参数 */
  beforeRouteEnter(to, from, next) {
    if (from.path != "/editActivity") {
      sessionStorage.removeItem("cativityBack");
    }
    next();
  },
};
</script>
<style lang="scss">
.container-activity {
  .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;
        color: #409eff;
        cursor: pointer;
      }
      .pitch {
        background-color: #409eff;
        border: none;
        color: #fff;
      }
    }
  }
  .screen-box {
    display: flex;
    justify-content: space-between;
    .el-select {
      margin-right: 25px;
    }
    .el-date-picker,
    .el-date-editor {
      margin-right: 25px;
    }
  }
  .mx-datepicker {
    width: 220px !important;
    margin-right: 25px;
  }

  .customWidth {
    width: 550px !important;
  }
  .operate-box {
    display: flex;
    flex-wrap: wrap;
    p {
      flex-shrink: 0;
    }
  }
  .el-upload {
    height: 40px !important;
    min-height: 40px !important;
  }
  .grey-color {
    cursor: pointer;
  }
}
</style>
