<template>
  <div
      id="invoice_export"
      v-loading="loading"
      element-loading-text="拼命加载中......请稍等"
  >
    <el-card>
      <el-form label-position="top" style="width: 100%">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="发票种类：">
              <el-select
                  v-model="invoiceExport.invoiceCategory"
                  placeholder="请选择"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in invoiceCategoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="起始日期：">
              <el-date-picker
                  v-model="invoiceExport.beginDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="结束日期：">
              <el-date-picker
                  v-model="invoiceExport.endDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
                            <span slot="label" style="color: #909399">
                                <i class="el-icon-info"></i>
                                <span
                                >&nbsp;&nbsp;选择日期时间越长，发票明细导出耗时越久！</span
                                >
                            </span>
              <el-button
                  @click="handleStartInvoiceExport"
                  type="primary"
                  icon="el-icon-arrow-right"
              >开始导出任务
              </el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <br/>
    <el-card>
      <div slot="header">
        <span>导出任务列表</span>
      </div>
      <el-form label-position="top" style="width: 100%">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="发票种类：">
              <el-select
                  v-model="search.invoiceCategory"
                  placeholder="请选择"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in invoiceCategoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="起始日期：">
              <el-date-picker
                  v-model="search.beginDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="结束日期：">
              <el-date-picker
                  v-model="search.endDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <span slot="label">&nbsp;</span>
              <el-button
                  @click="handleSearch"
                  type="primary"
                  icon="el-icon-search"
              >刷新
              </el-button
              >
              <el-button @click="handleResetSearch"
              >重置
              </el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-container>
        <el-table
            :data="search.resultList"
            border
            stripe
            height="550px"
            style="width: 100%"
        >
          <el-table-column
              type="index"
              :index="pageIndex"
              align="center"
              label="序号"
              width="50"
          ></el-table-column>
          <el-table-column
              prop="invoiceCategory"
              label="发票种类"
              width="160"
              align="center"
              :formatter="fmtInvoiceCategory"
          ></el-table-column>
          <el-table-column
              prop="beginDate"
              label="开票起始时间"
              width="160"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="endDate"
              label="开票截止时间"
              width="160"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="statusMemo"
              label="状态"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="statusChangeTime"
              label="状态改变时间"
              width="160"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="createTime"
              label="创建时间"
              width="160"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              label="操作"
              width="180"
              align="center"
              fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                  @click="handleDownloadFile(scope.row)"
                  :disabled="
                                    handleDownloadFileDisabled(scope.row)
                                "
                  type="primary"
              >文件下载
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-container>
      <br/>
      <el-row type="flex" :gutter="20">
        <el-col :span="12"></el-col>
        <el-col :span="12">
          <div style="text-align: right">
            <el-pagination
                layout="total, sizes, prev, pager, next"
                :current-page="search.resultPagination.currentPage"
                :page-sizes="search.resultPagination.pageSizes"
                :page-size="search.resultPagination.pageSize"
                :total="search.resultPagination.total"
                @size-change="handleSearchResultSizeChange"
                @current-change="handleSearchResultCurrentChange"
            ></el-pagination>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
        :show-close="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="400px"
        :visible.sync="exporting.dialogVisible"
        @opened="handleExportingDialogOpened"
        @closed="handleExportingDialogClosed"
    >
      <div
          v-loading="exporting.loading"
          element-loading-text="文件生成中......请稍等"
          style="height: 40px"
      ></div>
      <span slot="footer">
                <span>&nbsp;</span>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  invoiceExportCommit,
  invoiceExportRecords,
  invoiceExportRecordStatus,
} from '@/api/invoice_export'

import DateHelper from '@/utils/date'
import cache from '@/utils/cache'

// 发票种类列表
const invoiceCategoryOptions = [
  {
    value: 1,
    label: '增值税普通电子发票',
  },
  {
    value: 2,
    label: '增值税电子专用发票',
  },
  {
    value: 3,
    label: '增值税普通纸质发票',
  },
  {
    value: 4,
    label: '增值税专用纸质发票',
  },
]

/**
 * 获取发票种类文本；
 * @param {Number} intKey 发票类别的数字标识
 */
function GetInvoiceCategoryLabel(intKey) {
  let result = intKey
  for (const item of invoiceCategoryOptions) {
    if (item.value === intKey) {
      result = item.label
      break
    }
  }
  return result
}

