<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-document" type="primary" @click="save">{{$t('AlarmConfigManagement.save')}}</el-button>
        </div>
      </el-header>
      <!-- table数据表格 -->
      <el-main class="adapt-height-box">
        <el-table
          :empty-text="$t('common.noData')"
          ref="multipleTable"
          :data="alarmLevelConfigList"
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          border
          tooltip-effect="dark"
          highlight-current-row
          stripe
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            v-if="false"
            width="28">
          </el-table-column>
          <el-table-column
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            prop="alarmLevel"
            :label="$t('AlarmConfigManagement.alarmLevel')"
            align="left"
            :formatter="alarmLevelTurnWord"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="alarmColor"
            :label="$t('AlarmConfigManagement.alarmColor')"
            align="left"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-select
                size='mini'
                v-model="alarmLevelConfigList[scope.$index].alarmColor"
                :placeholder="$t('common.placeholder')"
                style="width: 180px"
                :style="{'background-color':alarmLevelConfigList[scope.$index].alarmColor}"
              >
                <el-option
                  v-for="item in colorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :style="{'background-color':item.value}">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="alarmVoice"
            :label="$t('AlarmConfigManagement.alarmVoice')"
            align="left"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column label="">
            <template slot-scope="scope">
              <el-upload
                accept="music/mp3,music/mp4,music/war"
                class="upload-demo"
                :action="uploadUrl()"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="1"
                :on-exceed="handleExceed"
                :on-success="successUpload"
                :auto-upload="true"
                :before-upload="beforeUpload"
                :file-list="fileList">
                <el-button size="mini" @click="loadFileClick(scope.$index)">{{$t('common.importBtn')}}</el-button>
              </el-upload>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </div>
</template>

