<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-circle-plus-outline" type="primary" @click="createTemplateInit"
                       v-if="createAndCopyCommand.visible">{{$t('common.createBtn')}}</el-button>
            <el-button size = 'mini' icon="el-icon-delete" type="danger" @click="deleteTemplateInit"
                       v-if="deleteTemplateCommand.visible">{{$t('common.deleteBtn')}}</el-button>
            <div class="search">
              <div class="search-div">
                <label>{{$t('ReportTemplateManagement.reportTemplateName')}}：</label>
                <el-input size='mini' :placeholder="$t('common.placeholder')"
                          v-model="queryReportTemplateName"
                          style="width: 180px"
                          clearable>
                </el-input>
              </div>
              <div class="search-div">
                <label>{{$t('ReportTemplateManagement.templateType')}}：</label>
                <el-select v-model="queryTemplateType" size="mini" :placeholder="$t('common.selectOption')" :clearable="true">
                  <el-option
                    v-for="item in TemplateNameList"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key">
                  </el-option>
                </el-select>
              </div>
              <div class="search-div">
                <label>{{$t('ReportTemplateManagement.subnetKey')}}：</label>
                <el-select v-model="querySubnetKey" size="mini" :placeholder="$t('common.selectOption')" :clearable="true">
                  <el-option
                    v-for="item in subnetList"
                    :key="item.subnetKey"
                    :label="item.subnetName"
                    :value="item.subnetKey">
                  </el-option>
                </el-select>
              </div>
              <div class="search-div">
                <el-button icon="el-icon-search" type="primary" size = 'mini' @click="queryReportTemplateList">{{$t('common.queryBtn')}}</el-button>
              </div>
            </div>
        </div>
      </el-header>
      <!-- table数据表格 -->
      <el-main class="adapt-height-box">
        <el-table
          :empty-text="$t('common.noData')"
          tooltip-effect="dark"
          stripe
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          border
          ref="singleTable"
          :data="reportTemplateList"
          highlight-current-row
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="28">
          </el-table-column>
          <el-table-column
            prop="reportTemplateName"
            :label="$t('ReportTemplateManagement.reportTemplateName')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="subnetName"
            :label="$t('ReportTemplateManagement.subnetKey')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="description"
            :label="$t('ReportTemplateManagement.desc')">
          </el-table-column>
          <el-table-column
            prop="reportType"
            :label="$t('ReportTemplateManagement.templateType')"
            :formatter="formatReportType">
          </el-table-column>
          <el-table-column
            prop="statDimensionX"
            :formatter="formatDimensionX"
            :label="$t('ReportTemplateManagement.X')">
          </el-table-column>
          <el-table-column
            prop="statDimensionY"
            :formatter="formatDimensionY"
            :label="$t('ReportTemplateManagement.Y')">
          </el-table-column>
          <el-table-column
            prop="filterValue"
            :formatter="formatFilterValue"
            :show-overflow-tooltip="true"
            :label="$t('ReportTemplateManagement.filter')">
          </el-table-column>
          <el-table-column
            width="105px"
            :label="$t('common.operation')">
            <template slot-scope="scope">
              <el-button
                size="mini"
                style="background: #175BE3"
                :title="$t('common.copyBtn')"
                @click="handleCopy(scope.row)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-fuzhi"></use>
                </svg>
              </el-button>
              <el-button
                size="mini"
                style="background: #008000"
                :title="$t('common.updateBtn')"
                @click="handleUpdate(scope.row)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-bianji"></use>
                </svg>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page.sync="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 ReportTemplateCommands from '@/commands/ReportTemplateCommands'
import ReportTemplateService from '@/domain/services/ReportTemplateService'
import HelperUtil from '@/utils/HelperUtil'
import loading from '../../utils/Loading'
import SubnetService from '../../domain/services/SubnetService'
import PerformanceStatisticService from "../../domain/services/PerformanceStatisticService";
import DeviceService from "../../domain/services/DeviceService";

