<template>
  <div id="files_import" class="body" v-loading="load" element-loading-text="文件上传中，请稍等">
    <div class="search">
      <div style="margin-right: 5px">
        <el-input
            v-model="fileName"
            clearable
            prefix-icon="el-icon-search"
            placeholder="请输入文件名称"
            class="file_input">
        </el-input>
      </div>
      <div style="margin-right: 5px">
        <el-date-picker
            v-model="fileDateTime"
            type="datetimerange"
            unlink-panels
            align="right"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </div>
      <div style="margin-right: 5px">
        <el-select v-model="fileStatus" placeholder="请选择文件处理状态">
          <el-option
              v-for="item in fileStatusData"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div>
        <el-button v-on:click="searchData" type="primary">搜索</el-button>
      </div>
    </div>
    <div class="file_import">
      <div class="flex: 1">
        <input ref="uploadExcel-input" style="display: none" type="file" accept=".xlsx, .xls"
               @change="excelFileChange">
        <el-button :loading="importLoading" type="primary" v-on:click="selectExcelFile"
                   style="margin-right: 5px">{{ $t('excel.import') }} Excel
        </el-button>
        <el-button type="primary" v-on:click="templateDownload"
                   style="margin-right: 5px">模版下载
        </el-button>
      </div>
    </div>
    <div>
      <el-table :data="invoiceFilesList" border style="width: 100%" :height="tableHeight">
        <el-table-column prop="entName" label="企业名称" width="160"></el-table-column>
        <el-table-column prop="entTaxId" label="企业税号" width="160"></el-table-column>
        <el-table-column prop="fileName" label="文件名" width="320"></el-table-column>
        <el-table-column prop="status" label="文件处理状态" width="100" :formatter="getFileStatus"></el-table-column>
        <el-table-column prop="successCnt" label="提交成功数" width="90"></el-table-column>
        <el-table-column prop="failCnt" label="提交失败数" width="90"></el-table-column>
        <el-table-column prop="operatorName" label="操作人员名称" width="100"></el-table-column>
        <el-table-column prop="operatorMobile" label="操作人员手机号" width="120"></el-table-column>
        <el-table-column prop="createTime" label="上传文件时间" width="140"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button v-on:click="seeDetails(scope.row)" type="primary" size="small" style="margin: 5px">发票开具
            </el-button>
            <el-button v-on:click="downloadFiles(scope.row)" type="primary" size="small" style="margin: 5px">下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-row type="flex" :gutter="20">
        <el-col :span="12"></el-col>
        <el-col :span="12">
          <div style="text-align:right">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="pageSizes"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next"
                :total="totalNumber"
            >
            </el-pagination>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import {AxiosRequestData, AxiosRequestFile} from '../../data/axios_request'
import cache from '@/utils/cache'
import {networkUrl} from '../../data/global_configuration'

export default {
  name: 'files_import',
  data() {
    return {
      importLoading: false,
      load: false,
      taxIncluded: '含税',
      invoiceFilesList: [],
      pageSizes: [10, 30, 50, 100],
      pageNum: 1,
      pageSize: 10,
      totalNumber: 0,
      totalPage: 0,
      account: '',
      entTaxId: '',
      token: '',
      fileName: '',
      fileStatusData: [{
        value: '',
        label: '全部'
      }, {
        value: '1',
        label: '文件处理中'
      }, {
        value: '2',
        label: '文件处理失败'
      }, {
        value: '3',
        label: '文件处理成功'
      }],
      fileDateTime: '',
      fileStatus: '',
      beginTime: '',
      endTime: '',
      tableHeight: ''
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 250
    this.account = JSON.parse(cache.getSession("user")).account;
    this.entTaxId = JSON.parse(cache.getSession('company')).entTaxId;
    this.token = cache.getToken();
    this.getFilesList()
  },
  mounted() {
    this.tableHeight = window.innerHeight - 250
    window.onresize = () => {
      return (() => {
        this.tableHeight = window.innerHeight - 250
      })()
    }
  },
  methods: {
    //变更每页显示的数据条数
    handleSizeChange(val) {
      this.pageSize = val
      this.getFilesList()
    },
    //翻页
    handleCurrentChange(val) {
      this.pageNum = val
      this.getFilesList()
    },
    //获取文件处理状态
    getFileStatus(row, column, cellValue) {
      if (cellValue == 1) {
        return '文件处理中'
      }
      if (cellValue == 2) {
        return '文件处理失败'
      }
      if (cellValue == 3) {
        return '文件处理成功'
      } else {
        return ''
      }
    },
    //Excel导入
    selectExcelFile() {
      this.$refs['uploadExcel-input'].click()
    },
    //读取Excel文件
    excelFileChange(ev) {
      this.load = true
      this.importLoading = true
      const files = ev.target.files
      const file = files[0]
      this.uploadFile(file)
    },
    //文件上传
    async uploadFile(file) {
      if (this.token && this.account) {
        const data = new FormData();
        data.append('mobile', this.account);
        data.append('entTaxId', this.entTaxId);
        data.append('batchFile', file);
        let res = await AxiosRequestFile('/sys/batchInvoice/save', this.token, data)
        if (res) {
          if (res.code == 0) {
            this.importLoading = false
            this.load = false
            this.$message({
              message: '文件上传成功！',
              type: 'success'
            });
            await this.getFilesList()
          } else {
            this.$message.error('文件上传失败！')
          }
        } else {
          this.$message.error('文件上传失败！')
        }
      }
    },
    //查看开票列表
    seeDetails(row) {
      this.$router.push({name: 'batch_invoice', params: {key: row.batchId.toString()}})
    },
    //获取上传文件列表
    async getFilesList() {
      if (this.token) {
        const url = "/sys/batchInvoice/findPageBatchs";
        let response = await AxiosRequestData(url, this.token, {
          entTaxId: this.entTaxId,
          fileName: this.fileName,
          status: this.fileStatus,
          uploadDateBegin: this.beginTime,
          uploadDateEnd: this.endTime,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
        }, false, 2);
        if (response) {
          if (response.code == 0) {
            this.totalNumber = response.data.total;
            this.totalPage = response.data.pages;
            this.invoiceFilesList = response.data.records
          }
        }
      }
    },
    // 查询数据
    searchData() {
      if (this.fileDateTime != null && this.fileDateTime.length > 0) {
        this.beginTime = this.fileDateTime[0]
        this.endTime = this.fileDateTime[1]
      }
      this.getFilesList()
    },
    // 文件下载
    downloadFiles(row) {
      window.open(row.fileUrl)
    },
    // 导入Excel模版下载
    templateDownload() {
      let url = networkUrl()
      window.location.href = url + '/ext/blue_invoice_template.xlsx'
    }
  }
}
</script>

<style scoped>
.body {
  flex: 1;
}

.search {
  display: flex;
  margin: 5px;
}

.file_input {
  width: 250px;
}

.file_import {
  margin: 5px;
}
</style>
