<template>
  <div id="main" class="h-all">
    <el-container class="h-all">
      <el-header height="auto">
        <div class="header-button-box">
          <el-button size='mini' icon="el-icon-delete" type="danger"
                     v-if="deleteCommand.visible"
                     @click="deletePeriodReportInit">
            {{$t("common.deleteBtn")}}
          </el-button>
        </div>
        <div class="header-search">
          <div class="search-input-box">
            <label>{{$t('common.startTime')}}：</label>
            <el-date-picker
              v-model="beginTimestamp"
              type="datetime"
              size="mini"
              format="yyyy-MM-dd HH:mm"
              clearable="false"
              align="center"
              style="width: 173px"
              :picker-options="startDatePicker"
              @change="beginDateChange"
              :placeholder="$t('AlarmQuery.chooseStartTime')">
            </el-date-picker>
          </div>
          <div class="search-input-box">
            <label>{{$t('common.endTime')}}：</label>
            <el-date-picker
              v-model="endTimestamp"
              type="datetime"
              size="mini"
              format="yyyy-MM-dd HH:mm"
              clearable="false"
              align="center"
              style="width: 173px"
              :picker-options="endDatePicker"
              @change="endDateChange"
              :placeholder="$t('AlarmQuery.chooseEndTime')">
            </el-date-picker>
          </div>
          <div class="search-input-box">
            <label>{{$t('PeriodReport.templateName')}}：</label>
            <el-input size='mini' style="width: 173px" :placeholder="$t('common.placeholder')" v-model="reportName"
                      clearable>
            </el-input>
          </div>
          <div class="search-input-box">
            <label>{{$t('PeriodReport.taskName')}}：</label>
            <el-input size='mini' style="width: 173px" :placeholder="$t('common.placeholder')" v-model="taskName"
                      clearable>
            </el-input>
          </div>
          <div class="search-input-box">
            <label>{{$t('PeriodReport.period')}}：</label>
            <el-select v-model="period" size="mini" :placeholder="$t('common.selectOption')" :clearable="true">
              <el-option
                v-for="item in PeriodList"
                :key="item.key"
                :label="item.label"
                :value="item.key">
              </el-option>
            </el-select>
          </div>
          <el-button icon="el-icon-search" type="primary" size = 'mini' @click="queryPeriodReportByCondition">{{$t('common.queryBtn')}}</el-button>
        </div>
      </el-header>
      <!-- table数据表格 -->
      <el-main class="adapt-height-box">
        <el-table
          :empty-text="$t('common.noData')"
          tooltip-effect="dark"
          ref="singleTable"
          :data="PeriodReportList"
          stripe
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          border
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="28">
          </el-table-column>
          <el-table-column
            prop="reportName"
            :label="$t('PeriodReport.templateName')">
          </el-table-column>
          <el-table-column
            prop="reportTaskName"
            :label="$t('PeriodReport.taskName')">
          </el-table-column>
          <el-table-column
            prop="period"
            :formatter='formatPeriod'
            :label="$t('PeriodReport.period')">
          </el-table-column>
          <el-table-column
            prop="genTime"
            :formatter="formatTime"
            :label="$t('PeriodReport.genTime')">
          </el-table-column>
          <el-table-column
            width="55px"
            :label="$t('common.operation')">
            <template slot-scope="scope">
              <el-button
                size="mini"
                style="background: #006FFF"
                :title="$t('PeriodReport.download')"
                @click="downloadLog(scope.row)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-xiazai"></use>
                </svg>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-main>
    </el-container>
    <CommandExecuteContext v-bind:commands="commandContext"></CommandExecuteContext>
  </div>
</template>

<script>
import CommandExecuteContext from '../../commands/CommandExecuteContext'
import HelperUtil from '../../utils/HelperUtil'
import PeriodReportService from '../../domain/services/PeriodReportService'
import PeriodReportCommands from '../../commands/PeriodReportCommands'

