<script src="../../../api/admin/user.js"></script>
<template>
  <basic-container>
    <div class="tabStyle">
      <avue-crud
        :data="tableDataTask"
        :option="option"
        :page.sync="page"
        :table-loading="tableLoadingTask"
        @on-load="getListTask"
        @search-change="searchVal"
        @size-change="sizeChange"
        @current-change="currentChange"
      >
        <template slot="taskTypes" slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-view" @click="viewDetail(scope.row, scope.index)">查看 </el-button>
        </template>

        <template slot="p2pAmount" slot-scope="scope">
          <span v-if="!scope.row.p2pDraft">{{ scope.row.p2pAmount + scope.row.p2pServiceAmount }}</span>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-tickets" @click="generateBtn(scope.row, scope.index)">生成报告 </el-button>

          <el-button type="text" size="small" icon="el-icon-view" @click="lookBtn(scope.row, scope.index)">查看 </el-button>

          <el-button type="text" size="small" icon="el-icon-folder-checked" :disabled="scope.row.ysh == 0 || scope.row.ysh == null" @click="exportBtn(scope.row, scope.index)">
            导出
          </el-button>
        </template>
      </avue-crud>
    </div>

    <!-- 生成报告弹窗 -->
    <el-dialog title="生成报告" :visible.sync="showReport" width="35%" :before-close="handleClose">
      <el-form ref="reportForm" :model="reportForm" label-width="120px">
        <el-form-item label="积分包名称">
          <el-input v-model="reportForm.score_package_name" :disabled="notUse"></el-input>
        </el-form-item>

        <el-form-item label="报告ID">
          <el-input v-model="reportForm.report_id" :disabled="notUse"></el-input>
        </el-form-item>

        <el-form-item label="完成积分值">
          <el-input v-model="reportForm.score" :disabled="notUse"></el-input>
        </el-form-item>

        <el-form-item label="合计服务数">
          <el-input v-model="reportForm.score_count" :disabled="notUse"></el-input>
        </el-form-item>

        <el-form-item label="结算企业">
          <el-input v-model="reportForm.description" :disabled="notUse"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="generateApproval" :disabled="approValnot">生成报告并审批</el-button>
        <!-- <el-button type="primary" @click="generateReport" :disabled="reportNot"
          >生成报告</el-button
        > -->
      </span>
    </el-dialog>

    <!-- 导出弹窗 -->
    <el-dialog title="导出" :visible.sync="exportDig" width="38%" :close-on-click-modal="false" center>
      <!-- 第一次导出 -->
      <template>
        <div class="down-item">
          <div class="btn">
            <span>word格式：</span>
            <template v-if="checkRow && checkRow.reportOpt.status === 'NOT_GENERATE'">
              <el-button class="first" @click="taskExport('word')" :loading="wordLoading">生成报告</el-button>
            </template>
            <template v-else-if="checkRow && checkRow.reportOpt.status === 'GENERATING'">
              <el-button class="first" :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>
          <div class="title-msg">
            <p v-if="checkRow && checkRow.reportOpt.status === 'GENERATED'">下载截止日期：{{ checkRow.reportOpt.ttl }}</p>
            <p v-if="checkRow && checkRow.reportOpt.status === 'ERROR'">本次导出失败：{{ checkRow.reportOpt.errorMsg }}</p>
          </div>
        </div>
        <div class="down-item">
          <div class="btn">
            <span>excel格式：</span>
            <template v-if="checkRow && checkRow.excelReportOpt.status === 'NOT_GENERATE'">
              <el-button class="first" @click="taskExport('excel')" :loading="excelLoading">生成报告</el-button>
            </template>
            <template v-if="checkRow && checkRow.excelReportOpt.status === 'GENERATING'">
              <el-button class="first" :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>
          <div class="title-msg">
            <p v-if="checkRow && checkRow.excelReportOpt.status === 'GENERATED'">下载截止日期：{{ checkRow.excelReportOpt.ttl }}</p>
            <p v-if="checkRow && checkRow.excelReportOpt.status === 'ERROR'">本次导出失败：{{ checkRow.excelReportOpt.errorMsg }}</p>
          </div>
        </div>
      </template>
      <el-divider></el-divider>
      <!-- 新版导出 -->
      <template>
        <div class="down-item">
          <div class="btn">
            <span>word格式（新版）：</span>
            <template v-if="checkRow && checkRow.newReportOpt.status === 'NOT_GENERATE'">
              <el-button class="first" @click="taskNewExport('word')" :loading="newWordLoading">生成报告</el-button>
            </template>
            <template v-else-if="checkRow && checkRow.newReportOpt.status === 'GENERATING'">
              <el-button class="first" :loading="true">报告生成中...</el-button>
            </template>
            <template v-else-if="checkRow && (checkRow.newReportOpt.status === 'GENERATED' || checkRow.newReportOpt.status === 'ERROR')">
              <el-button @click="taskNewExport('word')">重新导出</el-button>
              <el-button @click="downloadNewTask('word')" v-if="checkRow.newReportOpt.status === 'GENERATED'">下载报告</el-button>
              <el-button disabled :title="checkRow.newReportOpt.errorMsg" v-else-if="checkRow.newReportOpt.status === 'ERROR'">导出失败</el-button>
            </template>
          </div>
          <div class="title-msg">
            <p v-if="checkRow && checkRow.newReportOpt.status === 'GENERATED'">下载截止日期：{{ checkRow.newReportOpt.ttl }}</p>
            <p v-if="checkRow && checkRow.newReportOpt.status === 'ERROR'">本次导出失败：{{ checkRow.newReportOpt.errorMsg }}</p>
          </div>
        </div>
        <div class="down-item">
          <div class="btn">
            <span>excel格式（新版）：</span>
            <template v-if="checkRow && checkRow.newExcelReportOpt.status === 'NOT_GENERATE'">
              <el-button class="first" @click="taskNewExport('excel')" :loading="newExcelLoading">生成报告</el-button>
            </template>
            <template v-if="checkRow && checkRow.newExcelReportOpt.status === 'GENERATING'">
              <el-button class="first" :loading="true">报告生成中...</el-button>
            </template>
            <template v-else-if="checkRow && (checkRow.newExcelReportOpt.status === 'GENERATED' || checkRow.newExcelReportOpt.status === 'ERROR')">
              <el-button @click="taskNewExport('excel')">重新导出</el-button>
              <el-button @click="downloadNewTask('excel')" v-if="checkRow.newExcelReportOpt.status === 'GENERATED'">下载报告</el-button>
              <el-button disabled :title="checkRow.newExcelReportOpt.errorMsg" v-else-if="checkRow.newExcelReportOpt.status === 'ERROR'">导出失败</el-button>
            </template>
          </div>
          <div class="title-msg">
            <p v-if="checkRow && checkRow.newExcelReportOpt.status === 'GENERATED'">下载截止日期：{{ checkRow.newExcelReportOpt.ttl }}</p>
            <p v-if="checkRow && checkRow.newExcelReportOpt.status === 'ERROR'">本次导出失败：{{ checkRow.newExcelReportOpt.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>

    <!-- 表单-查看有效服务类型 -->
    <el-dialog title="有效服务类型" :visible.sync="taskTypedialog" width="50%" center :before-close="handleClose">
      <div>
        <ul>
          <li v-for="(item, index) in taskTypes" :key="index">{{ item.code }}：{{ item.label }}</li>
        </ul>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="taskTypedialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {missionCenterData} from '@/const/crud/missionCenter';
import {
  getPageTasklist,
  taskExportNbqybg,
  taskExportExcelNbqybg,
  taskExportNbqybgInfo,
  selectScore,
  saveAndUpdateWmTask,
  saveAndUpdateWmReport,
  taskNewExportNbqybg,
  taskExportNewExcelNbqybg
} from '@/api/taskManagement/missionCenter';
import {selectByScorePackageId} from '@/api/task/taskType';
import {plist} from '@/const/crud/taskTypeTree/index';
export default {
  name: 'points',
  data() {
    return {
      searchFormTask: {},
      reportForm: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      tableDataTask: [],
      option: missionCenterData,
      wordLoading: false,
      excelLoading: false,
      newWordLoading: false,
      newExcelLoading: false,
      tableLoadingTask: false,
      taskExportLoading: false,
      taskExportInfoLoading: false,
      notUse: true,
      showReport: false,
      exportDig: false,
      checkRow: '', // 导出选中值
      reportVal: {},
      taskTypedialog: false,
      taskTypes: '',
      approValnot: false,
      reportNot: false
    };
  },
  components: {},
  mounted() {},
  computed: {},

  methods: {
    getListTask(page, params) {
      this.tableLoadingTask = true;
      getPageTasklist(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchFormTask
        )
      )
        .then(response => {
          this.tableDataTask = response.data.data.records;

          for (let i = 0; i < this.tableDataTask.length; i++) {
            this.tableDataTask[i].ywctt = parseInt(this.tableDataTask[i].ysh) - parseInt(this.tableDataTask[i].ytjtt);
          }

          this.page.total = response.data.data.total;
          this.tableLoadingTask = false;
        })
        .catch(() => {
          this.tableLoadingTask = false;
        });
    },
    // 搜索按钮
    searchVal(form, done) {
      this.searchFormTask = form;
      this.page.currentPage = 1;
      this.getListTask(this.page, form);
      done();
    },
    // 生成报告按钮-展示
    generateBtn(row) {
      this.reportVal = row;
      let arg = {
        scorePackageId: row.id
      };
      selectScore(arg)
        .then(response => {
          if (response.data.data == 0) {
            this.approValnot = true;
            this.reportNot = true;
            this.$message.error('没有可生成报告的服务');
          } else {
            this.showReport = true;
            this.approValnot = false;
            this.reportNot = false;
          }
          this.reportForm = response.data.data == 0 ? {} : response.data.data;
        })
        .catch(() => {
          this.$message.error('请求异常');
        });
    },

    // 生成报告并提交按钮-提交
    generateApproval() {
      let arg = {
        scorePackageId: this.reportVal.id,
        taskStatus: 3
      };
      saveAndUpdateWmReport(arg)
        .then(response => {
          console.log('response', response);
          if (response.data.code === 0) {
            this.$message.success('提交成功');
            this.showReport = false;
            this.getListTask(this.page, form);
          }
        })
        .catch(() => {
          // this.$message.error('请求异常')
        });
    },
    // 生成按钮-提交
    generateReport() {
      let arg = {
        scorePackageId: this.reportVal.id,
        taskStatus: 3
      };
      saveAndUpdateWmTask(arg)
        .then(response => {
          this.$message.success('提交成功');
          this.showReport = false;
          this.getListTask(this.page, form);
        })
        .catch(() => {
          // this.$message.error('请求异常')
        });
    },
    // 查看按钮
    lookBtn(row) {
      this.$router.push({
        path: '/admin/taskManagement/missionLook?packageId=' + row.id
      });
    },
    // 导出按钮
    exportBtn(row) {
      this.exportDig = true;
      this.checkRow = row;
    },
    async taskExport(type) {
      let row = this.checkRow;
      var obj = {
        id: row.id
      };
      let res;
      if (type === 'word') {
        this.wordLoading = true;
        res = await taskExportNbqybg(obj);
      } else if (type === 'excel') {
        this.excelLoading = true;
        res = await taskExportExcelNbqybg(obj);
      }
      if (res.data) {
        this.$message.success(res.data.data);
        this.exportDig = false;
        this.getListTask(this.page);
        this.wordLoading = false;
        this.excelLoading = false;
      } else {
        this.$message.error('导出失败');
      }
    },
    async taskNewExport(type) {
      try {
        let row = this.checkRow;
        var obj = {
          id: row.id
        };
        let res;
        if (type === 'word') {
          this.newWordLoading = true;
          res = await taskNewExportNbqybg(obj);
        } else if (type === 'excel') {
          this.newExcelLoading = true;
          res = await taskExportNewExcelNbqybg(obj);
        }
        if (res.data) {
          this.$message.success(res.data.data);
          this.exportDig = false;
          this.getListTask(this.page);
        } else {
          this.$message.error('导出失败');
        }
        this.newWordLoading = false;
        this.newExcelLoading = false;
      } catch (err) {
        this.newWordLoading = false;
        this.newExcelLoading = false;
      }
    },

    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.exportDig = false;
    },
    // 下载新版报告
    downloadNewTask(type) {
      let latestUrl;
      if (type === 'word') {
        latestUrl = this.checkRow.newReportOpt.latestUrl;
      } else if (type === 'excel') {
        latestUrl = this.checkRow.newExcelReportOpt.latestUrl;
      }
      let a = document.createElement('a');
      a.href = latestUrl;
      a.click();
      this.$message.success('导出汇总报告成功');
      this.exportDig = false;
    },
    // taskExportInfo() {
    //   this.taskExportInfoLoading = true;
    //   let row = this.checkRow;
    //   var obj = {
    //     scorePackageId: row.id
    //   };
    //   taskExportNbqybgInfo(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.$message.success('导出报告详情成功')
    //     this.taskExportInfoLoading=false;
    //   }).catch(() => {
    //     this.taskExportInfoLoading = false;
    //   })
    // },
    // 表格-查看有效服务类型
    viewDetail(row) {
      // this.taskTypes = row.taskTypes == null ? "无" : row.taskTypes;
      // this.taskTypedialog = true;
      selectByScorePackageId({id: row.id}).then(response => {
        this.taskTypes = response.data.data;
        this.taskTypes.forEach(item => {
          item.code = plist[item.code];
        });
        this.taskTypedialog = true;
      });
    },
    // 有效服务类型取消
    cancelBtn() {
      this.taskTypedialog = false;
    },
    // 取消按钮
    handleClose() {
      this.showReport = false;
      this.exportDig = false;
      this.taskTypedialog = false;
    },
    // 条数发生改变
    sizeChange(row) {
      this.page.pageSize = row;
    },
    // 页数发生改变
    currentChange(row) {
      this.page.currentPage = row;
    },
    // 导出确认按钮
    exportSure() {},
    // 导出取消按钮
    exportCancle() {}
  }
};
</script>
<style lang="scss" scoped>
.down-item {
  margin-left: 20px;
  margin-bottom: 15px;
  span {
    display: inline-block;
    text-align: right;
  }
  .btn {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .first {
    width: 240px;
  }
}
</style>
<style>
.tabStyle {
  width: 100%;
  margin-top: 10px;
}
.el-input__inner {
  border: 1px solid #dcdfe6 !important;
}

.generating {
  color: #1e90ff;
  text-align: center;
  display: block;
}

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

.title-msg {
  text-align: center;
  margin-top: 10px;
}
</style>
