<template>
  <div class="app-container">
    <button-bar ref="btnbar" view-title="库存信息" :btndisabled="btndisabled" @btnhandle="btnHandle" />
    <div class="main-content">
      <div class="searchcon">
        <el-button size="small" class="searchbtn" @click="clicksearchShow">{{ searchxianshitit }}</el-button>
        <div v-show="isSearchShow" class="search">
          <el-form :inline="true" :model="queryParams" class="tab-header">
            <el-form-item label="数据日期">
              <el-date-picker v-model="queryParams.params.dataDateStart" type="date" clearable value-format="yyyy-MM-dd" placeholder="选择数据开始日期" />
              <span style="padding: 0 8px">至</span>
              <el-date-picker v-model="queryParams.params.dataDateEnd" type="date" clearable value-format="yyyy-MM-dd" placeholder="选择数据结束日期" />
            </el-form-item>
          </el-form>
          <div class="btn" style="text-align: center;">
            <el-button type="primary" size="small" icon="el-icon-search" @click="dosearch">查询</el-button>
            <el-button type="primary" size="small" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </div>
      <!-- Start 项目列表头部 -->
      <div class="listtop">
        <div class="tit" />
        <pageye v-show="dataList.length > 0" :total="queryParams.total" :page.sync="queryParams.current" :limit.sync="queryParams.size" class="pagination" @pagination="loadList" />
      </div>
      <!-- End 项目列表头部 -->
      <!-- Start 项目列表 -->
      <div class="">
        <el-table v-loading="tableLoading" :data="dataList" border style="width: 100%">
          <el-table-column fixed width="60" label="序号" type="index" :index="indexMethod" align="center" />
          <el-table-column prop="orderDate" label="数据日期" align="center" width="200" />
          <el-table-column prop="createTime" label="导入时间" align="center" width="200" />
          <el-table-column prop="allNum" label="总记录数" align="center" width="200" />
          <el-table-column prop="validNum" label="普通商品数" align="center" width="200" />
          <el-table-column prop="errRowNum" label="烟草商品数" align="center" width="200" />
          <el-table-column label="操作" wid align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.state==1"><el-tag type="info">正在导入数据库...</el-tag><el-button
                type="text"
                icon="el-icon-refresh"
                style="margin-left: 5px;"
                @click="loadList()"
              >刷新</el-button></div>
              <div v-else-if="scope.row.state==2"><el-tag type="warning">正在创建报表...</el-tag><el-button
                type="text"
                icon="el-icon-refresh"
                style="margin-left: 5px;"
                @click="loadList()"
              >刷新</el-button></div>
              <div v-else-if="scope.row.state==3"><el-tag type="success">正在生成Excel...</el-tag><el-button
                type="text"
                icon="el-icon-refresh"
                style="margin-left: 5px;"
                @click="loadList()"
              >刷新</el-button></div>
              <div v-else-if="scope.row.state==4&&scope.row.fileUrl.length>1">
                <el-button type="text" @click="toDownload(scope.row)">下载库存日报表</el-button>
                <!--                <el-button type="text" @click="toDownloadKchz(scope.row)">下载门店商品总表</el-button>
                <el-button type="text" @click="toDownloadKchzfb(scope.row)">下载门店商品分表压缩包</el-button> -->
              </div>
              <div v-else>没有报表文件</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- End 项目列表 -->
      <div class="pages">
        <div class="tit" />
        <!--  翻页  -->
        <pagination
          v-show="dataList.length > 0"
          :total="queryParams.total"
          :page.sync="queryParams.current"
          :limit.sync="queryParams.size"
          class="pagination"
          @pagination="loadList"
        />
      </div>
    </div>
    <el-dialog title="上传《库存信息查询.xlsx》" :visible.sync="dialogVisible" width="60%" :before-close="dialogClose">
      <el-card class="box-card">
        <div>
          <el-upload
            ref="upload"
            class="upload-demo"
            :action="updateAction"
            :on-progress="handleProgress"
            :on-success="handleSuccess"
            :file-list="fileList"
            :auto-upload="false"
            :multiple="false"
            :limit="1"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">上传 《库存信息查询.xlsx》文件</div>
          </el-upload>
        </div>
        <div>
          <h3>文件上传结果</h3>
          <el-card class="box-card">
            <div>{{ uploadResultMesssage }}</div>
          </el-card>
        </div>
        <div>
          <h3>库存汇总数据</h3>
          <el-card class="box-card">
            <div>{{ hzResultMesssage }}</div>
            <div>
              <el-button :disabled="!hzFilePath" size="small" type="primary" @click="doDownloadHz">下载库存汇总文件</el-button>
              <!-- <el-button :disabled="!ychzFilePath" size="small" type="primary" @click="doDownloadHzYc">下载烟草汇总文件</el-button> -->
            </div>
          </el-card>
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
  import ButtonBar from '@/components/ButtonBar'
  import Pagination from '@/components/pagination'
  import pageye from '@/components/pagination/pageye'
  import req from '@/api/supervise/gdinventorylog'

  export default {
    name: 'DaydatauploadGdinventoryLog',
    components: {
      ButtonBar,
      Pagination,
      pageye
    },
    data() {
      return {
        btndisabled: false,
        viewState: 1, // 1、列表 2、添加 3、修改 4、查看
        isSearchShow: false,
        searchxianshitit: '显示查询条件',
        queryParams: {
          current: 1,
          size: 10,
          total: 0,
          params: {
            dataDateStart: '',
            dataDateEnd: ''
          }
        },
        tableLoading: false,
        dataList: [],
        btnList: [{
            type: 'primary',
            size: 'small',
            icon: 'upload',
            btnKey: 'showUploadXlsx',
            btnLabel: '上传库存信息'
          },
          {
            type: 'info',
            size: 'small',
            icon: 'cross',
            btnKey: 'doClose',
            btnLabel: '关闭'
          }
        ],
        dialogVisible: false,
        updateAction: '/api/customer' + '/v1/gdinventoryok/uploadGdData',
        name: '库存数据导入',
        fileList: [],
        uploadResultMesssage: '',
        hzResultMesssage: '',
        hzFilePath: '',
        ychzFilePath: '',
        fullscreenloading: null
      }
    },
    mounted() {
      this.$refs['btnbar'].setButtonList(this.btnList)
    },
    created() {
      this.loadList()
    },
    methods: {
      // 搜索条件效果
      clicksearchShow() {
        this.isSearchShow = !this.isSearchShow
        if (this.isSearchShow) {
          this.searchxianshitit = '隐藏查询条件'
        } else {
          this.searchxianshitit = '显示查询条件'
        }
      },
      btnHandle(btnKey) {
        switch (btnKey) {
          case 'showUploadXlsx':
            this.showUploadXlsx()
            break
          case 'doClose':
            this.doClose()
            break
          default:
            break
        }
      },
      dosearch() {
        this.queryParams.current = 1
        this.loadList()
      },
      resetQuery() {
        this.queryParams = {
          current: 1,
          size: 10,
          total: 0,
          params: {
            dataDateStart: '',
            dataDateEnd: ''
          }
        }
        this.loadList()
      },
      // 序号
      indexMethod(index) {
        var pagestart = (this.queryParams.current - 1) * this.queryParams.size
        var pageindex = index + 1 + pagestart
        return pageindex
      },
      loadList() {
        req.listPage(this.queryParams).then(res => {
          this.queryParams.total = res.data.total
          this.dataList = res.data.records
        }).catch(e => {
          console.log('GdinventoryLog-loadList-ee:', e)
        })
      },
      doClose() {
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.go(-1)
      },
      showUploadXlsx() {
        this.dialogVisible = true
      },
      dialogClose() {
        this.currentLog = {}
        this.fileList = []
        this.filecandown = true
        this.dialogVisible = false
      },
      // 返回
      handleReturn() {
        this.$router.go(-1)
      },
      submitUpload() {
        this.$refs.upload.submit()
      },
      handleProgress(event, file, fileList) {
        const _this = this
        this.fullscreenloading = this.$loading({
          lock: true,
          text: '文件正在上传',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        console.log('111', event.percent)
        if (event.percent >= 100) {
          _this.fullscreenloading.text = '上传完成，正在导入数据库'
        }
      },
      handleSuccess(resp, file, fileList) {
        // if (this.fullscreenloading) this.fullscreenloading.close()
        // this.fullscreenloading = null
        console.log('222', resp)
        const rdata = resp.data
        const _this = this
        if (this.fullscreenloading) this.fullscreenloading.close()
        this.fullscreenloading = null
        _this.uploadResultMesssage = '文件上传完成，正在进行数据整理~'
        _this.loadList()
        setTimeout(function() {
          _this.dialogClose()
        }, 3000)
        // _this.fullscreenloading.text = '数据导入完成，正在生成报表~'
        // this.fileList = []
        // _this.uploadResultMesssage = '共导入数据：' + rdata.allNum + ' 条；普通商品数据：' + rdata.validNum + ' 条；烟草商品数据：' + rdata.errRowNum + ' 条；用时：' + rdata.durations + ' 毫秒。'
        // const param = {
        //   orderDate: rdata.orderDate
        // }
        // req.kcReport(param)
        //   .then(res => {
        //     console.log('333', res)
        //     _this.fullscreenloading.text = '报表数据完成，创建Excel文件'

        //     req.kcExcel({ logid: rdata.id })
        //       .then(res => {
        //         if (this.fullscreenloading) this.fullscreenloading.close()
        //         this.fullscreenloading = null
        //         console.log('444', res)
        //         _this.hzFilePath = res.data.fileUrl
        //       })
        //       .catch(e => {
        //         if (this.fullscreenloading) this.fullscreenloading.close()
        //         this.fullscreenloading = null
        //       })
        //   })
        //   .catch(e => {
        //     if (this.fullscreenloading) this.fullscreenloading.close()
        //     this.fullscreenloading = null
        //   })
      },
      toDownload(row) {
        console.log('lll', row)
        if (row.fileUrl) {
          window.open(row.fileUrl, '_blank')
        }
      },
      toDownloadKchz(row) {
        const odate = row.orderDate
        console.log('222', odate)
        const tdate = odate.replaceAll('-', '')
        console.log('222-tt', tdate)
        const turl = 'https://supervise.yxtsoft.com/downfile/gd36524/门店商品库存' + tdate + '.xlsx'
        window.open(turl, '_blank')
      },
      toDownloadKchzfb(row) {
        const odate = row.orderDate
        console.log('333', odate)
        const tdate = odate.replaceAll('-', '')
        console.log('333-tt', tdate)
        const turl = 'https://supervise.yxtsoft.com/downfile/gd36524/门店商品库存' + tdate + '(分门店).zip'
        window.open(turl, '_blank')
      },
      doDownloadHz() {
        window.open(this.hzFilePath, '_blank')
        //   downloadhz({ filepath: this.hzFilePath })
        //     .then(res => {
        //       console.log('xxx', res)
        //       const blob = new Blob([res.data])
        //       const url = window.URL.createObjectURL(blob) // 创建 url 并指向 blob
        //       const a = document.createElement('a')
        //       a.href = url
        //       a.download = '导出数据.xlsx'
        //       a.click()
        //       window.URL.revokeObjectURL(url) // 释放该 ur
        //     })
        //     .catch(e => {
        //       console.log(e)
        //     })
      },
      doDownloadHzYc() {
        window.open(this.ychzFilePath, '_blank')
      }
    }
  }
</script>
<style scoped>
  .wenjiantit {
    font-size: 16px;
    font-weight: bold;
    margin: 25px 0 10px 0;
  }

  .forminfo {
    margin: 0;
    padding: 0;
  }

  .listcon {
    height: calc(100vh - 250px);
    overflow-y: auto;
    overflow-x: hidden;
  }
</style>

