<template>
  <div class="charge-box">
    <div class="charge-tools">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="数据来源：" style="margin-left: 35px">
          <el-select
            v-model="queryParams.exportLogType"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in LogTypeArr"
              :key="item.id"
              :label="item.value"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="任务名称:" style="margin-left: 50px">
          <el-input
            v-model.trim="queryParams.exportName"
            placeholder="请输入任务名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="时间范围:" style="margin-left: 50px">
          <el-date-picker
            v-model="dateTime"
            class="times"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="serch actve" @click="handleQuery"
            >查询</el-button
          >
          <el-button type="primary" class="serch" @click="resetForm"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="charge-table">
      <div class="charge-table-bottom">
        <el-table
          :data="datalist"
          :header-cell-style="{
            background: '#1d283e',
            borderColor: '#2f3c86',
            height: '36px',
            lineHeight: '36px',
            color: 'white',
            fontSize: '15px',
          }"
          stripe
          fit
          :height="tableheight"
          style="width: 100%"
        >
          <el-table-column prop="exportName" label="导出任务名称" />
          <el-table-column label="日志类型">
            <template slot-scope="scope">
              <span v-if="scope.row.exportLogType === 1">机器人</span>
              <span v-else-if="scope.row.exportLogType === 2">充电机</span>
              <span v-else-if="scope.row.exportLogType === 3">BMS</span>
            </template>
          </el-table-column>
          <el-table-column prop="exporterName" label="创建人" />
          <el-table-column label="状态" width="400">
            <template slot-scope="scope">
              <span v-if="scope.row.exportStatus !== 2">{{
                scope.row.exportStatus === 0 ? "完成" : "失败"
              }}</span>
              <span v-else
                ><el-progress
                  :percentage="scope.row.exportProgress"
                ></el-progress
              ></span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.exportStatus === 0">
                <el-button
                  type="primary"
                  class="handle"
                  size="small"
                  @click="
                    handleDownFile(
                      scope.row.exportFilePath,
                      scope.row.exportName
                    )
                  "
                  >下载</el-button
                >
              </span>
              <span v-if="scope.row.exportStatus !== 2">
                <el-button
                  type="primary"
                  class="handle"
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  >删除</el-button
                >
              </span>

              <span v-else>— —</span>
            </template>
          </el-table-column>
        </el-table>
        <vue-loading
          :isLoading="showTotip"
          type="loading3"
          text="下载中..."
          color="lightgreen"
          scale="1"
        ></vue-loading>
      </div>
      <div class="pageblock">
        <el-pagination
          :current-page="queryParams.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import "./log.scss";