export default {
  name: 'invoice_export',
  data() {
    return {
      loading: false,
      invoiceCategoryOptions: invoiceCategoryOptions,
      invoiceExport: {
        invoiceCategory: '',
        beginDate: DateHelper.LocalCurrentMonthStart(),
        endDate: DateHelper.LocalCurrentMonthEnd(),
      },
      search: {
        invoiceCategory: '',
        beginDate: DateHelper.LocalCurrentMonthStart(),
        endDate: DateHelper.LocalCurrentMonthEnd(),
        resultList: [],
        resultPagination: {
          currentPage: 1,
          pageSizes: [10, 30, 50, 100],
          pageSize: 10,
          total: 0,
        },
      },
      exporting: {
        dialogVisible: false,
        loading: false,
        recordId: '', // 同步记录主键id，用于查询导出文件生成状态
      },
    }
  },
  created() {
    this.callInvoiceExportRecords(
        this.search.resultPagination.currentPage,
        this.search.resultPagination.pageSize
    )
  },
  methods: {
    pageIndex(index) {
      let currentPage = this.search.resultPagination.currentPage //当前页码，具体看组件取值
      let pageSize = this.search.resultPagination.pageSize //每页条数，具体是组件取值
      return index + 1 + (currentPage - 1) * pageSize
    },
    fmtInvoiceCategory(row, column, cellValue) {
      return GetInvoiceCategoryLabel(cellValue)
    },
    // 开始发票导出
    handleStartInvoiceExport() {
      // 验证发票种类输入
      let invoiceCategory = this.invoiceExport.invoiceCategory
      if (
          invoiceCategory === null ||
          invoiceCategory === '' ||
          invoiceCategory === undefined
      ) {
        this.$message.error('请选择导出发票明细时使用发票种类！')
        return false
      }
      let beginTime = this.invoiceExport.beginDate
      let endTime = this.invoiceExport.endDate
      if (beginTime) {
        beginTime = this.dateFormat(
            new Date(beginTime),
            'yyyy-MM-dd HH:mm:ss'
        )
      }
      if (endTime) {
        let endTimeObj = new Date(endTime)
        endTime = this.dateFormat(
            new Date(
                endTimeObj.getFullYear(),
                endTimeObj.getMonth(),
                endTimeObj.getDate(),
                '23',
                '59',
                '59'
            ),
            'yyyy-MM-dd HH:mm:ss'
        )
      }
      if (beginTime && endTime) {
        if (DateHelper.ValidateDateRange(beginTime, endTime) == false) {
          this.$message.error(
              '起始日期与结束日期不合法，请确定后重试！'
          )
          return false
        }
      } else {
        this.$message.error(
            '起始日期与结束日期为必输项，请确定后重试！'
        )
        return false
      }

      let _this = this
      _this.loading = true
      invoiceExportCommit({
        exportType: 1,
        invoiceCategory: _this.invoiceExport.invoiceCategory,
        beginDate: beginTime,
        endDate: endTime
      })
          .then((val) => {
            _this.exporting.recordId = val.data.recordId
            _this.loading = false
            _this.exporting.dialogVisible = true
            _this.$message.success(
                '您的导出任务已创建，请刷新“导出任务列表”查看导出结果'
            )
          })
          .catch((err) => {
            _this.$message.error(err)
            _this.loading = false
          })

      // 根据票种查询导出任务
      // invoiceExportRecords({
      //     invoiceCategory: this.search.invoiceCategory,
      // })
      //     .then((val) => {
      //         // 相同票种不能多次创建导出任务
      //         if (val.data.records && val.data.records.length > 0) {
      //             let row = val.data.records[0];
      //             // 任务执行中
      //             if (row.status == 1) {
      //             }
      //             let msg = `您有同条件导出任务于 ${row.createTime} 创建并执行中，请在 导出任务列表 中查看执行进度`;
      //             _this.loading = false;
      //             _this.$message.error(msg);
      //             return false;
      //         }
      //     })
      //     .catch((err) => {
      //         _this.$message.error(err);
      //         _this.loading = false;
      //     });
    },
    // 导出任务列表查询
    handleSearch() {
      this.callInvoiceExportRecords(
          1,
          this.search.resultPagination.pageSize
      )
    },
    // 导出任务列表重置
    handleResetSearch() {
      this.search.invoiceCategory = ''
      this.search.beginDate = ''
      this.search.endDate = ''
    },
    handleSearchResultSizeChange(val) {
      this.callInvoiceExportRecords(1, val)
    },
    handleSearchResultCurrentChange(val) {
      this.callInvoiceExportRecords(
          val,
          this.search.resultPagination.pageSize
      )
    },
    // 调用分页查询发票导出记录接口
    callInvoiceExportRecords(pageNum, pageSize) {
      this.loading = true
      let _this = this
      this.callInvoiceExportRecordsTask(pageNum, pageSize)
          .then((val) => {
            _this.search.resultPagination.total = val.data.total
            _this.search.resultPagination.pageSize = val.data.size
            _this.search.resultPagination.currentPage =
                val.data.current
            _this.search.resultList = val.data.records
            _this.loading = false
          })
          .catch((err) => {
            _this.$message.error(err)
            _this.loading = false
          })
    },
    // 调用分分页查询发票导出记录接口 任务
    callInvoiceExportRecordsTask(pageNum, pageSize) {
      let beginTime = this.search.beginDate
      let endTime = this.search.endDate
      if (beginTime) {
        beginTime = this.dateFormat(
            new Date(beginTime),
            'yyyy-MM-dd HH:mm:ss'
        )
      }
      if (endTime) {
        let endTimeObj = new Date(endTime)
        endTime = this.dateFormat(
            new Date(
                endTimeObj.getFullYear(),
                endTimeObj.getMonth(),
                endTimeObj.getDate(),
                '23',
                '59',
                '59'
            ),
            'yyyy-MM-dd HH:mm:ss'
        )
      }
      if (beginTime && endTime) {
        if (DateHelper.ValidateDateRange(beginTime, endTime) == false) {
          return Promise.reject(
              '起始日期与结束日期不合法，请确定后重试！'
          )
        }
      }
      return invoiceExportRecords({
        exportType: 1,
        invoiceCategory: this.search.invoiceCategory,
        createTimeBegin: beginTime,
        createTimeEnd: endTime,
        pageNum: pageNum,
        pageSize: pageSize,
      })
    },
    // 发票导出中对话框打开结束时的回调
    handleExportingDialogOpened() {
      // 开始等待
      this.exporting.loading = true
      // 三秒后执行发票修复进度查询
      let _this = this
      setTimeout(function () {
        _this.callInvoiceExportRecordStatus()
      }, 10000)
    },
    // 发票导出中对话框关闭结束时的回调
    handleExportingDialogClosed() {
      this.exporting.recordId = ''
      this.exporting.loading = false
      // 刷新导出任务列表
      this.callInvoiceExportRecords(
          1,
          this.search.resultPagination.pageSize
      )
    },
    // 调用查询发票导出状态接口
    callInvoiceExportRecordStatus() {
      let _this = this
      invoiceExportRecordStatus(this.exporting.recordId)
          .then((val) => {
            if (val.data) {
              // status => 1：进行中  2：结束
              if (val.data.status == 1) {
                // 三秒后执行发票修复进度查询
                setTimeout(function () {
                  _this.callInvoiceExportRecordStatus()
                }, 10000)
              } else if (val.data.status == 2) {
                _this.$message.success(val.msg)
                _this.exporting.dialogVisible = false
              } else {
                _this.$message.error(
                    '文件生成状态未知，终止等待！'
                )
                _this.exporting.dialogVisible = false
              }
            } else {
              _this.$message.error('无状态信息，终止等待！')
              _this.exporting.dialogVisible = false
            }
          })
          .catch((err) => {
            _this.$message.error(err)
            _this.exporting.dialogVisible = false
          })
    },
    // 下载文件功能是否可用；
    handleDownloadFileDisabled(row) {
      return row && row.status == 2 ? false : true
    },
    // 下载文件
    handleDownloadFile(row) {
      let invalidMsg = '文件下载链接无效！'
      let _this = this
      // let download = function (url) {
      //     _this
      //         .isRunUrl(url)
      //         .then((val) => {
      //             let a = document.createElement("a");
      //             a.href = url;
      //             a.target = "_blank";
      //             a.click();
      //         })
      //         .catch((err) => {
      //             _this.$message.error(invalidMsg);
      //         });
      // };
      if (row) {
        let url = row.fileUrl
        if (url === null || url === '' || url === undefined) {
          _this.$message.error(invalidMsg)
        } else {
          console.log('下载链接：')
          console.log(url)
          // download(url);
          window.open(url)
        }
      } else {
        console.log('无操作数据！')
      }
    },
    // isRunUrl(url) {
    //     return new Promise(function (resolve, reject) {
    //         // 测试链接连通性, 主要检测404错误
    //         // 由于AJAX通常无法区分404和跨域问题
    //         // 所以只能用script 或者 link标签
    //         // link比script更容易捕获错误
    //         var dom = document.createElement("link");
    //         dom.href = url;
    //         dom.rel = "stylesheet";
    //         document.head.appendChild(dom);
    //         dom.onload = function () {
    //             document.head.removeChild(dom);
    //             resolve();
    //         };
    //         dom.onerror = reject;
    //     });
    // },
    dateFormat(date, fmt) {
      // 小时只支持24小时制
      var o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'H+': date.getHours(), // 24小时,
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      }
      for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                  ? o[k]
                  : ('00' + o[k]).substr(('' + o[k]).length)
          )
        }
      }
      return fmt
    },
  },
}
</script>

<style scoped>
</style>