<script>
  import Vue from 'vue';
  import VueResource from 'vue-resource'
  import ElCol from 'element-ui/packages/col/src/col'
  import AlarmManagerService from '@/domain/services/AlarmManagerService.js'
  import DeviceService from '@/domain/services/DeviceService.js'
  import AlarmLevelConfigService from '@/domain/services/AlarmLevelConfigService.js'
  import HelperUtil from "../../utils/HelperUtil";

  export default {
    name: 'AlarmConfigManagement',
    data() {
      return {
        //颜色选择
        colorOptions: [{
          value: '#FF6347',
          label: this.$t('AlarmConfigManagement.red')
        }, {
          value: '#FFFF00',
          label: this.$t('AlarmConfigManagement.yellow')
        }, {
          value: '#FFA500',
          label: this.$t('AlarmConfigManagement.orange')
        }],
        colorValue0: 'color1',
        colorValue1: 'color2',
        colorValue2: 'color0',
        colorValue0_backup: 'color1',
        colorValue1_backup: 'color2',
        colorValue2_backup: 'color0',
        uploadUrl1: '',

        voiceValue0: 'voice0',
        voiceValue1: 'voice1',
        voiceValue2: 'voice2',
        fileList: [],
        alarmLevelConfigList: [],   //报警等级配置列表
        alarmLevelConfigList_backup: [],  //报警等级配置列表（备份）
        alarmLevelListUpdate: [],   //报警配置列表上传内容
        alarmLevelListUpdateNum: 0,   //报警配置列表上传列表长度
        updateRowIndex: '',    //上传文件的行数
        alertContain: '',   //告警等级信息修改内容
      }
    },
    created: function () {
      this.getAlarmConfigList();
      this.getAlarmConfigList1();
    },
    methods: {
      uploadUrl: function () {
        //return protocal + ip + port + project + "cxf/nms/alarmconfig/uploadaudio";
        return AlarmManagerService.getUplaodUrl()
      },

      loadFileClick: function (index) {
        this.updateRowIndex = index;
      },

      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        //当前限制选择 1 个文件"
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.UPDATE_LIMIT_CODE))
      },
      beforeRemove(file, fileList) {
        //return this.$confirm(`确定移除 ${ file.name }？`);
      },

      beforeUpload(file) {
        var FileExt = file.name.replace(/.+\./, "");
        if (['mp3','wma','wav','ape','flac','ogg','aac'].indexOf(FileExt.toLowerCase()) === -1){
          this.InfoTip.warningTip(this, {message: this.$t('AlarmConfigManagement.voiceTip')})
          return false;
        }
      },

      /**
       *   当成功上传的时候
       */
      successUpload(response, file, fileList) {
        console.log(file);
        this.alarmLevelConfigList[this.updateRowIndex].alarmVoice = file.name;
        this.alarmLevelConfigList_backup[this.updateRowIndex].alarmVoice = file.name;
        this.alarmLevelListUpdate.push(this.alarmLevelConfigList_backup[this.updateRowIndex]);
        this.handleAlertContain(this.alarmLevelListUpdate[0], 1);
        let alartContainObject = new Object();
        alartContainObject.message = this.alertContain;
        this.InfoTip.conformTip(this, alartContainObject).then(() => {
          this.updateAlarmLevelVoice()
        }).catch(()=>{
          this.alertContain = "";
        });
      },

      /**
       *  获取告警配置的数据
       */
      getAlarmConfigList: function () {
        let _this = this;
        AlarmLevelConfigService.getNormalAlarmLevelConfig().then(result => {
          //成功
          _this.alarmLevelConfigList = Object.values(result)
        }).catch(err => {
          //失败
          _this.InfoTip.errorTip(_this, err);
        })
      },
      /**
       *  获取告警配置的数据（备份）
       */
      getAlarmConfigList1: function () {
        let _this = this;
        AlarmLevelConfigService.getNormalAlarmLevelConfig().then(result => {
          //成功
          _this.alarmLevelConfigList_backup = Object.values(result)
        }).catch(err => {
          //失败
          _this.InfoTip.errorTip(_this, err);
        })
      },

      /**
       *  处理告警配置数据
       */
      handleAlarmConfigList: function () {
        for (let i = 0; i < this.alarmLevelConfigList.length; i++) {
          if (this.alarmLevelConfigList[i].alarmLevel === 0) {
            this.colorValue0 = this.alarmLevelConfigList[i].alarmColor;
            this.colorValue0_backup = this.alarmLevelConfigList[i].alarmColor;
          }
          if (this.alarmLevelConfigList[i].alarmLevel === 1) {
            this.colorValue1 = this.alarmLevelConfigList[i].alarmColor;
            this.colorValue1_backup = this.alarmLevelConfigList[i].alarmColor;
          }
          if (this.alarmLevelConfigList[i].alarmLevel === 2) {
            this.colorValue2 = this.alarmLevelConfigList[i].alarmColor;
            this.colorValue2_backup = this.alarmLevelConfigList[i].alarmColor;
          }
        }
      },

      /**
       *  保存数据
       */
      save: function () {
        this.alertContain = '';
        this.alarmLevelListUpdate = [];
        this.alarmLevelListUpdateNum = 0;
        let alarmLevelChangeIs = false;   //用于判断告警等级的告警颜色是否发生变化
        //判断是否有数据发生修改
        //等级颜色
        for (let i = 0; i < this.alarmLevelConfigList.length; i++) {
          alarmLevelChangeIs = false;
          //判断如果不相等
          if (this.alarmLevelConfigList[i].alarmColor !== this.alarmLevelConfigList_backup[i].alarmColor) {
            this.alarmLevelListUpdate.push(this.alarmLevelConfigList[i]);
            this.alarmLevelListUpdateNum++;
            alarmLevelChangeIs = true;
          }
          if (this.alarmLevelConfigList[i].alarmVoice !== this.alarmLevelConfigList_backup[i].alarmVoice) {
            if (alarmLevelChangeIs === false) {
              this.alarmLevelListUpdate.push(this.alarmLevelConfigList[i]);
              this.alarmLevelListUpdateNum++;
              this.handleAlertContain(this.alarmLevelConfigList[i],1);
            } else {
              this.handleAlertContain(this.alarmLevelConfigList[i],2);
            }
          }else{
            if(alarmLevelChangeIs === true){
              this.handleAlertContain(this.alarmLevelConfigList[i],0);
            }
          }
        }
        if (this.alarmLevelListUpdateNum !== 0) {
          if(this.IsAlarmLevelColorSame(this.alarmLevelConfigList) === true){
            this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.COLOR_SAME_CODE))
          }else{
//            this.$alert(this.alertContain, '修改内容', {
//              confirmButtonText: '确定',
//            });
            let alartContainObject = new Object();
            alartContainObject.message = this.alertContain;

            this.InfoTip.conformTip(this, alartContainObject).then(() => {
              this.updateAlarmLevel();
            }).catch(()=>{

            });
          }
        }else{
          //未修改任何内容！"
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.UNUPDATE_CODE))
        }

      },

      /**
       * 判断告警等级颜色是否相同
       */
      IsAlarmLevelColorSame:function (List) {
       if(List[0].alarmColor === List[1].alarmColor || List[0].alarmColor === List[2].alarmColor || List[2].alarmColor === List[1].alarmColor){
         return true
       }
       return false
      },

      /**
       * 告警信息修改提示内容
       */
      handleAlertContain: function (alarmLevelConfigListOne,type) {
        this.alertContain = this.alertContain + this.alarmLevelTurnName(alarmLevelConfigListOne.alarmLevel);
        //根据type去决定什么样的处理方式，一共三种
        //0，只是修改了颜色
        if(type === 0){
          this.alertContain = this.alertContain + this.$t('AlarmConfigManagement.colorChange') + this.alarmLevelColorTurnName(alarmLevelConfigListOne.alarmColor) + "\n";
        }
        //1，只是修改了声音
        if(type === 1){
          this.alertContain = this.alertContain + this.$t('AlarmConfigManagement.voiceChange') + alarmLevelConfigListOne.alarmVoice;
        }
        //2，修改了颜色和声音
        if(type === 2){
          this.alertContain = this.alertContain + this.$t('AlarmConfigManagement.colorChange') + this.alarmLevelColorTurnName(alarmLevelConfigListOne.alarmColor);
          this.alertContain = this.alertContain + this.$t('AlarmConfigManagement.voiceChange') + alarmLevelConfigListOne.alarmVoice;
        }
      },

      /**
       * 上传修改值
       */
      updateAlarmLevel: function () {
        let _this = this;
        let loadingInstance = _this.Loading.openLoading();
        AlarmManagerService.updateAlarmLevel(this.alarmLevelListUpdate).then(result => {
          //成功
          _this.Loading.closeLoading(loadingInstance);
//          _this.InfoTip.successTip(_this,HelperUtil.getStatusCodeObjectByCode(_this.successCode.MODIFY_CODE));
          this.getAlarmConfigList();
          this.getAlarmConfigList1();
        }).catch(err => {
          //失败
          _this.Loading.closeLoading(loadingInstance);
          _this.InfoTip.errorTip(_this, err);
        })
      },

      /**
       * 上传声音修改值
       */
      updateAlarmLevelVoice: function () {
        this.alertContain = '';
        let _this = this;
        let loadingInstance = _this.Loading.openLoading();
        AlarmManagerService.updateAlarmLevel(this.alarmLevelListUpdate).then(result => {
          //成功
          this.alarmLevelListUpdate = [];
          _this.Loading.closeLoading(loadingInstance);
        }).catch(err => {
          //失败
          _this.Loading.closeLoading(loadingInstance);
          _this.InfoTip.errorTip(_this, err);
        })
      },


      /**
       * 告警等级转换为文字，0：警告，1：严重，2：紧急
       */
      alarmLevelTurnWord: function (row, column) {
        if (row.alarmLevel === 0) {
          return this.$t('AlarmConfigManagement.MinorAlarm')
        } else if (row.alarmLevel === 1) {
          return this.$t('AlarmConfigManagement.MajorAlarm')
        } else if (row.alarmLevel === 2) {
          return this.$t('AlarmConfigManagement.CriticalAlarm')
        }
      },

      /**
       * 告警等级转换为文字
       */
      alarmLevelTurnName: function (alarmLevel) {
        if (alarmLevel === 0) {
          return this.$t('AlarmConfigManagement.MinorAlarm')
        } else if (alarmLevel === 1) {
          return this.$t('AlarmConfigManagement.MajorAlarm')
        } else if (alarmLevel === 2) {
          return this.$t('AlarmConfigManagement.CriticalAlarm')
        }
      },

      /**
       * 告警等级颜色转换为文字
       */
      alarmLevelColorTurnName: function (alarmColor) {
        if (alarmColor === '#FF6347') {
          return this.$t('AlarmConfigManagement.red')
        } else if (alarmColor === '#FFFF00') {
          return this.$t('AlarmConfigManagement.yellow')
        } else if (alarmColor === '#FFA500') {
          return this.$t('AlarmConfigManagement.orange')
        }
      },
    },
    computed: {
      queryNodeTypeChange(){
        this.colorOptions[0].label=this.$t('AlarmConfigManagement.red');
        this.colorOptions[1].label=this.$t('AlarmConfigManagement.yellow');
        this.colorOptions[2].label=this.$t('AlarmConfigManagement.orange');
      }
    },
    watch:{
      '$i18n.locale' () {
        this.queryNodeTypeChange()
      }
    },
  }
</script>

<style lang="scss" scoped>

</style>
