<template>
  <div class="execution">
    <basic-container>
      <!-- :selectable='selectable'  -->
      <avue-crud
        ref="crud"
        :page="pageTask"
        :data="tableDataTask"
        :table-loading="tableLoadingTask"
        :option="tableOptionTask"
        @selection-change="selectionChange"
        @on-load="getListTask"
        @search-change="searchChangeTask"
        @refresh-change="refreshChangeTask"
        @size-change="sizeChangeTask"
        @current-change="currentChangeTask"
      >
        <template slot="menuLeft">
          <el-button
            type="primary"
            @click="exportTaskInfoAll()"
            :loading="infoExportAllLoading"
            >合并导出<i class="el-icon-download el-icon--right"></i
          ></el-button>
        </template>

        <template slot="menu" slot-scope="scope">
          <el-button
            v-show="scope.row.packageType2 == '1'"
            type="text"
            size="small"
            icon="el-icon-check"
            :disabled="scope.row.ysh <= 0"
            @click="exportBtn(scope.row, scope.index)"
          >
            导出
          </el-button>

          <el-button
            type="text"
            size="small"
            icon="el-icon-check"
            :disabled="scope.row.ysh <= 0"
            @click="lookDetail(scope.row, scope.index)"
            >查看
          </el-button>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="40%"
      :close-on-click-modal="false"
      center
    >
      <!-- 合并导出 -->
      <template v-if="!checkRow">
        <div class="all-down">
          <span>word格式：</span>
          <el-button
            class="down-info"
            v-if="allDownInfo.status === 'NOT_GENERATE'"
            @click="taskExport('word')"
            :loading="wordLoading"
            >导出报告</el-button
          >
          <el-button
            class="down-info"
            v-if="allDownInfo.status === 'GENERATING'"
            disabled
            :loading="true"
            >报告生成中</el-button
          >
          <el-button v-if="allDownInfo.status === 'UNDERLINE'" disabled
            >报告生成失败</el-button
          >
          <el-button
            v-if="
              allDownInfo.status === 'UNDERLINE' ||
                allDownInfo.status === 'GENERATED'
            "
            @click="allDownReset('word')"
            >重新生成</el-button
          >
          <el-button
            v-if="allDownInfo.status === 'GENERATED'"
            @click="allDownClick('word')"
            >下载报告</el-button
          >
          <div class="title-msg">
            <p v-if="allDownInfo.status === 'GENERATED'">
              下载截止日期：{{ allDownInfo.ttl }}
            </p>
            <p v-if="allDownInfo.status === 'ERROR'">
              本次导出失败：{{ allDownInfo.errorMsg }}
            </p>
          </div>
        </div>
        <div class="all-down">
          <span>excel格式：</span>
          <el-button
            class="down-info"
            v-if="allExcelDownInfo.status === 'NOT_GENERATE'"
            @click="taskExport('excel')"
            :loading="excelLoading"
            >导出报告</el-button
          >
          <el-button
            class="down-info"
            v-if="allExcelDownInfo.status === 'GENERATING'"
            disabled
            :loading="true"
            >报告生成中</el-button
          >
          <el-button v-if="allExcelDownInfo.status === 'UNDERLINE'" disabled
            >报告生成失败</el-button
          >
          <el-button
            v-if="
              allExcelDownInfo.status === 'UNDERLINE' ||
                allExcelDownInfo.status === 'GENERATED'
            "
            @click="allDownReset('excel')"
            >重新生成</el-button
          >
          <el-button
            v-if="allExcelDownInfo.status === 'GENERATED'"
            @click="allDownClick('excel')"
            >下载报告</el-button
          >
          <div class="title-msg">
            <p v-if="allExcelDownInfo.status === 'GENERATED'">
              下载截止日期：{{ allExcelDownInfo.ttl }}
            </p>
            <p v-if="allExcelDownInfo.status === 'ERROR'">
              本次导出失败：{{ allExcelDownInfo.errorMsg }}
            </p>
          </div>
        </div>
      </template>

      <!-- 第一次导出 -->
      <template v-if="checkRow">
        <div class="all-down">
          <span>word格式：</span>
          <template
            v-if="checkRow && checkRow.reportOpt.status === 'NOT_GENERATE'"
          >
            <el-button
              class="down-info"
              @click="taskExport('word')"
              :loading="wordLoading"
              >生成报告</el-button
            >
          </template>
          <template
            v-else-if="checkRow && checkRow.reportOpt.status === 'GENERATING'"
          >
            <el-button class="down-info" :loading="true"
              >报告生成中...</el-button
            >
          </template>
          <template
            v-else-if="
              checkRow &&
                (checkRow.reportOpt.status === 'GENERATED' ||
                  checkRow.reportOpt.status === 'ERROR')
            "
          >
            <el-button @click="taskExport('word')">重新导出</el-button>
            <el-button
              @click="downloadTask('word')"
              v-if="checkRow.reportOpt.status === 'GENERATED'"
              >下载报告</el-button
            >
            <el-button
              disabled
              :title="checkRow.reportOpt.errorMsg"
              v-else-if="checkRow.reportOpt.status === 'ERROR'"
              >导出失败</el-button
            >
          </template>
          <div class="title-msg">
            <p v-if="checkRow.reportOpt.status === 'GENERATED'">
              下载截止日期：{{ checkRow.reportOpt.ttl }}
            </p>
            <p v-if="checkRow.reportOpt.status === 'ERROR'">
              本次导出失败：{{ checkRow.reportOpt.errorMsg }}
            </p>
          </div>
        </div>
        <div class="all-down">
          <span>excel格式：</span>
          <template
            v-if="checkRow && checkRow.excelReportOpt.status === 'NOT_GENERATE'"
          >
            <el-button
              class="down-info"
              @click="taskExport('excel')"
              :loading="excelLoading"
              >生成报告</el-button
            >
          </template>
          <template
            v-if="checkRow && checkRow.excelReportOpt.status === 'GENERATING'"
          >
            <el-button class="down-info" :loading="true"
              >报告生成中...</el-button
            >
          </template>
          <template
            v-else-if="
              checkRow &&
                (checkRow.excelReportOpt.status === 'GENERATED' ||
                  checkRow.excelReportOpt.status === 'ERROR')
            "
          >
            <el-button @click="taskExport('excel')">重新导出</el-button>
            <el-button
              @click="downloadTask('excel')"
              v-if="checkRow.excelReportOpt.status === 'GENERATED'"
              >下载报告</el-button
            >
            <el-button
              disabled
              :title="checkRow.excelReportOpt.errorMsg"
              v-else-if="checkRow.excelReportOpt.status === 'ERROR'"
              >导出失败</el-button
            >
          </template>
          <div class="title-msg">
            <p v-if="checkRow.excelReportOpt.status === 'GENERATED'">
              下载截止日期：{{ checkRow.excelReportOpt.ttl }}
            </p>
            <p v-if="checkRow.excelReportOpt.status === 'ERROR'">
              本次导出失败：{{ checkRow.excelReportOpt.errorMsg }}
            </p>
          </div>
        </div>
      </template>

      <span slot="footer" class="dialog-footer">
        注意： 1.报告将于24小时之内生成完毕，请注意下载。<br />
        <i style="margin-left:62px"></i
        >2.报告汇总为封面+任务数据汇总+任务列表明细。
        <br />
        <i style="margin-left:10px"></i>3.报告详情为每条任务的任务详情+图片。
      </span>
    </el-dialog>
    <exportDialog
      :dialogShow.sync="dialogShow"
      type="4"
      :packageIds="packageIds"
      :checkRow="checkRow"
      @downSuccess="downSuccess"
    />
  </div>