export default {
  name: 'PeriodReport',

  components: {
    CommandExecuteContext
  },
  created: function () {
    if (this.$route.query.reportTaskName != null) {
      this.taskName = this.$route.query.reportTaskName
      this.TurnFromReportTask(this.$route.query.reportTaskName)
    }
    if (this.$route.query.reportTaskKey == null) {
      this.queryInit()
    }
  },
  data: function () {
    return {
      // 命令
      commandContext: {},
      // 为修改传参数
      multipleSelection: [],
      deleteList: [],
      PeriodReportList: [],
      reportTemplateList: [],

      addTimestamp: '00.000',
      addTimestamp1: '59.999',
      startDatePicker: this.beginDate(),
      endDatePicker: this.endDate(),
      // form参数
      beginTimestamp: '',
      endTimestamp: '',
      reportName: '',
      taskName: '',
      period: '',
      PeriodList: [
        {
          key: 5,
          label: this.$t('ReportTask.dayReport')
        },
        {
          key: 4,
          label: this.$t('ReportTask.weekReport')
        },
        {
          key: 3,
          label: this.$t('ReportTask.monthReport')
        },
        {
          key: 2,
          label: this.$t('ReportTask.quarterReport')
        },
        {
          key: 1,
          label: this.$t('ReportTask.halfYearReport')
        },
        {
          key: 0,
          label: this.$t('ReportTask.yearReport')
        }
      ],
      reportTypeList: [
        {
          key: 0,
          label: this.$t('ReportTemplateManagement.alarmDistribution')
        },
        {
          key: 1,
          label: this.$t('ReportTemplateManagement.alarmTrend')
        },
        {
          key: 2,
          label: this.$t('ReportTemplateManagement.alarmTopBottom')
        },
        {
          key: 3,
          label: this.$t('ReportTemplateManagement.performanceDistribution')
        },
        {
          key: 4,
          label: this.$t('ReportTemplateManagement.performanceTrend')
        },
        {
          key: 5,
          label: this.$t('ReportTemplateManagement.performanceTopBottom')
        }
      ],
      // 双向绑定展示数据
      beginItem: 1,
      endItem: 100,
      total: 100,
      currentPage: 1,
      pageSize: 100
    }
  },

  computed: {
    deleteCommand () {
      return PeriodReportCommands.deletePeriodReportCommand(this.deleteList, this.commandContext)
    },
    openTab () {
      return this.$store.state.openTab
    },
    activeIndex: {
      get () {
        return this.$store.state.activeIndex
      },
      set (val) {
        this.$store.commit('set_active_index', val)
      }
    }
  },

  methods: {
    /**
     * @Description  : 开始时间
     * @author       : ls
     * @date         : 2020/6/12 9:03
     * @param        :
     * @return       :
     */
    beginDate: function () {
      return {
        disabledDate: time => {
          if (this.endTimestamp) {
            return (
              time.getTime() > new Date(this.endTimestamp).getTime()
            )
          }
        }
      }
    },
    /**
     * @Description  : 结束时间
     * @author       : ls
     * @date         : 2020/6/12 9:05
     * @param        :
     * @return       :
     */
    endDate: function () {
      return {
        disabledDate: time => {
          if (this.beginTimestamp) {
            return (
              time.getTime() < new Date(this.beginTimestamp).getTime()
            )
          }
        }
      }
    },
    /**
     * @Description  : shanchu
     * @author       : ls
     * @date         : 2020/4/26 15:01
     * @param        :
     * @return       :
     */
    deletePeriodReportInit () {
      if (this.multipleSelection.length === 0) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.DELETE_SELECT_CODE))
      } else {
        this.deleteList = []
        for (var i = 0; i < this.multipleSelection.length; i++) {
          this.deleteList.push(this.multipleSelection[i])
        }
        this.deleteCommand.execute()
      }
    },
    /**
     * @Description  : 格式化周期
     * @author       : ls
     * @date         : 2020/6/9 16:08
     * @param        :
     * @return       :
     */
    formatPeriod: function (row) {
      var ret = ''
      switch (row.period) {
        case 0:
          ret = this.$t('ReportTask.yearReport')
          break
        case 1:
          ret = this.$t('ReportTask.halfYearReport')
          break
        case 2:
          ret = this.$t('ReportTask.quarterReport')
          break
        case 3:
          ret = this.$t('ReportTask.monthReport')
          break
        case 4:
          ret = this.$t('ReportTask.weekReport')
          break
        case 5:
          ret = this.$t('ReportTask.dayReport')
          break
      }
      return ret
    },
    /**
     * @Description  : 格式化时间
     * @author       : ls
     * @date         : 2020/6/12 9:36
     * @param        :
     * @return       :
     */
    formatTime: function (row) {
      return HelperUtil.timeTran(row.genTime)
    },
    /**
     * @Description  : shezhitiaojian
     * @author       : ls
     * @date         : 2020/4/27 10:05
     * @param        :
     * @return       :
     */
    setSelectList: function () {
      this.selectList = []
      if (this.beginTimestamp !== null && this.beginTimestamp !== '') {
        this.selectList.push({
          quaryAttribute: 'genTime',
          compareSymbol: '>',
          compareValue: HelperUtil.getTimeInit(this.beginTimestamp) + this.addTimestamp
        })
      }
      if (this.endTimestamp !== '' && this.endTimestamp !== null) {
        this.selectList.push({
          quaryAttribute: 'genTime',
          compareSymbol: '<',
          compareValue: HelperUtil.getTimeInit(this.endTimestamp) + this.addTimestamp1
        })
      }
      if (this.reportName !== '' && this.reportName !== null) {
        this.selectList.push({
          quaryAttribute: 'reportName',
          compareSymbol: 'like',
          compareValue: this.reportName
        })
      }
      if (this.taskName !== '' && this.taskName !== null) {
        this.selectList.push({
          quaryAttribute: 'reportTaskName',
          compareSymbol: 'like',
          compareValue: this.taskName
        })
      }
      if (this.period !== '' && this.period !== null) {
        this.selectList.push({
          quaryAttribute: 'period',
          compareSymbol: '=',
          compareValue: this.period
        })
      }
    },
    /**
     * @Description  : 下载
     * @author       : ls
     * @date         : 2020/6/15 14:14
     * @param        :
     * @return       :
     */
    downloadLog: function (row) {
      let _this = this
      let loadingInstance = this.Loading.openLoading()
      PeriodReportService.downloadPeriodReport(row).then(result => {
        // 关闭loading
        _this.Loading.closeLoading(loadingInstance)
        // 成功
        _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.OTHERS_CODE))
      }).catch(err => {
        // 关闭loading
        _this.Loading.closeLoading(loadingInstance)
        // 失败
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 转入
     * @author       : ls
     * @date         : 2020/6/15 15:50
     * @param        :
     * @return       :
     */
    TurnFromReportTask: function (msg) {
      let _this = this
      _this.selectList = []
      _this.selectList.push({
        quaryAttribute: 'reportTaskName',
        compareSymbol: 'like',
        compareValue: msg
      })
      this.PeriodReportDataTotalNumber()
    },
    /**
     * @Description  : 选中数据
     * @author       : ls
     * @date         : 2020/4/29 12:06
     * @param        :
     * @return       :
     */
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    /**
     * @Description  : 初始化
     * @author       : ls
     * @date         : 2020/5/26 14:42
     * @param        :
     * @return       :
     */
    handleCurrentChange (val) {
      this.currentPage = val
      this.beginItem = ((val - 1) * 100) + 1
      this.endItem = this.beginItem + 99
      if (this.endItem > this.total) {
        this.endItem = this.total
      }
      this.queryPeriodReportDataByConditionCurrentPage()
    },
    /**
     * @Description  : 分页
     * @author       : ls
     * @date         : 2020/5/26 14:44
     * @param        :
     * @return       :
     */
    queryPeriodReportDataByConditionCurrentPage: function () {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      PeriodReportService.queryPeriodReportDataSplitNumber(this.beginItem, this.endItem, this.selectList).then(result => {
        _this.PeriodReportList = Object.values(result)
        _this.Loading.closeLoading(loadingInstance)
      }).catch(err => {
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 查询
     * @author       : ls
     * @date         : 2020/6/10 14:45
     * @param        :
     * @return       :
     */
    queryInit: function () {
      this.beginItem = 1
      this.setSelectList()
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      PeriodReportService.getPeriodReportTotalCounts(this.selectList).then(result => {
        _this.total = result
        _this.Loading.closeLoading(loadingInstance)
        if (_this.total === 0 || _this.total < 0) {
          _this.PeriodReportList = []
        } else {
          if (_this.total < 100 && _this.total > 0) {
            _this.endItem = _this.total
          } else {
            _this.endItem = 100
          }
          _this.queryPeriodReportDataByConditionCurrentPage()
        }
      }).catch(err => {
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 条件查询
     * @author       : ls
     * @date         : 2020/5/26 14:47
     * @param        :
     * @return       :
     */
    queryPeriodReportByCondition: function () {
      this.beginItem = 1
      this.setSelectList()
      this.PeriodReportDataTotalNumber()
    },
    /**
     * @Description  : 查询总数
     * @author       : ls
     * @date         : 2020/5/26 15:04
     * @param        :
     * @return       :
     */
    PeriodReportDataTotalNumber: function () {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      PeriodReportService.getPeriodReportTotalCounts(this.selectList).then(result => {
        _this.total = result
        _this.Loading.closeLoading(loadingInstance)
        if (_this.total === 0 || _this.total < 0) {
          _this.PeriodReportList = []
          _this.InfoTip.warningTip_alarm(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.QUERY_NULL_CODE))
        } else {
          if (_this.total < 100 && _this.total > 0) {
            _this.endItem = _this.total
          } else {
            _this.endItem = 100
          }
          _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.QUERY_CODE))
          _this.queryPeriodReportDataByConditionCurrentPage()
        }
      }).catch(err => {
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    }
  },

  watch: {
    '$route' (to) {
      if (to.name === '周期报表' && to.query.reportTaskName !== undefined) {
        this.taskName = to.query.reportTaskName
        this.TurnFromReportTask(to.query.reportTaskName)
      }
    },
    commandContext (newVal, oldVal) {
      if (JSON.stringify(newVal) === '{}') {
        this.queryInit()
        this.$refs.singleTable.clearSelection()
      }
      deep: true
    }
  }
}
</script>

<style scoped>
</style>