import { exportList, deleteExportData, RecordFile } from "@/api/log";
import request from "@/utils/longRuquest";
export default {
  name: "DataExport",
  components: {},
  data() {
    return {
      //下载提示框
      showTotip: false,
      // 查询时间数组
      dateTime: "",
      // 导出类型z1
      LogTypeArr: [
        {
          id: 1,
          value: "机器人",
        },
        {
          id: 2,
          value: "充电机",
        },
        {
          id: 3,
          value: "BMS",
        },
      ], //日志类型
      // 数据列表
      datalist: [],
      exportLogType: undefined,
      exporterId: 0, //导出人id
      // 查询参数
      queryParams: {
        page: 1, // 当前页
        pageSize: 10, // 每页条数
        exportName: undefined, // 导出任务名称
        exporterId: undefined, // 导出人id
        startTime: undefined,
        endTime: undefined,
        orderByField: "createTime", // 排序字段
        orderByWays: "desc", // 排序方式
        exporterId: this.$store.getters.userId,
      },
      total: 0, // 总条数，
      tableheight: 0, // 表格高度设置
      loading: false,
      heightTimer: false,
      exportTimer: null, //定时器
    };
  },
  watch: {
    tableheight(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.heightTimer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenHeight = val;
        this.heightTimer = true;
        setTimeout(function () {
          this.heightTimer = false;
        }, 400);
      }
    },
  },
  destroyed() {
    this.clearListTimer();
  },
  mounted() {
    this.onLoadHeight();
    this.changeWindow();
    //清除定时器
    this.clearListTimer();
    //开启定时任务
    this.setListTimer();
  },
  methods: {
    //定时请求导出列表
    setListTimer() {
      this.getExportList();
      this.exportTimer = setInterval(() => {
        this.getExportList();
      }, 1000);
    },
    //清除定时器
    clearListTimer() {
      if (this.exportTimer) {
        clearInterval(this.exportTimer);
      }
    },
    /* 设置初始视窗高度*/
    onLoadHeight() {
      this.$nextTick(() => {
        this.tableheight = document.body.clientHeight - 370;
      });
    },
    /* 设置窗口变化高度*/
    changeWindow() {
      window.onresize = () => {
        return (() => {
          this.tableheight = document.body.clientHeight - 370;
        })();
      };
    },
    // 清空表单数据
    dialogClose() {},
    //获取换电记录列表
    getExportList() {
      this.exportList(this.queryParams).then((res) => {
        if (res?.code == 0) {
          this.datalist = res.data.list;
          this.total = res.data.total;
        }
      });
    },
    /** 分页下一页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getExportList();
    },
    /** 分页选择页数 */
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getExportList();
    },
    // 搜索
    handleQuery() {
      if (this.dateTime) {
        this.queryParams.startTime = this.$moment(this.dateTime[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.queryParams.endTime = this.$moment(this.dateTime[1]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      this.getExportList();
    },
    // 搜索重置
    resetForm() {
      // window.location.reload();
      this.queryParams = {
        page: 1, // 当前页
        pageSize: 10, // 每页条数
        exportName: undefined, // 导出任务名称
        startTime: undefined,
        endTime: undefined,
        orderByField: "createTime", // 排序字段
        orderByWays: "desc", // 排序方式
        exporterId: this.$store.getters.userId,
      };
      this.dateTime = "";
      this.queryParams.page = 1;
      this.queryParams.pageSize = 10;
      this.getExportList();
    },
    //删除导出任务列表
    handleDelete(id) {
      this.$confirm("删除数据将丢失,请确认是否删除", "确认删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.deleteExportData(id);
          this.$message({
            type: "success",
            message: "删除成功！",
          });
          this.getExportList();
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //下载文件
    async handleDownFile(url, fileName) {
      this.showTotip = true;
      const execlUrl = process.env.VUE_APP_BASE_API + "/excel/" + url;
      const fileDownName = fileName + "_" + new Date().getTime();
      console.log(execlUrl, fileDownName);
      const resUrl = await this.RecordFile(execlUrl, fileDownName);
    },
    //导出数据列表
    exportList(data) {
      return request({
        url: "/export/list",
        method: "post",
        data,
      });
    },
    //删除数据导出列表
    deleteExportData(id) {
      return request({
        url: `/export/delete/${id}`,
        method: "post",
      });
    },
    RecordFile(Fileurl, fileName) {
      setTimeout(() => {
        this.showTotip = false;
      }, 7200000);
      //接口方法
      return request({
        url: Fileurl,
        method: "get",
        responseType: "blob",
      }).then((data) => {
        console.log("RecordFile then", data);

        if (!data) {
          this.showTotip = false;
          return alert("文件下载失败");
        }
        // let fileName = '统计表计';
        if (typeof window.navigator.msSaveBlob !== "undefined") {
          // window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx');
          window.navigator.msSaveBlob(
            new Blob([data], { type: "application/vnd.ms-excel" }),
            fileName
          );
        } else {
          let url = window.URL.createObjectURL(
            new Blob([data], { type: "application/vnd.ms-excel" })
          );
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
        this.showTotip = false;
      });
    },
  },
};
</script>
<style scoped>
::v-deep .el-table__fixed{
  height: calc(100% - 10px) !important;
}
::v-deep .el-table th.is-leaf{
  font-size: 15px !important;
}
</style>