export default {
  name: 'ReportTemplateManagement',
  components: {
    CommandExecuteContext
  },

  data: function () { // 存放数据
    return {
      reportTemplateList: [],
      queryReportTemplateName: '',
      queryTemplateType: '',
      querySubnetKey: '',
      subnetList: [],
      TemplateNameList: [
        {
          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')
        }
      ],
      tranDimension: {
        'alarmLevel': this.$t('ReportTemplateManagement.alarmLevel'),
        'alarmStatus': this.$t('ReportTemplateManagement.alarmStatus'),
        'alarmCode': this.$t('ReportTemplateManagement.alarmCause'),
        'displayName': this.$t('ReportTemplateManagement.device'),
        'deviceTypeKey': this.$t('ReportTemplateManagement.deviceType'),
        'deviceModel': this.$t('ReportTemplateManagement.deviceModel'),
        'brand': this.$t('ReportTemplateManagement.deviceBrand'),
        'deviceParam': this.$t('ReportTemplateManagement.performEvent')
      },
      tranDimensionY: {
        'alarmLevel': this.$t('ReportTemplateManagement.alarmLevel'),
        'alarmStatus': this.$t('ReportTemplateManagement.alarmStatus'),
        'alarmCode': this.$t('ReportTemplateManagement.alarmCause'),
        'displayName': this.$t('ReportTemplateManagement.device'),
        'deviceTypeKey': this.$t('ReportTemplateManagement.deviceType'),
        'deviceModel': this.$t('ReportTemplateManagement.deviceModel'),
        'brand': this.$t('ReportTemplateManagement.deviceBrand'),
        'deviceParam': this.$t('ReportTemplateManagement.performEvent')
      },
      tranAlarmLevel: {
        0: this.$t('ReportTemplateManagement.warn'),
        1: this.$t('ReportTemplateManagement.serve'),
        2: this.$t('ReportTemplateManagement.urgency')
      },
      tranAlarmStatus: {
        0: this.$t('AlarmQuery.Notconfirmed'),
        1: this.$t('AlarmQuery.Confirmed'),
        2: this.$t('AlarmQuery.Cleared'),
        3: this.$t('AlarmQuery.Restored'),
        4: this.$t('AlarmQuery.Delete')
      },
      tranDeviceParam: {},
      tranDeviceTypeKey: {},
      // 命令
      commandContext: {},
      // 为了创建复制初始化传参
      createAndCopyInitList: [],
      copyInitList: [],
      createAndCopyTitle: '',
      // 删除相关
      deleteList: [],
      // 为修改传参数
      updateInitList: [],
      fullscreenLoading: false,
      formLabelWidth: '120px',
      value: '',
      selectList: [],
      beginItem: 1,
      endItem: 100,
      total: 100,
      currentPage: 1,
      pageSize: 100,
      // 保存多选行数据
      multipleSelection: []
    }
  },
  // vue加载初始化函数，加载数据
  created: function () {
    this.getAllSubnetInit()
    this.getPerformType()
    this.getAllDeviceType()
    this.queryInit()
  },
  computed: {
    // 命令
    createAndCopyCommand () {
      return ReportTemplateCommands.createAndCopyReportTemplateCommand(this.createAndCopyTitle, this.createAndCopyInitList, this.commandContext)
    },
    copyCommand () {
      return ReportTemplateCommands.copyReportTemplateCommand(this.createAndCopyInitList, this.commandContext)
    },
    deleteTemplateCommand () {
      return ReportTemplateCommands.deleteReportTemplateCommand(this.deleteList, this.commandContext)
    },
    updateTemplateCommand () {
      return ReportTemplateCommands.updateReportTemplateCommand(this.updateInitList, this.commandContext)
    }
  },
  methods: {
    /**
     * @Description  : 创建报表模板
     * @author       : ls
     * @date         : 2020/5/2 14:37
     * @param        :
     * @return       :
     */
    createTemplateInit: function () {
      this.createAndCopyTitle = this.$t('ReportTemplateManagement.createReportTemplate')
      this.createAndCopyInitList = {}
      this.createAndCopyCommand.execute()
    },
    /**
     * @Description  : 复制
     * @author       : ls
     * @date         : 2020/5/2 14:37
     * @param        :
     * @return       :
     */
    handleCopy: function (row) {
      this.createAndCopyTitle = this.$t('ReportTemplateManagement.copyReportTemplate')
      this.createAndCopyInitList = row
      this.copyCommand.execute()
    },
    /**
     * @Description  : 修改
     * @author       : ls
     * @date         : 2020/5/2 14:39
     * @param        :
     * @return       :
     */
    handleUpdate: function (row) {
      this.updateInitList = row
      this.updateTemplateCommand.execute()
    },
    /**
     * @Description  : shanchu
     * @author       : ls
     * @date         : 2020/4/23 19:40
     * @param        :
     * @return       :
     */
    deleteTemplateInit: function () {
      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]['reportTemplateKey'])
        }
        this.deleteTemplateCommand.execute()
      }
    },
    /**
     * @Description  : 取值
     * @author       : ls
     * @date         : 2020/5/2 14:39
     * @param        :
     * @return       :
     */
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    /**
     * @Description  : 子网格式化
     * @author       : ls
     * @date         : 2020/5/26 16:44
     * @param        :
     * @return       :
     */
    formatSubnetKey: function (row) {
      for (var i = 0; i < this.subnetList.length; i++) {
        if (this.subnetList[i]['subnetKey'] === row.subnetKey) {
          return this.subnetList[i]['subnetName']
        }
      }
    },
    /**
     * @Description  : 格式化维度
     * @author       : ls
     * @date         : 2020/5/27 15:18
     * @param        :
     * @return       :
     */
    formatDimensionX: function (val) {
      return this.tranDimension[val.statDimensionX]
    },
    /**
     * @Description  : 格式化维度
     * @author       : ls
     * @date         : 2020/5/27 15:55
     * @param        :
     * @return       :
     */
    formatDimensionY: function (val, col) {
      if (val.statDimensionY.charAt(0) < 'A' || val.statDimensionY.charAt(0) > 'Z') {
        return this.tranDimension[val.statDimensionY]
      } else {
        return this.tranDimensionY[val.statDimensionY]['peformTypeName']
      }
    },
    /**
     * @Description  : 格式化条件
     * @author       : ls
     * @date         : 2020/5/27 15:55
     * @param        :
     * @return       :
     */
    formatFilterValue: function (val) {
      if (val.filterValue !== '' && val.filterValue !== null) {
        var ret = ''
        var arr1 = []
        var arr = (val.filterValue.indexOf(';') !== -1) ? val.filterValue.split(';') : val.filterValue.split()
        for (var i = 0; i < arr.length; i++) {
          ret = (i === 0) ? ret : ret.concat(';  ')
          arr1 = arr[i].split('@#')
          for (var j = 0; j < arr1.length; j++) {
            if (j === 0) {
              ret = ret.concat(this.tranDimension[arr1[0]]).concat(':')
            } else if (j === 1) {
              continue
            } else {
              if (arr1[0] === 'alarmLevel') {
                var arr2 = arr1[2].split(',')
                for (var t = 0; t < arr2.length; t++) {
                  if (t === 0) {
                    ret = ret.concat(this.tranAlarmLevel[arr2[t]])
                  } else {
                    ret = ret.concat(',').concat(this.tranAlarmLevel[arr2[t]])
                  }
                }
              } else if (arr1[0] === 'alarmStatus') {
                var arr3 = arr1[2].split(',')
                for (var k = 0; k < arr3.length; k++) {
                  if (k === 0) {
                    ret = ret.concat(this.tranAlarmStatus[arr3[k]])
                  } else {
                    ret = ret.concat(',').concat(this.tranAlarmStatus[arr3[k]])
                  }
                }
              } else if (arr1[0] === 'deviceParam') {
                var arr4 = arr1[2].split(',')
                for (var k1 = 0; k1 < arr4.length; k1++) {
                  if (k1 === 0) {
                    ret = ret.concat(this.tranDeviceParam[arr4[k1]]['peformTypeName'])
                  } else {
                    ret = ret.concat(',').concat(this.tranDeviceParam[arr4[k1]]['peformTypeName'])
                  }
                }
              } else if (arr1[0] === 'deviceTypeKey') {
                var arr5 = arr1[2].split(',')
                for (var k2 = 0; k2 < arr5.length; k2++) {
                  if (k2 === 0) {
                    ret = ret.concat(this.tranDeviceTypeKey[arr5[k2]]['deviceTypeName'])
                  } else {
                    ret = ret.concat(',').concat(this.tranDeviceTypeKey[arr5[k2]]['deviceTypeName'])
                  }
                }
              } else {
                ret = ret.concat(arr1[j])
              }
            }
          }
        }
        return ret
      } else {
        return ''
      }
    },
    /**
     * @Description  : 格式化类型
     * @author       : ls
     * @date         : 2020/5/26 17:10
     * @param        :
     * @return       :
     */
    formatReportType: function (row) {
      var ret = ''
      switch (row.reportType) {
        case 0:
          ret = this.$t('ReportTemplateManagement.alarmDistribution')
          break
        case 1:
          ret = this.$t('ReportTemplateManagement.alarmTrend')
          break
        case 2:
          ret = this.$t('ReportTemplateManagement.alarmTopBottom')
          break
        case 3:
          ret = this.$t('ReportTemplateManagement.performanceDistribution')
          break
        case 4:
          ret = this.$t('ReportTemplateManagement.performanceTrend')
          break
        case 5:
          ret = this.$t('ReportTemplateManagement.performanceTopBottom')
          break
      }
      return ret
    },
    /**
     * @Description  : 分页变化
     * @author       : ls
     * @date         : 2020/5/6 15:44
     * @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.reportTemplateListByConditionCurrentPage()
    },
    /**
     * @Description  : 查询
     * @author       : ls
     * @date         : 2020/6/10 15:15
     * @param        :
     * @return       :
     */
    queryInit: function () {
      this.beginItem = 1
      this.setSelectList()
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      ReportTemplateService.queryReportTemplateTotalNumber(this.selectList).then(result => {
        _this.Loading.closeLoading(loadingInstance)
        _this.total = result
        if (_this.total === 0 || _this.total < 0) {
          _this.reportTemplateList = []
        } else {
          if (_this.total < 100 && _this.total > 0) {
            _this.endItem = _this.total
          } else {
            _this.endItem = 100
          }
        }
        _this.reportTemplateListByConditionCurrentPage()
      }).catch(err => {
        _this.endItem = 100
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 首次加载
     * @author       : ls
     * @date         : 2020/5/6 15:55
     * @param        :
     * @return       :
     */
    queryReportTemplateList: function () {
      this.beginItem = 1
      this.setSelectList()
      this.queryReportTemplateListTotalNumber()
    },
    /**
     * @Description  : 查询总页数
     * @author       : ls
     * @date         : 2020/5/6 16:01
     * @param        :
     * @return       :
     */
    queryReportTemplateListTotalNumber: function () {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      ReportTemplateService.queryReportTemplateTotalNumber(this.selectList).then(result => {
        _this.Loading.closeLoading(loadingInstance)
        _this.total = result
        if (_this.total === 0 || _this.total < 0) {
          _this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.QUERY_NULL_CODE))
          _this.reportTemplateList = []
        } 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.reportTemplateListByConditionCurrentPage()
      }).catch(err => {
        _this.endItem = 100
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 分页查询
     * @author       : ls
     * @date         : 2020/5/6 15:46
     * @param        :
     * @return       :
     */
    reportTemplateListByConditionCurrentPage: function () {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      ReportTemplateService.queryReportTemplateDataSplitNumber(this.beginItem, this.endItem, this.selectList).then(result => {
        // 成功
        _this.reportTemplateList = Object.values(result)
        _this.Loading.closeLoading(loadingInstance)
      }).catch(err => {
        // 失败
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 获取所有
     * @author       : ls
     * @date         : 2020/5/2 14:28
     * @param        :
     * @return       :
     */
    getAllTreportemplateInit: function () {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      ReportTemplateService.getAllReportTemplateCollection().then(result => {
        // 成功
        _this.reportTemplateList = Object.values(result)
      }).catch(err => {
        this.InfoTip.errorTip(this, err)
      })
      _this.Loading.closeLoading(loadingInstance)
    },
    /**
     * @Description  : 获取子网
     * @author       : ls
     * @date         : 2020/5/26 16:46
     * @param        :
     * @return       :
     */
    getAllSubnetInit: function () {
      let _this = this
      let loadingInstance = loading.openLoading()
      SubnetService.getAllSubnetCollection().then(result => {
        _this.subnetList = Object.values(result)
        loadingInstance.close()
      }).catch(err => {
        this.InfoTip.errorTip(this, err)
        loadingInstance.close()
      })
    },
    /**
     * @Description  : getPerformType
     * @author       : ls
     * @date         : 2021/1/26 17:03
     * @param        :
     * @return       :
     */
    getPerformType: function () {
      let _this = this
      PerformanceStatisticService.getPerformTypeService().then(result => {
        _this.tranDeviceParam = result
        _this.tranDimensionY = Object.assign(_this.tranDimensionY, result)
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : getAllDeviceType
     * @author       : ls
     * @date         : 2021/1/26 17:47
     * @param        :
     * @return       :
     */
    getAllDeviceType: function () {
      let _this = this
      DeviceService.getAllDeviceTypeCollection().then(result => {
        _this.tranDeviceTypeKey = result
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 设置条件
     * @author       : ls
     * @date         : 2020/5/26 16:46
     * @param        :
     * @return       :
     */
    setSelectList: function () {
      this.selectList = []
      if (this.queryReportTemplateName !== '' && this.queryReportTemplateName !== null) {
        this.selectList.push({
          quaryAttribute: 'reportTemplateName',
          compareSymbol: 'like',
          compareValue: this.queryReportTemplateName
        })
      }
      if (this.queryTemplateType !== '' && this.queryTemplateType !== null) {
        this.selectList.push({
          quaryAttribute: 'reportType',
          compareSymbol: '=',
          compareValue: this.queryTemplateType
        })
      }
      if (this.querySubnetKey !== '' && this.querySubnetKey !== null) {
        this.selectList.push({
          quaryAttribute: 'subnetKey',
          compareSymbol: '=',
          compareValue: this.querySubnetKey
        })
      }
    },
    /**
     * @Description  : 条件查询
     * @author       : ls
     * @date         : 2020/4/22 17:22
     * @param        :
     * @return       :
     */
    queryTemplateByCondition: function () {
      let _this = this
      this.setSelectList()
      let loadingInstance = _this.Loading.openLoading()
      ReportTemplateService.queryReportTemplate(this.selectList).then(result => {
        _this.reportTemplateList = Object.values(result)
        _this.Loading.closeLoading(loadingInstance)
        if (_this.reportTemplateList.length === 0) {
          this.InfoTip.warningTip(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.QUERY_NULL_CODE))
        } else {
          this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.QUERY_CODE))
        }
      }).catch(err => {
        this.Loading.closeLoading(loadingInstance)
        this.InfoTip.errorTip(_this, err)
      })
    }
  },
  watch: {
    commandContext (newVal, oldVal) {
      if (JSON.stringify(newVal) === '{}') {
        this.queryInit()
        this.$refs.singleTable.clearSelection()
      }
      deep: true
    }
  }
}
</script>

<style scoped>
</style>