</template>

<script>
import {
  exportZbReport,
  taskExportZbqybgInfo,
  infoExportJsInfo,
  getExportPackageZbTotalList,
  exportExcelZbStatus,
  exportZbStatus,
  exportExcelZbReport,
  allExportStatus
} from "@/api/wmtask";
import { exportReport } from "@/const/crud/export";
import { mapGetters } from "vuex";
import exportDialog from "@/components/exportDialog/index";
export default {
  name: "wmtask",
  components: { exportDialog },
  data() {
    return {
      dialogShow: false,
      infoExportAllLoading: false,
      wordLoading: false,
      excelLoading: false,
      taskExportLoading: false,
      taskExportInfoLoading: false,
      centerDialogVisible: false,
      checkRow: null,
      packageIds: "",
      isAllCheck: false,
      tableLoading: false,
      allDownInfo: {},
      allExcelDownInfo: {},
      isHasAudit: false,
      formTask: {},
      searchFormTask: {},
      tableDataTask: [],
      pageTask: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoadingTask: false,
      tableOptionTask: exportReport
    };
  },
  computed: {},

  methods: {
    sizeChangeTask(pageSize) {
      this.pageTask.pageSize = pageSize;
    },
    currentChangeTask(current) {
      this.pageTask.currentPage = current;
    },
    // 查询
    searchChangeTask(form, done) {
      this.searchFormTask = form;
      this.pageTask.currentPage = 1;
      this.getListTask(this.pageTask, form);
      done();
    },
    // 刷新
    refreshChangeTask() {
      this.getListTask(this.pageTask);
    },
    // 初始化列表
    getListTask(page, params) {
      this.tableLoadingTask = true;
      getExportPackageZbTotalList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchFormTask
        )
      )
        .then(response => {
          this.tableDataTask = response.data.data.records;
          this.pageTask.total = response.data.data.total;
          this.tableLoadingTask = false;
        })
        .catch(() => {
          this.tableLoadingTask = false;
        });
    },
    downSuccess() {
      this.getListTask(this.pageTask);
    },

    // 导出按钮
    showExportDia(row, index) {
      this.checkRow = row;
      this.centerDialogVisible = true;
      this.isAllCheck = false;
    },
    exportBtn(row) {
      this.checkRow = row;
      this.dialogShow = true;
    },
    // 导出汇总报告按钮
    async taskExport(type) {
      let rowid = "";
      if (this.isAllCheck) {
        rowid = this.packageIds;
      } else {
        let row = this.checkRow;
        rowid = row.id;
      }
      var obj = {
        exportType: 1,
        scorePackageDrugId: rowid
      };
      let res;
      if (type === "word") {
        this.wordLoading = true;
        res = await exportZbReport(obj);
      } else if (type === "excel") {
        this.excelLoading = true;
        res = await exportExcelZbReport(obj);
      }
      if (res.data) {
        this.$message.success(res.data.data);
        this.centerDialogVisible = false;
        this.getListTask(this.pageTask);
        this.wordLoading = false;
        this.excelLoading = false;
        this.allDownInfo = {};
        this.allExcelDownInfo = {};
      } else {
        this.$message.error("导出失败");
      }
    },
    downloadTask(type) {
      let latestUrl;
      if (type === "word") {
        latestUrl = this.checkRow.reportOpt.latestUrl;
      } else if (type === "excel") {
        latestUrl = this.checkRow.excelReportOpt.latestUrl;
      }
      let a = document.createElement("a");
      a.href = latestUrl;
      a.click();
      this.$message.success("导出汇总报告成功");
      this.centerDialogVisible = false;
    },
    // 导出报告详情
    taskExportInfo() {
      this.taskExportInfoLoading = true;
      let rowid = "";
      if (this.isAllCheck) {
        rowid = this.packageIds;
      } else {
        let row = this.checkRow;
        rowid = row.id;
      }
      var obj = {
        exportType: 2,
        scorePackageDrugId: rowid
      };
      exportZbReport(obj).then(response => {
        if (undefined == response.data || undefined == response.data.data) {
          this.$message.error("导出失败");
          return false;
        }
        let obj = response.data.data;
        let a = document.createElement("a");
        a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
        a.click();
        this.taskExportInfoLoading = false;
      });
    },

    // 合并导出
    async exportTaskInfoAll() {
      if ("" == this.packageIds) {
        this.$message.error("请选择需要导出的列");
        return false;
      }
      this.isAllCheck = true;
      this.checkRow = null;
      await this.getExportZbStatus();
    },

    async getExportZbStatus() {
      let rowid = "";
      if (this.isAllCheck) {
        const arr = this.packageIds
          .split(",")
          .sort((a, b) => Number(a) - Number(b));
        rowid = arr.join(",");
      } else {
        let row = this.checkRow;
        rowid = row.id;
      }
      var obj = {
        id: rowid
      };
      const res = await allExportStatus(obj);
      console.log("res", res);
      if (res.data.code === 0) {
        this.allDownInfo = res.data.data;
        this.checkRow = res.data.data;
        this.dialogShow = true;
      }
    },
    allDownClick(type) {
      let latestUrl;
      if (type === "word") {
        latestUrl = this.allDownInfo.latestUrl;
      } else if (type === "excel") {
        latestUrl = this.allExcelDownInfo.latestUrl;
      }
      let a = document.createElement("a");
      a.href = latestUrl;
      a.click();
      this.$message.success("导出汇总报告成功");
      this.centerDialogVisible = false;
      return false;
    },

    // 复选框选中的值
    selectionChange(selection, row) {
      this.isHasAudit = false;
      this.packageIds = "";
      if (undefined != selection) {
        for (var i = 0; i < selection.length; i++) {
          if (selection[i].ysh > 0) {
            this.isHasAudit = true;
          }
          this.packageIds += selection[i].id;
          if (i < selection.length - 1) {
            this.packageIds += ",";
          }
        }
      }
    },
    // 重新生成
    async allDownReset(type) {
      await this.taskExport(type);
    },
    // 查看详情按钮
    lookDetail(row) {
      this.$router.push({
        path: "/admin/export/reportExportlook?id=" + row.id
      });
    }
  }
};
</script>
<style scoped lang="scss">
.generating {
  color: #1e90ff;
  text-align: center;
  display: block;
}

.btns {
  display: flex;
  justify-content: center;
}

.title-msg {
  text-align: center;
  margin-top: 10px;
}

.all-down {
  margin-left: 80px;
  margin-bottom: 15px;
  span {
    width: 80px;
    display: inline-block;
    text-align: right;
  }
  .down-info {
    width: 240px;
  }
}
</style>
