<template>
  <div id="reportlist">
    <el-card class="box-card">
      <div slot="header" class="header">
        <el-form :inline="true" :model="searchform" @submit.native.prevent>
          <el-form-item label="">
            <el-button
              v-permission="permissionBtn.reportManageBtn.reportManage_reportAdd"
              type="primary"
              size="medium"
              @click="$router.push({ path: '/addreportNew' })"
              >添加研报</el-button
            >
            <!-- <el-button type="primary" plain size="medium" @click="$router.push({path:'/addreport'})">添加研报(旧版)</el-button> -->
            <el-button
              v-permission="permissionBtn.reportManageBtn.reportManage_dayWeekReportAdd"
              type="primary"
              size="medium"
              @click="$router.push({ path: '/dayorweek' })"
              >添加晨报/周报</el-button
            >
            <!-- <el-button type="primary" size="medium" @click="publishreport">发 布</el-button> -->
            <template v-if="Role === 'rai_researcher'">
              <el-button
                type="primary"
                size="medium"
                @click="downLoadReport"
                v-if="!batches.length"
                >下载阅读数据</el-button
              >
              <a style="margin-left: 10px" :href="exportUrlDl" v-else download>
                <el-button type="primary" size="medium">下载阅读数据</el-button>
              </a>
            </template>
          </el-form-item>
          <el-form-item label="">
            <el-date-picker
              @change="search"
              v-model="searchform.dateValue"
              type="daterange"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="起始日期"
              end-placeholder="结束日期"
              size="medium"
              style="width: 280px"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="">
            <el-select
              @change="search"
              v-model="searchform.frequency"
              placeholder="更新频度筛选"
              size="medium"
              clearable
              style="width: 140px"
            >
              <el-option label="年度" value="年度"></el-option>
              <el-option label="半年度" value="半年度"></el-option>
              <el-option label="季度" value="季度"></el-option>
              <el-option label="月度" value="月度"></el-option>
              <el-option label="双周度" value="双周度"></el-option>
              <el-option label="周度" value="周度"></el-option>
              <el-option label="日度" value="日度"></el-option>
              <el-option label="不定时" value="不定时"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-cascader
              @change="search"
              :options="optionsArr"
              v-model="searchform.classifynameArr"
              clearable
              placeholder="类型筛选"
              size="medium"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="">
            <el-select
              v-permission="[
                  permissionBtn.reportManageBtn.reportManage_reportList,
                  permissionBtn.reportManageBtn.reportManage_reportList_sendTime,
                  'or']"
              @change="search"
              v-model.number="searchform.msgIsSend"
              placeholder="状态筛选"
              size="medium"
              clearable
              style="width: 140px"
            >
              <el-option label="未推送消息" :value="1"></el-option>
              <el-option label="已推送消息" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              @input="search"
              placeholder="标题 / 作者"
              v-model="searchform.key_word"
              clearable
              size="medium"
            >
              <i class="el-icon-search" slot="prefix" @click="search"></i>
            </el-input>
          </el-form-item>
          <!-- <el-form-item><el-button type="primary" size="medium" @click.native="search">搜索</el-button></el-form-item> -->
        </el-form>
      </div>
      <template>
        <!-- <el-table :data="tableData" v-loading="listLoading" @sort-change='sortChange' @selection-change="selectchange" :default-sort="{prop:'publish_time',order:'descending'}" element-loading-text="数据加载中..." border style="width:100%;"> -->
        <el-table
          ref="table"
          :data="tableData"
          v-loading="listLoading"
          @sort-change="sortChange"
          element-loading-text="数据加载中..."
          border
          style="width: 100%"
        >
          <el-table-column
            prop="Title"
            label="报告标题"
            align="center"
            min-width="140"
          >
            <template slot-scope="scope">
              <div @click="lookreportdtl(scope.row)">
                <span
                  style="cursor: pointer; color: #4099ef"
                >{{ scope.row.Title }}</span
                >
                <span
                  style="cursor: pointer; color: #4099ef"
                  v-if="scope.row.MsgSendTime"
                  >({{ scope.row.MsgSendTime.substring(5, 7)
                  }}{{ scope.row.MsgSendTime.substring(8, 10) }})</span
                >
                <span
                  style="cursor: pointer; color: #4099ef"
                  v-else-if="scope.row.PublishTime"
                  >({{ scope.row.PublishTime.substring(5, 7)
                  }}{{ scope.row.PublishTime.substring(8, 10) }})</span
                >
                <span
                  style="cursor: pointer; color: #4099ef"
                  v-else-if="scope.row.CreateTime"
                  >({{ scope.row.CreateTime.substring(5, 7)
                  }}{{ scope.row.CreateTime.substring(8, 10) }})</span
                >

              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="Abstract"
            label="摘要"
            align="center"
            min-width="140"
          ></el-table-column>
          <el-table-column label="报告类型" align="center" min-width="140">
            <template slot-scope="scope"
              >{{ scope.row.ClassifyNameFirst }}
              <span v-if="scope.row.ClassifyNameSecond"
                >/ {{ scope.row.ClassifyNameSecond }}</span
              ></template
            >
          </el-table-column>
          <el-table-column
            prop="AdminRealName"
            label="创建人"
            align="center"
            min-width="100"
          ></el-table-column>
          <el-table-column label="发布状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.State == '2'" style="color: #46c371"
                >已发布</span
              >
              <span v-if="scope.row.State == '1'">未发布</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="PublishTime"
            label="发布时间"
            min-width="124"
            align="center"
            :formatter="formatterColumn"
          ></el-table-column>
          <el-table-column
            prop="MsgSendTime"
            label="报告推送时间"
            min-width="124"
            align="center"
          >
            <template slot-scope="scope">{{
              scope.row.MsgSendTime | formatTime
            }}</template>
          </el-table-column>
          <el-table-column
            prop="ModifyTime"
            label="更新时间"
            min-width="124"
            align="center"
            :formatter="formatterColumn"
          ></el-table-column>
          <el-table-column label="期数" align="center">
            <template slot-scope="scope">第{{ scope.row.Stage }}期</template>
          </el-table-column>
          <el-table-column label="频度" align="center">
            <template slot-scope="scope">{{ scope.row.Frequency }}</template>
          </el-table-column>
          <!-- <el-table-column label="音频" align="center">
						<template slot-scope="scope">
							<span v-if="!scope.row.VideoUrl" style="color:#46C371; cursor:pointer;" @click="openupload(scope.row.Id)">上传</span>
							<a :href="hostapi+'?ReportId='+parseInt(scope.row.Id)" v-if="scope.row.VideoUrl" :download="scope.row.VideoName" style="cursor:pointer; color:#4099ef;">下载</a>
						</template>
					</el-table-column> -->
          <el-table-column
            label="PV / UV"
            align="center"
            :render-header="renderHeader"
            width="140"
          >
            <template slot-scope="scope"
              >{{ scope.row.Pv }}/{{ scope.row.Uv }}</template
            >
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="130">
            <template slot-scope="scope">
              <div class="opt-btns">
                <template
                  v-if="scope.row.State == 1"
                >
                  <!-- <i class="el-icon-edit-outline" @click="$router.push({name:'编辑研报',query:{id:scope.row.id}})"></i> -->
                  <span
                    v-permission="permissionBtn.reportManageBtn.reportManage_publish"
                    class="editsty"
                    @click="publishreport(scope.row)"
                    v-if="scope.row.CanEdit"
                    >发布</span
                  >
                  <span
                    v-permission="permissionBtn.reportManageBtn.reportManage_reportEdit"
                    class="editsty"
                    @click="editreport(scope.row, 'edit')"
                    v-if="scope.row.CanEdit"
                    >编辑</span
                  >
                  <span
                    v-permission="permissionBtn.reportManageBtn.reportManage_reportEdit"
                    class="editsty"
                    @click="editreport(scope.row, 'editing')"
                    v-else
                    >{{ scope.row.Editor || "" }}编辑中...</span
                  >
                  <!-- <i class="el-icon-delete" @click="deleteitem(scope.row)"></i> -->
                  <span
                    v-permission="permissionBtn.reportManageBtn.reportManage_reportDel"
                    class="deletesty"
                    @click="deleteitem(scope.row)"
                    v-if="scope.row.CanEdit"
                    >删除</span
                  >
                </template>
                <template v-if="scope.row.State == 2">
                  <span
                    v-permission="permissionBtn.reportManageBtn.reportManage_cancelPublish"
                    @click="canclepublish(scope.row)"
                    style="color: red; cursor: pointer"
                    >取消发布</span
                  >
                  <!-- <template v-if="scope.row.ClassifyNameFirst!='周报'"> -->
                  <span
                    v-permission="permissionBtn.reportManageBtn.reportManage_sendMsg"
                    v-if="scope.row.MsgIsSend == 0"
                    style="color: #4099ef; cursor: pointer"
                    @click="messageSend(scope.row)"
                    >推送消息</span
                  >
                  <span v-permission="permissionBtn.reportManageBtn.reportManage_sendMsg"
                    v-else style="color: red">已推送消息</span>
                  <!-- </template> -->
                  <!-- <template v-else>
										<span v-if="scope.row.MsgIsSend=='0'" @click="gosendTemplateMsg(scope.row)" style="color:#4099ef; cursor:pointer;">推送模版消息</span>
										<span v-else style="color:red;">已推送模版消息</span>
									</template> -->

                  <!-- <span v-if="scope.row.MsgIsSend=='0'" @click="gosendTemplateMsg(scope.row)" style="color:#4099ef; cursor:pointer;">推送模版消息</span>
									<span v-else style="color:red;">已推送模版消息</span>
									<template v-if="scope.row.NeedThsMsg!=0">
									<span v-if="scope.row.ThsMsgIsSend == 0" @click="messagePush(scope.row)" style="color:#4099ef; cursor:pointer;">推送客群消息</span>
									<span v-else style="color:red;">已推送客群消息</span>
									</template> -->
                </template>
                <span
                  v-permission="permissionBtn.reportManageBtn.reportManage_audioUpload"
                  style="color: #46c371; cursor: pointer"
                  v-if="!['晨报', '周报'].includes(scope.row.ClassifyNameFirst)"
                  @click="openupload(scope.row.Id)"
                  >音频上传</span
                >
                <a
                  v-permission="permissionBtn.reportManageBtn.reportManage_audioDownload"
                  :href="hostapi + '?ReportId=' + parseInt(scope.row.Id)"
                  v-if="
                    scope.row.VideoUrl &&
                    !['晨报', '周报'].includes(scope.row.ClassifyNameFirst)
                  "
                  :download="scope.row.VideoName"
                  style="cursor: pointer; color: #4099ef"
                  >音频下载</a
                >
                <span
                  v-permission="permissionBtn.reportManageBtn.reportManage_audioDownload"
                  style="cursor: pointer; color: #4099ef"
                  v-if="
                    ['晨报', '周报'].includes(scope.row.ClassifyNameFirst) &&
                    scope.row.ChapterVideoList.length > 0
                  "
                  @click="handleShowDownloadAudio(scope.row)"
                  >音频下载</span
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-col :span="24" class="toolbar">
        <el-pagination
          v-if="ispage"
          layout="total,prev,pager,next,jumper"
          background
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          :total="total"
          style="float: right"
        ></el-pagination>
      </el-col>
    </el-card>
    <!-- 添加账号弹框 -->
    <el-dialog
      title="提 示"
      :modal-append-to-body="false"
      :visible.sync="remarkDialog"
      :close-on-click-modal="false"
      :center="true"
      v-dialogDrag
      custom-class="dialogclass"
      width="400px"
    >
      <div slot="title" style="display: flex; align-items: center">
        <img
          :src="$icons.warn"
          style="color: #fff; width: 16px; height: 16px; margin-right: 5px"
        />
        <span style="font-size: 16px">提 示</span>
      </div>
      <div>
        <el-input
          type="textarea"
          v-model="remarkForm.Remark"
          rows="4"
          placeholder="请输入备注内容"
        ></el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="medium" @click.native="setremarkcontent"
          >确 定</el-button
        >
        <el-button
          type="primary"
          plain
          size="medium"
          @click.native="remarkDialog = false"
          >取 消</el-button
        >
      </div>
    </el-dialog>
    <!-- 上传音频弹框 -->
    <el-dialog
      title="上传音频"
      :visible.sync="uploadDialog"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :center="true"
      v-dialogDrag
      custom-class="dialogclass"
      width="510px"
    >
      <div slot="title" style="display: flex; align-items: center">
        <img
          :src="$icons.up"
          style="color: #fff; width: 16px; height: 16px; margin-right: 5px"
        />
        <span style="font-size: 16px">上传音频</span>
      </div>
      <el-form
        :model="uploadForm"
        ref="uploadForm"
        label-position="right"
        label-width="0px"
        @submit.native.prevent
      >
        <el-form-item label="">
          <input
            type="file"
            name="file"
            @change="fileSelected()"
            id="file"
            class="true-file"
            style="display: none"
          />
          <el-input
            type="text"
            v-model="uploadForm.audioname"
            readonly
            placeholder="上传报告录音"
            size="medium"
            style="width: 350px"
          ></el-input>
          <el-button type="primary" size="medium" @click.native="clickinput"
            >选择文件</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          type="primary"
          plain
          size="medium"
          @click.native="uploadDialog = false"
          >取 消</el-button
        >
        <el-button
          type="primary"
          size="medium"
          :loading="uploadloading"
          @click.native="uploadaudio"
          >{{ uploadloading ? "上传中" : "上 传" }}</el-button
        >
      </div>
    </el-dialog>

    <!-- 音频下载弹窗（晨报周报多个音频情况） -->
    <el-dialog
      title="音频下载"
      :visible.sync="downloadAudio.show"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :center="true"
      v-dialogDrag
      custom-class="dialogclass"
      width="510px"
    >
      <div class="download-audio-wrap">
        <h3
          style="
            text-align: center;
            font-size: 14px;
            margin-top: -10px;
            margin-bottom: 10px;
          "
        >
          {{ downloadAudio.title }}
        </h3>
        <div class="list-box">
          <el-checkbox
            :indeterminate="downloadAudio.select.length > 0 && !checkAllAudio"
            v-model="checkAllAudio"
            style="margin-bottom: 10px"
            @change="handleDownloadAudioCheckAll"
            >全选</el-checkbox
          >
          <el-checkbox-group v-model="downloadAudio.select">
            <el-checkbox
              :label="item"
              v-for="item in downloadAudio.list"
              :key="item.ReportChapterId"
              style="margin-bottom: 10px; display: block"
              >{{ item.VideoName }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
        <div style="text-align: center; margin: 30px 0">
          <el-button type="primary" plain @click="downloadAudio.show = false"
            >取消</el-button
          >
          <el-button type="primary" @click="handelConfirmDownloadAudio"
            >确定</el-button
          >
        </div>
      </div>
    </el-dialog>

    <!-- 批量发布弹窗 -->
    <el-dialog
      title="发布提示"
      :visible.sync="showPublish"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :center="true"
      v-dialogDrag
      custom-class="dialogclass"
      width="510px"
      @close="handleClosePublish"
    >
      <div>
        <div style="height: 100px; padding-top: 40px">
          <i
            class="el-icon-warning"
            style="font-size: 24px; color: #e6a23c; vertical-align: middle"
          ></i>
          是否发布报告，且推送模板消息和客户群？
        </div>
        <div style="margin-bottom: 20px; text-align: center">
          <el-button
            type="primary"
            plain
            style="width: 100px"
            @click="handleClosePublish"
            >取消发布</el-button
          >
          <el-button
            type="primary"
            style="width: 100px; margin: 0 20px"
            @click="handlePublic(1)"
            >仅发布</el-button
          >
          <el-button
            type="primary"
            style="width: 100px"
            :disabled="!canPushMsg"
            @click="handlePublic(2)"
            >发布&推送</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  reportlist,
  classifylist,
  reportpublish,
  reportpublishcancle,
  voiceupload,
  reportdelete,
  sendTemplateMsg,
  messagePushPost,
  markReport,
  reportMessageSend,
  weekReportValidAudio,
} from "api/api.js";
export default {
  computed: {
    exportUrlDl() {
      let url = this.exportUrl;
      let ids = this.batches.join(",");
      let param_token = localStorage.getItem("auth") || "";
      return `${url}?ReportIds=${ids}&${param_token}`;
    },
    Role() {
      let role = localStorage.getItem("Role") || "";
      return role;
    },
    checkAllAudio() {
      return (
        this.downloadAudio.list.length === this.downloadAudio.select.length
      );
    },
    canPushMsg() {
      //判断是否能推送
      if (this.batches.length == 0) return false;
      let tag = false;
      this.tableData.forEach((item) => {
        if (this.batches.includes(item.Id)) {
          if (item.NeedThsMsg != 0 && item.ThsMsgIsSend == 0) {
            tag = true;
          }
        }
      });
      return tag;
    },
  },
  data() {
    return {
      exportUrl:
        process.env.VUE_APP_API_ROOT + "/report/report_view_record/export", //导出数据
      hostapi: process.env.VUE_APP_API_ROOT + "/voice/download",
      dayWeekAudio: process.env.VUE_APP_API_ROOT + "/voice/report/download",
      optionsArr: [],
      PageIndex: 1,
      total: 0,
      pageSize: 15,
      ispage: true,
      listLoading: false,
      tableData: [],
      searchform: {
        dateValue: "",
        frequency: "",
        classifynameArr: "",
        state: "",
        key_word: "",
        publish_sort: "desc",
        msgIsSend: "",
      },
      batches: [],
      uploadloading: false,
      remarkDialog: false,
      remarkForm: {},
      uploadDialog: false,
      uploadForm: {
        id: "",
        formdata: null,
        audioname: "",
      },

      downloadAudio: {
        show: false,
        title: "名称",
        list: [],
        select: [],
      },

      showPublish: false,
    };
  },
  mounted() {
    let PageIndex = sessionStorage.getItem("PageIndex") || false;
    let searchform = sessionStorage.getItem("searchform") || false;
    if (PageIndex && searchform) {
      this.searchform = JSON.parse(searchform);
      this.PageIndex = PageIndex;
      sessionStorage.removeItem("PageIndex");
      sessionStorage.removeItem("searchform");
    }
    this.getclassifylist();
    this.getlist();
    // document.onkeydown=e=>{
    // 	// console.log(this.$route)
    // 	let keyval=window.event.keyCode;
    //     if( keyval===13 && this.$route.path === '/reportlist'){
    // 		this.getlist();
    //     }
    // }
  },
  methods: {
    //点击显示下载音频弹窗
    handleShowDownloadAudio(item) {
      this.downloadAudio.show = true;
      this.downloadAudio.title = item.Title;
      this.downloadAudio.list = item.ChapterVideoList;
      this.downloadAudio.select = [];
    },

    handleDownloadAudioCheckAll(val) {
      this.downloadAudio.select = val ? this.downloadAudio.list : [];
    },

    handelConfirmDownloadAudio() {
      //批量下载音频
      let ids = [];
      this.downloadAudio.select.forEach((item) => {
        ids.push(item.ReportChapterId);
      });

      const a = document.createElement("a");
      a.style.display = "none";
      a.setAttribute("download", "测试");
      a.href = `${this.dayWeekAudio}?ChapterIds=${ids.join(",")}`;
      document.body.appendChild(a);
      a.click();

      // this.downloadAudio.select.forEach(item=>{
      //     const a=document.createElement('a')
      //     a.setAttribute("download",item.VideoName)
      //     a.style.display = "none"
      // 	   a.href=`${this.dayWeekAudio}?ChapterIds=${item.ReportChapterId}`
      //     document.body.appendChild(a);
      //     a.click()
      // })
    },

    renderHeader(h, { column, $index }) {
      //table表头自定义
      return h("div", { attrs: { style: "padding:0;" } }, [
        h("span", column.label),
        h("el-tooltip", { props: { placement: "top" } }, [
          h(
            "p",
            {
              slot: "content",
              attrs: { style: "display:block;padding:5px 0;width:420px;" },
            },
            "pv：报告被打开的次数，每次打开都计算一次（只统计有权限用户）"
          ),
          h(
            "p",
            {
              slot: "content",
              attrs: { style: "display:block;padding:5px 0;width:420px;" },
            },
            "uv：访问报告的人数，每篇报告同一个人访问只计算一次（只统计有权限用户）"
          ),
          h(
            "el-button",
            {
              props: { icon: "el-icon-info" },
              attrs: { style: "border:none;background:none" },
            },
            ""
          ),
        ]),
      ]);
    },
    async editreport(item, type) {
      // if(type==='editing'){
      //   this.$message.warning('该研报正在编辑，不可重复编辑')
      //   return
      // }
      //编辑前标记一下
      const res = await markReport({
        Status: 1,
        ReportId: item.Id,
      });
      if (res.Ret === 200) {
        if (res.Data.Status == 1) {
          this.$message.warning(res.Data.Msg || "该研报正在编辑，不可重复编辑");
          item.CanEdit = false;
          item.Editor = res.Data.Editor || "";
          return;
        } else if (res.Data.Status == 0) {
          item.CanEdit = true;
          item.Editor = res.Data.Editor || "";
        }
      } else {
        this.$message.error(res.ErrMsg || "未知错误，请稍后重试");
        return;
      }
      // 晨报周报
      if (["day", "week"].includes(item.ChapterType)) {
        sessionStorage.setItem("dayWeek", JSON.stringify(item));
        this.$router.push({
          path: "/dayorweek",
          query: {
            reportid: item.Id,
            isEdit: true,
            type: item.ChapterType,
          },
        });
        return;
      }

      sessionStorage.setItem("searchform", JSON.stringify(this.searchform));
      sessionStorage.setItem("PageIndex", this.PageIndex);
      this.$router.push({
        path: item.ReportVersion === 2 ? "/editreportNew" : "/editreport",
        query: {
          id: item.Id,
        },
      });
    },
    lookreportdtl(item) {
      //如果没有预览权限，就不跳转
      if(!this.permissionBtn.checkPermissionBtn(this.permissionBtn.reportManageBtn.reportManage_reportView)) return
      sessionStorage.setItem("reportdtl", JSON.stringify(item));
      let { href } = this.$router.resolve({
        name: "预览报告",
        query: { id: item.Id, code: item.ReportCode },
      });
      window.open(href, "_blank");
    },
    openupload(id) {
      //唤醒上传弹窗
      this.uploadForm = { id: id, formdata: null, audioname: "" };
      this.uploadDialog = true;
    },
    clickinput() {
      //上传模拟点击
      $("#file").click();
    },
    fileSelected() {
      //选择文件上传
      const that = this;
      if (document.getElementById("file").files[0]) {
        let hostfile = document.getElementById("file").files[0];
        let size = Math.floor(hostfile.size / 1024 / 1024);
        if (size > 200) {
          that.$message.error("上传文件大小不能大于200M！");
          hostfile = {};
          return false;
        }
        if (
          hostfile.name.includes(".mp3") ||
          hostfile.name.includes(".wav") ||
          hostfile.name.includes(".wma")
        ) {
          let form = new FormData();
          form.append("file", hostfile); //hostfile.name
          form.append("ReportId", this.uploadForm.id);
          this.uploadForm.formdata = form;
          this.uploadForm.audioname = hostfile.name;
        } else {
          that.$message.error("上传文件格式不正确！");
        }
      }
    },
    uploadaudio() {
      if (this.uploadForm.formdata == null) {
        this.$message.error("请选择文件");
        return false;
      }
      this.uploadloading = true;
      voiceupload(this.uploadForm.formdata).then((res) => {
        if (res.Ret === 200) {
          this.$message.success("上传成功");
          this.getlist();
        }
        this.uploadloading = false;
        $("#file").val("");
        this.uploadDialog = false;
      });
    },
    gosendTemplateMsg(item) {
      //推送消息
      item.MsgIsSend = 1;
      sendTemplateMsg({ ReportId: parseInt(item.Id) }).then((res) => {
        if (res.Ret === 200) {
          this.$message.success(res.Msg);
          this.getlist();
        }
      });
    },
    checkboxT(row, rowIndex) {
      //复选框禁用
      if (row.State == "2") {
        return false; //禁用
      } else {
        return true; //不禁用
      }
    },
    sortChange(column, prop, order) {
      //排序 ascending descending
      this.searchform.publish_sort =
        column.order == "ascending"
          ? "asc"
          : column.order == "descending"
          ? "desc"
          : "";
      this.search();
    },
    canclepublish(item) {
      //取消发布
      reportpublishcancle({ ReportIds: item.Id }).then((res) => {
        if (res.Ret === 200) {
          this.$message.success(res.Msg);
          this.getlist();
        }
      });
    },
    deleteitem(item) {
      //删除
      this.$confirm("确认删除吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          reportdelete({ ReportIds: item.Id }).then((res) => {
            if (res.Ret === 200) {
              this.$message.success(res.Msg);
              this.getlist();
            }
          });
        })
        .catch(() => {});
    },
    async publishreport(item) {
      //发布报告
      this.batches = [];
      this.batches.push(item.Id);

      // 周报不需要弹窗直接发布
      // 2023/3/6 研报后台5.5中修改 周报校验是否上传了音频
      if (item.ClassifyNameFirst == "周报") {
        const validRes = await weekReportValidAudio({
          ReportId: Number(item.Id),
        });
        if (validRes.Ret === 200) {
          if (validRes.Data) {
            this.$confirm(
              `报告未上传录音：${validRes.Data.join("、")}，确定发布吗？`,
              "发布提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(() => {
                // this.handlePublishReport()
                this.showPublish = true;
              })
              .catch(() => {});
          } else {
            this.showPublish = true;
          }
        }

        // this.handlePublic(1)
        return;
      }

      this.showPublish = true;
    },
    // 点击确认发布&推送报告
    // 1 仅发布 2发布且推送
    handlePublic(type) {
      reportpublish({ ReportIds: this.batches.join(",") }).then((res) => {
        if (res.Ret == 200) {
          if (type == 2) {
            reportMessageSend({
              ReportId: this.batches[0],
            }).then((resMsg) => {
              if (resMsg.Ret == 200) {
                this.$message.success("发布且推送成功");
                this.batches = [];
                this.getlist();
                this.showPublish = false;
                // this.$refs.table.clearSelection()
              }
            });
          } else {
            if (res.Data) {
              this.$alert(res.Data, "发布提示", {
                confirmButtonText: "确定",
                callback: (action) => {},
              });
            } else {
              this.$message.success("发布成功");
            }
            this.batches = [];
            this.getlist();
            this.showPublish = false;

            // this.$refs.table.clearSelection()
          }
        }
      });
    },
    handleClosePublish() {
      this.batches = [];
      this.showPublish = false;
    },

    selectchange(val) {
      //多选操作
      this.batches = [];
      val.forEach((item) => {
        this.batches.push(item.Id);
      });
    },
    getclassifylist() {
      //获取分类列表
      let params = { CurrentIndex: 0, PageSize: 1000, KeyWord: "" };
      classifylist(params).then((res) => {
        if (res.Ret == 200 && Array.isArray(res.Data.List)) {
          this.optionsArr = [];
          res.Data.List.forEach((item, index) => {
            let newitem = {
              label: item.ClassifyName,
              value: item.ClassifyName,
            };
            if (item.Child) {
              let childnode = [];
              item.Child.forEach((itemchild, i) => {
                childnode.push({
                  label: itemchild.ClassifyName,
                  value: itemchild.ClassifyName,
                });
              });
              newitem.children = childnode;
            }
            this.optionsArr.push(newitem);
          });
        }
      });
    },
    getlist() {
      //获取列表
      let params = {
        CurrentIndex: this.PageIndex,
        PageSize: this.pageSize,
        Frequency: this.searchform.frequency,
        ClassifyNameFirst: this.searchform.classifynameArr
          ? this.searchform.classifynameArr[0]
          : "",
        ClassifyNameSecond:
          this.searchform.classifynameArr &&
          this.searchform.classifynameArr.length > 1
            ? this.searchform.classifynameArr[1]
            : "",
        State: this.searchform.state ? this.searchform.state : null,
        KeyWord: this.searchform.key_word,
        MsgIsSend: this.searchform.msgIsSend,
        // PublishSort:this.searchform.publish_sort,
      };
      if (this.searchform.dateValue) {
        params.StartDate = this.searchform.dateValue[0];
        params.EndDate = this.searchform.dateValue[1];
      }
      this.listLoading = true;
      reportlist(params).then((res) => {
        if (res.Ret === 200) {
          this.tableData = res.Data.List || [];
          this.total = parseInt(res.Data.Paging.Totals);
        }
        this.listLoading = false;
      });
    },
    search() {
      //搜索
      this.ispage = false;
      this.$nextTick(() => {
        this.PageIndex = 1;
        this.getlist();
        this.ispage = true;
      });
    },
    handleCurrentChange(current) {
      //分页页码跳转
      this.PageIndex = current;
      this.getlist();
    },
    handleSizeChange(val) {
      //分页页码改变
      this.pageSize = val;
      this.getlist();
    },
    /* 下载阅读数据 */
    downLoadReport() {
      if (this.batches.length == 0) {
        this.$confirm("请选择需要下载的报告", "提示", {
          type: "warning",
          showCancelButton: false,
        })
          .then(() => {})
          .catch(() => {});
        return false;
      }
      // const xhr = new XMLHttpRequest();
      // xhr.open('GET',this.exportUrlDl);
      // xhr.onprogress = function (event) {
      // 	console.log(event);
      // 	if (event.lengthComputable) {
      // 			console.log(event.loaded);
      // 			console.log(event.total);
      // 		const process = event.loaded/event.total;
      // 		process < 1 ? console.log('loading') : console.log('完成')
      // 	}
      // };
      // const link = document.createElement('a')
      // link.href = this.exportUrlDl
      // link.download = '';
      // link.click();
      // xhr.send();
    },
    //推送客群消息
    async messagePush(item) {
      const res = await messagePushPost({
        ReportId: [item.Id],
      });
      if (res.Ret == 200) {
        item.ThsMsgIsSend = 1;
        this.$message.success("发送成功");
      }
    },

    // 推送消息（同时推送模板消息和客群消息）
    messageSend(item) {
      reportMessageSend({ ReportId: item.Id }).then((res) => {
        if (res.Ret === 200) {
          this.$message.success("推送成功");
          item.MsgIsSend = 1;
        }
      });
    },
  },
};
</script>

<style lang="scss">
.download-audio-wrap {
  .el-checkbox__label {
    white-space: normal;
  }
}
</style>
<style scoped lang="scss">
#reportlist {
  overflow: hidden;
  .header .el-form-item {
    margin-bottom: 0;
  }
  .opt-btns {
    span,
    a {
      display: inline-block;
      margin: 0 3px;
    }
  }
}
</style>
