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

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

<script setup>
import { ref, watch, onMounted, reactive, computed, toRefs } from "vue";
import { raiInterface, sealInterence } 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 * as OpenCC from "opencc-js";
// 将繁体中文（香港）转换为简体中文（中国大陆）
const converter = OpenCC.Converter({ from: "hk", to: "cn" });

import AtcParticulars from "../components/atcParticulars.vue";
import imgMeeting from "./components/imgMeeting.vue";

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

const pageState = reactive({
  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: import.meta.env.VITE_APP_API_ROOT,
  isShowImgMeetingDlg: false,
  imgMeetingData: [],
});

const sta = computed(() => {
  return pageState.status >= 0 && typeof pageState.status == "number" ? pageState.status : 2;
});

const isResearch = computed(() => {
  return $route.path.indexOf("purchaser") != -1 ? true : false;
});

function titleInput() {
  pageState.page_no = 1;
  init();
  getsummaryManageList();
}
function init() {
  pageState.industry = ""; //行业
  pageState.status = ""; //状态
  pageState.issueTime = ""; //时间
  pageState.cactivityTypeVal = ""; //活动
  pageState.sta = "";
}
//头部tabs
function tabsBoxBtn(item, index) {
  pageState.activeStateId = item.Id;
  pageState.tabsPitchon = index;
  pageState.page_no = 1;
  getsummaryManageList();
}
function operationBtn(id, value) {
  ElMessageBox.confirm(`确定${value}该活动吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      if (value == "删除") {
        raiInterface
          .activityDelete({
            ActivityId: id,
          })
          .then((res) => {
            if (res.Ret !== 200) return;
            ElMessage.success("删除成功！");
            let page_num = Math.ceil((pageState.total - 1) / pageState.PageSize);
            if (pageState.page_no > page_num) {
              pageState.page_no = page_num;
            }
            getsummaryManageList();
          });
      } else {
        raiInterface
          .activityPublishAndCancel({
            ActivityId: id,
          })
          .then((res) => {
            if (res.Ret !== 200) return;
            ElMessage.success(value + "成功！");
            getsummaryManageList();
          });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: `已取消${value}`,
      });
    });
}
//编辑
function editBtn(id, show) {
  $router.push({
    path: !pageState.isResearch ? "/editActivity" : "/editPurchaserActivity",
    query: {
      id: id,
      isShow: show,
    },
  });
}
//分页
function handleCurrentChange(page) {
  pageState.page_no = page;
  getsummaryManageList();
}
//获取行业
function chartPermission() {
  raiInterface.chartPermission({ IsHideResearch: !pageState.isResearch }).then((res) => {
    if (res.Ret === 200) {
      pageState.chartPermissionList = res.Data.List;
    }
  });
}
//活动类型
function activityType() {
  raiInterface.getActivityType({ IsResearch: pageState.isResearch }).then((res) => {
    if (res.Ret === 200) {
      pageState.cactivityTypeList = res.Data.List;
    }
  });
}
//列表
function getsummaryManageList() {
  raiInterface
    .getActivityList({
      CurrentIndex: pageState.page_no,
      PageSize: pageState.PageSize,
      PublishStatus: pageState.sta - 0,
      ChartPermissionId: pageState.industry,
      StartDate: pageState.issueTime[0],
      EndDate: pageState.issueTime[1],
      KeyWord: pageState.titleValue,
      ActivityTypeId: pageState.cactivityTypeVal,
      ActiveState: pageState.activeStateId,
      ActivityLabel: pageState.activityLabel,
      PublishStartDate: pageState.publishDate,
      IsResearch: pageState.isResearch,
    })
    .then((res) => {
      if (res.Ret !== 200) return;
      pageState.dataList = res.Data.List;
      pageState.total = res.Data.Paging.Totals;
    });
}
//change事件
function conditionChange() {
  pageState.page_no = 1;
  getsummaryManageList();
}
//点击标题的弹框
function titleBtnClick(id) {
  raiInterface.activityDetail({ ActivityId: Number(id) }).then((res) => {
    if (res.Ret == 200) {
      pageState.detailData = res.Data;
    }
  });
  pageState.dialogVisible = true;
}
// 下载图片
function 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 function 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) {
        pageState.isShowImgMeetingDlg = true;
        pageState.imgMeetingData = resImg.Data.List.map((item) => {
          return {
            ...item,
            Company: converter(item.Company),
          };
        });
      }
    }
  } catch (err) {}
}
const imgUpload = ref(null);
// 点击取消的回调事件
function childrenImgMeetingHandler() {
  imgUpload.value.clearFiles();
}
// 是否置顶
async function overheadHandler(id) {
  const res = await raiInterface.yanxuan_tope_change({
    ActivityId: id,
  });
  if (res.Ret !== 200) return;
  ElMessage.success("操作成功！");
  getsummaryManageList();
}
function deleteLabelItem() {
  pageState.imgMeetingData.splice(index, 1);
}

onMounted(() => {
  if (sessionStorage.getItem("cativityBack")) {
    const initialize = JSON.parse(sessionStorage.getItem("cativityBack"));
    pageState.titleValue = initialize.keyword;
    pageState.industry = initialize.industry;
    pageState.status = initialize.status;
    pageState.issueTime = initialize.issueTime;
    pageState.cactivityTypeVal = initialize.cactivityTypeVal;
    pageState.activeStateId = initialize.activeStateId;
    pageState.tabsPitchon = initialize.tabsPitchon;
    pageState.activityLabel = initialize.activityLabel;
    pageState.publishDate = initialize.publishDate;
  }
  // 研选下 没有行业的搜索框
  !pageState.isResearch && chartPermission();
  activityType();
  getsummaryManageList();
});

onBeforeRouteLeave((to, form, next) => {
  let backData = {
    page_no: pageState.page_no,
    keyword: pageState.titleValue,
    industry: pageState.industry, //行业
    status: pageState.status, //状态
    issueTime: pageState.issueTime, //时间
    cactivityTypeVal: pageState.cactivityTypeVal, //活动
    activeStateId: pageState.activeStateId, //
    tabsPitchon: pageState.tabsPitchon,
    activityLabel: pageState.activityLabel,
    publishDate: pageState.publishDate,
  };
  sessionStorage.setItem("cativityBack", JSON.stringify(backData));
  next();
});

const {
  listTitle,
  tabsPitchon,
  page_no,
  dataList,
  industry,
  status,
  issueTime,
  cactivityTypeVal,
  options,
  titleValue,
  total,
  PageSize,
  chartPermissionList,
  cactivityTypeList,
  dialogVisible,
  activeStateId,
  detailData,
  activityLabel,
  publishDate,
  baseApi,
  isShowImgMeetingDlg,
  imgMeetingData,
} = toRefs(pageState);
</script>

<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 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" 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 v-model="issueTime" type="date" range placeholder="活动时间" value-type="format" @change="conditionChange"> </date-picker>
          <el-select placeholder="发布状态" clearable v-model="status" @change="conditionChange">
            <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" :prefix-icon="Search"> </el-input>
        </div>
        <div>
          <el-input v-model="titleValue" @input="titleInput" placeholder="请输入活动名称" clearable style="display: inline-block; width: 220px" :prefix-icon="Search"> </el-input>
        </div>
      </div>
      <!-- 表格部分 -->
      <el-table :data="dataList" style="width: 100%; margin-top: 20px" border>
        <el-table-column align="center" label="活动名称" min-width="285">
          <template #default="{ 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 #default="{ 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 #default="{ row }"> {{ row.IsUpload ? "已上传" : "" }} </template>
        </el-table-column>
        <el-table-column align="center" width="156" label="操作">
          <template #default="{ 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 v-model:dialogVisible="dialogVisible" v-model:detailData="detailData" />
    <imgMeeting
      v-model:page_no="page_no"
      v-model:isShowImgMeetingDlg="isShowImgMeetingDlg"
      v-model:imgMeetingData="imgMeetingData"
      @childrenImgMeetingHandler="childrenImgMeetingHandler"
      @deleteLabelItem="deleteLabelItem"
      @getsummaryManageList="getsummaryManageList"
    />
  </div>
</template>

<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>
