<template>
  <div id="uploadlog">
    <div>
      <span style="font-weight: bold;font-size: 14px">文件生成日期：</span>
      <el-date-picker
        v-model="dataTime"
        type="date"
        placeholder="选择日期"
        size="small"
        @change="seachLogInfo"
      />
      <span style="font-weight: bold;font-size: 14px">上报对象：</span>
      <el-select v-model="uploadObjectId" size="small" @change="uploadObjectChange">
        <el-option
          v-for="item in uploadList"
          :key="item.id"
          :label="item.uploadObjectName"
          :value="item.id"
        />
      </el-select>
      <span style="font-weight: bold;font-size: 14px">文件类型：</span>
      <el-select v-model="uploadFileType" clearable size="small">
        <el-option
          v-for="item in FileTypeList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <span style="font-weight: bold;font-size: 14px">上报成功：</span>
      <el-select v-model="fileStatus" clearable size="small">
        <el-option
          v-for="item in fileStatusList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" icon="el-icon-search" size="small" @click="seachLogInfo">查询</el-button>
      <el-button type="primary" icon="el-icon-download" size="small" @click="exportDataEvent">导出</el-button>
      <el-button type="primary" icon="el-icon-info" size="small" @click="seachCache">查看缓存</el-button>
      <el-button type="primary" icon="el-icon-upload" size="small" @click="quickReport">一键补报</el-button>
    </div>

    <div style="padding-top: 15px">
      <vxe-table
        ref="sTable"
        align="center"
        :loading="loading"
        class="mytable-style"
        auto-resize
        border
        resizable
        export-config
        highlight-current-row
        show-overflow
        max-height="700"
        :data="tableData"
        :row-style="rowstyle"
      >
        <vxe-table-column title="文件上报日志">
          <vxe-table-column field="uploadObjectName" title="上报对象名称" width="10%"/>
          <vxe-table-column field="uploadObjectNo" title="上报对象编号" width="6%" />
          <vxe-table-column field="fileName" title="上报文件名称" width="18%" />
          <vxe-table-column field="fileTypeEnum" title="上报文件类型" :formatter="formatefileType" width="8%"/>
          <vxe-table-column :formatter="dateFormat" field="createTime" title="文件生成时间" width="150px" />
          <vxe-table-column field="backupA" title="文件补报时间" width="150px" />
          <vxe-table-column
            field="fileStatusEnum"
            title="上报文件状态"
            :filters="this.filterFileStatus"
            :filter-multiple="false"
            type="html"
            :formatter="formateStatus"
            width="150"
          />
          <vxe-table-column field="uploadProtocolEnum" title="上报协议" :formatter="formateProtocol" width="100"/>
          <vxe-table-column field="uploadCounter" title="上报次数" width="50">
            <template v-slot="{ row }">
              <span @click="getFileDetaile(row)">{{ row.uploadCounter }}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column width="100px" align="center" title="操作">
            <template v-slot="{ row }">
              <div v-if="row.fileStatusEnum === 'E4'">
                  <el-button
                    type="primary"
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-upload"
                    :loading="saveLoading"
                    @click="report(row)"
                  >
                    补报
                  </el-button>
              </div>
              <div v-else>
                <el-button
                  type="danger"
                  style="padding: 3px 4px 3px 4px;margin: 2px"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeEvent(row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </vxe-table-column>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager
        perfect
        :total="totalResult"
        :layouts="['Total']"
      />
    </div>
    <div>
      <vxe-modal v-model="logDetailShow" title="上报日志详细信息" width="800" resize destroy-on-close>
        <vxe-table
          ref="sTable"
          align="center"
          :loading="loading"
          auto-resize
          border
          resizable
          highlight-current-row
          show-overflow
          :data="detaileTable"
        >
          <vxe-table-column field="uploadTime" title="上报时间" :formatter="dateFormat" />
          <vxe-table-column field="fileStatusEnum" title="上报文件状态" :formatter="formateStatus" />
          <vxe-table-column field="uploadChannelName" title="上报通道" />
          <vxe-table-column field="uploadFailureReason" title="失败原因" />
        </vxe-table>
        <vxe-pager
          perfect
          :total="total"
          :layouts="['Total']"
        />
      </vxe-modal>
    </div>

    <div>
      <vxe-modal v-model="cacheShow" title="文件缓存信息" width="900" resize destroy-on-close>
        <vxe-table
          ref="xTable"
          align="center"
          auto-resize
          border
          resizable
          highlight-current-row
          show-overflow
          :data="cacheTable.slice((currentPage-1)*pageSize,currentPage*pageSize)"
        >
          <vxe-table-column field="uploadObjectName" title="上报对象名称" />
          <vxe-table-column field="fileName" title="上报文件名称" width="300" />
          <vxe-table-column field="fileTypeEnum" title="上报文件类型" :formatter="formatefileType" />
          <vxe-table-column
            field="fileStatusEnum"
            title="上报文件状态"
            :filters="this.filterFileStatus"
            :filter-multiple="false"
            type="html"
            :formatter="formateStatus"
          />
          <vxe-table-column field="uploadProtocolEnum" title="上报协议" :formatter="formateProtocol" />
        </vxe-table>
        <vxe-pager
          perfect
          :total="cacheTotal"
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
        />
      </vxe-modal>
    </div>
    <div>
      <vxe-modal v-model="feedbackShow" title="反馈信息" width="70%" height="500" resize destroy-on-close>
        <vxe-table
          ref="feedbackTable"
          align="center"
          auto-resize
          border
          resizable
          highlight-current-row
          show-overflow
          :data="feedbackTable"
        >
          <vxe-table-column field="fileName" title="反馈文件名称" width="350" />
          <vxe-table-column field="uploadTime" title="时间" :formatter="dateFormat" />
          <vxe-table-column
            field="feedbackFileStatusEnum.message"
            title="获取文件状态"
            :filters="this.feedbackFileStatusEnum"
            :filter-multiple="false"
          />
          <vxe-table-column field="uploadFailureReason" title="失败原因" />
        </vxe-table>
      </vxe-modal>
    </div>
  </div>
</template>

<script>

export default {
  name: 'Index',
  data() {
    return {
      quickReportData: [],
      uploadObjectId: '',
      uploadFileType: '',
      uploadList: [],
      detaileTable: [],
      uploadFileTypeList: [],
      FileTypeList: [],
      tableData: [],
      cacheTable: [],
      feedbackTable: [],
      provinceEnum: '',
      butDisabled: false,
      loading: false,
      saveLoading: false,
      logDetailShow: false,
      cacheShow: false,
      feedbackShow: false,
      dataTime: new Date(new Date(new Date().toLocaleDateString()).getTime()),
      fileStatus: '',
      totalResult: 0,
      total: 0,
      cacheTotal: 0,
      currentPage: 1,
      pageSize: 10,
      fileStatusList: [{ value: 1, label: '是' }, { value: 0, label: '否' }],
      filterFileStatus: [],
      fileStatusEnum: [],
      uploadProtocolEnum: [],
      fileTypeEnum: [],
      feedbackFileStatusEnum: []
    }
  },
  created() {
    this.get()
  },
  methods: {
    quickReport() {
      this.saveLoading = true
      var data = this.dataTime
      var dataTime = data.getTime()


      for (let i = 0; i < this.tableData.length; i++) {
        if(this.tableData[i].fileStatusEnum =="E3" || this.tableData[i].fileStatusEnum == "E4"){
          this.tableData[i].createTime = new Date(dataTime)
          this.quickReportData.push(this.tableData[i])
        }
      }
      this.$axios.post("uploadFileLog/quickReport",this.quickReportData).then(res=>{
        this.saveLoading = false
        this.$message({
          message: '执行成功',
          type: 'success'
        })
        this.seachLogInfo()
      })
    },
    get() {
      Promise.all([this.getAll(), this.getFileType(), this.getStatusEnum(), this.getProtocolEnum(), this.getFileTypeEnum()]).then((res) => {
        this.uploadList = res[0]
        this.uploadFileTypeList = res[1]
        this.fileStatusEnum = res[2]
        this.uploadProtocolEnum = res[3]
        this.fileTypeEnum = res[4]
        this.updateFilterEvent()
      })
    },
    // 过滤条件赋值，重新处理
    updateFilterEvent() {
      var data = []
      for (var i = 0; i < this.fileStatusEnum.length; i++) {
        data.push({ value: this.fileStatusEnum[i].name, label: this.fileStatusEnum[i].message })
      }
      const xTable = this.$refs.sTable
      const column = xTable.getColumnByField('fileStatusEnum')
      // 修改筛选列表，并默认设置为选中状态
      xTable.setFilter(column, data)
      // 修改条件之后，需要手动调用 updateData 处理表格数据
      xTable.updateData()
    },
    getEl() {
      const a = this.$axios
      return new Promise(function(resolve, reject) {
        a.get('/electricField/').then(res => {
          resolve(res.data)
          // console.log("获取场站信息成功")
        }).catch((error) => {
          this.$message.error('获取场站信息出错' + error)
        })
      })
    },
    getAll() {
      const a = this.$axios
      return new Promise(function(resolve, reject) {
        a.get('/uploadObject/').then(res => {
          resolve(res.data)
        }).catch(error => {
          this.$message.error('获取通道对象信息出错' + error)
        })
      })
    },
    getFileType() {
      const a = this.$axios
      return new Promise(function(resolve, reject) {
        a.get('/uploadObject/getFileType').then(res => {
          resolve(res.data)
        }).catch((error) => {
          this.$message.error('获取上报文件类型出错' + error)
        })
      })
    },
    getStatusEnum() {
      const a = this.$axios
      return new Promise(function(resolve, reject) {
        a.get('/uploadFileLog/getFileStatusEnum').then(res => {
          resolve(res.data)
        }).catch((error) => {
          this.$message.error('获取上报状态枚举出错' + error)
        })
      })
    },
    getProtocolEnum() {
      const a = this.$axios
      return new Promise(function(resolve, reject) {
        a.get('/uploadFileLog/getUploadProtocolEnum').then(res => {
          resolve(res.data)
        }).catch((error) => {
          this.$message.error('获取上报协议枚举出错' + error)
        })
      })
    },
    getFileTypeEnum() {
      const a = this.$axios
      return new Promise(function(resolve, reject) {
        a.get('/uploadFileLog/getFileTypeEnum').then(res => {
          resolve(res.data)
        }).catch((error) => {
          this.$message.error('获取上报文件类型枚举出错' + error)
        })
      })
    },
    // 查询
    seachLogInfo() {
      this.loading = true
      var data = this.dataTime
      var dataTime = data.getTime()
      const nowTimeDate = new Date(dataTime)
      nowTimeDate.setHours(0, 0, 0, 0)
      if (this.uploadObjectId === '' || this.uploadObjectId === null) {
        this.$message.error('请选择上报对象')
        this.loading = false
      } else {
        var uploadFileType = this.uploadFileType
        var fileStatus = this.fileStatus
        if (this.uploadFileType === '' || this.uploadFileType === null) {
          uploadFileType = 'ALL'
        }
        if (this.fileStatus === '' || this.fileStatus === null) {
          fileStatus = 'ALL'
        }
        this.$axios.get('/uploadFileLog/getFileLog/' + this.uploadObjectId + '/' + nowTimeDate.getTime() + '/' + uploadFileType + '/' + fileStatus).then((res) => {
          this.tableData = res.data
          this.totalResult = this.tableData.length
          this.loading = false
        }).catch(res => {
          this.loading = false
        })
      }
    },
    uploadObjectChange() {
      this.$axios.get('/uploadObject/getByuploadObjectId/' + this.uploadObjectId).then((res) => {
        // console.log(res)
        var list = res.data[0].uploadFileType.split(',')
        const data1 = []
        // console.log(list)
        for (let n = 0; n < list.length; n++) {
          for (let j = 0; j < this.uploadFileTypeList.length; j++) {
            if (list[n] == this.uploadFileTypeList[j]['value']) {
              data1.push({ value: this.uploadFileTypeList[j]['value'], label: this.uploadFileTypeList[j]['label'] })
            }
          }
        }
        this.FileTypeList = data1
      })
    },
    // 详细日志信息
    getFileDetaile(row) {
      // console.log(row)
      if (row.id === '' || row.id === null) {
        return
      } else {
        this.$axios.get('/uploadFileLogDetail/' + row.id).then((res) => {
          // console.log(res.data)
          this.detaileTable = res.data
          this.total = this.detaileTable.length
          this.logDetailShow = true
        })
      }
    },
    removeEvent(row) {
      // console.log(row.id)
      this.$XModal.confirm('您确定要删除该数据?').then(type => {
        if (type === 'confirm') {
          this.$axios.delete('/uploadFileLog/' + row.id).then(res => {
            if (res.data === 1) {
              if (row.uploadCounter > 0) {
                this.$axios.delete('/uploadFileLogDetail/' + row.id).then(res => {
                  if (res.data === 1) {
                    this.$message.success(`删除 ${row.fileName} 的文件日志和明细成功！！！`)
                    this.cleanCache(row)
                  }
                })
              } else {
                this.$message.success(`删除 ${row.fileName} 的文件日志成功！！！`)
                this.cleanCache(row)
              }
            }
          })
        }
      })
    },
    seachCache() {
      this.$axios.post('/uploadFileOpenInterface/getFileCache/').then(res => {
        // console.log(res.data)
        this.cacheShow = true
        this.currentPage = 1
        this.pageSize = 10
        this.cacheTable = res.data
        this.cacheTotal = res.data.length
        var data = []
        for (var i = 0; i < this.fileStatusEnum.length; i++) {
          data.push({ value: this.fileStatusEnum[i].name, label: this.fileStatusEnum[i].message })
        }
        this.$nextTick(() => {
          const xTable = this.$refs.xTable
          const column = xTable.getColumnByField('fileStatusEnum')
          // 修改筛选列表，并默认设置为选中状态
          xTable.setFilter(column, data)
          // 修改条件之后，需要手动调用 updateData 处理表格数据
          xTable.updateData()
        })
      })
    },
    cleanCache(row) {
      this.$axios.post('/uploadFileLog/cleanCache/', row).then(res => {
        this.seachLogInfo()
      })
    },
    seachFeedBackFile() {
      this.$axios.get('/feedbackFileLog').then(res => {
        this.feedbackShow = true
        this.feedbackTable = res.data
        var data = []
        for (var i = 0; i < this.feedbackFileStatusEnum.length; i++) {
          data.push({ value: this.feedbackFileStatusEnum[i].message, label: this.feedbackFileStatusEnum[i].message })
        }
        this.$nextTick(() => {
          const xTable = this.$refs.feedbackTable
          const column = xTable.getColumnByField('feedbackFileStatusEnum.message')
          // 修改筛选列表，并默认设置为选中状态
          xTable.setFilter(column, data)
          // 修改条件之后，需要手动调用 updateData 处理表格数据
          xTable.updateData()
        })
      })
    },
    // 根据文件样式改变行样式
    rowstyle({ row, rowIndex }) {
      // console.log(row)
      if (row.fileStatusEnum === 'E3') {
        return {
          background: 'linear-gradient(to bottom, #fa9870, #f85716)',
          color: '#ffffff'
        }
      } else if (row.fileStatusEnum === 'E4') {
        return {
          background: 'linear-gradient(to bottom, #fa908f,#f53f3d)',
          color: '#fff'
        }
      } else if (row.fileStatusEnum === 'E56') {
        return {
          background: 'linear-gradient(to right, #fdd921,#FF7F24)',
          color: '#ffffff'
        }
      }
    },
    // 导出
    exportDataEvent() {
      var date = new Date(this.dataTime) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()
      date = Y + M + D
      this.$refs.sTable.exportData({
        filename: `${date}文件日志`,
        type: 'csv'
      })
    },
    // 转换文件解析状态
    formateStatus({ cellValue }) {
      const item = this.fileStatusEnum.find(item => item.name === cellValue)
      return item ? item.message : ''
    },
    // 转换文件协议
    formateProtocol({ cellValue }) {
      const item = this.uploadProtocolEnum.find(item => item.name === cellValue)
      return item ? item.message : ''
    },
    // 转换文件类型协议
    formatefileType({ cellValue }) {
      const item = this.fileTypeEnum.find(item => item.name === cellValue)
      return item ? item.message : ''
    },
    // 时间转换
    dateFormat({ cellValue, row, column }) {
      if (cellValue !== null) {
        const date = new Date(cellValue) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
        const Y = date.getFullYear() + '-'
        const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        const D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()
        const h = ' ' + (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
        const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
        const s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
        return Y + M + D + h + m + s
      }
    },
    report(row){
      this.saveLoading = true
      var data = this.dataTime
      var dataTime = data.getTime()

      row.createTime = new Date(dataTime)
      this.$axios.post("uploadFileLog/report",row).then(res=>{
        this.saveLoading = false
        this.$message({
          message: '执行成功',
          type: 'success'
        })
        this.seachLogInfo()
      })
    }
  }
}
</script>

<style scoped>
  #uploadlog{
    padding-left: 20px;
    padding-top: 20px;
  }
  .mytable-style .vxe-body--row.row-red {
    background-color: red ;/*linear-gradient(to left, red , blue)*/
    color: #fff;
  }

</style>
