<!--计量语音配置-->
<template>
  <div class="systemBase">
    <div>
      <div class="common-title-div">计量语音配置
        <div class="common-operation-button-div">
          <el-button icon="el-icon-circle-plus-outline" type="primary" size="mini" v-loading.fullscreen.lock="operateLoading"
           @click="addData" v-privilege="activeMenu + 'ADD'">新增</el-button>
          <el-button icon="el-icon-edit" type="primary" size="mini" v-loading.fullscreen.lock="operateLoading"
          @click="modifyData" v-privilege="activeMenu + 'UPDATE'">修改</el-button>
          <el-button size="mini" type="primary" icon="el-icon-check" v-loading.fullscreen.lock="operateLoading"
           @click="recoveryData" v-privilege="activeMenu + 'RECOVERY'">启用</el-button>
          <el-button size="mini" type="danger" plain icon="el-icon-remove-outline" v-loading.fullscreen.lock="operateLoading"
           @click="abolishData" v-privilege="activeMenu + 'ABOLISH'">废除</el-button>
        </div>
      </div>
      <div class="common-table-div">
        <el-table ref="dataTable"  @row-click="rowChange" border :height="tableHeight" highlight-current-row
          @selection-change="handleSelectionChange" :data="table.list" :row-class-name="tableRowClassName"
          :exchangeFilterMap="{'validFlag':{'0':'无效','1':'有效'}}"
          :icore-filter-flag="icoreFilterFlag">
          <el-table-column type="index" label="序号" fixed="center" align="center"></el-table-column>
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="voiceNo" label="语音编号" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="voiceName" label="语音名称" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="150px" prop="voiceFileName" label="文件名称" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="voiceFileType" label="文件类型" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="200px" prop="voiceFileUrl" label="文件存放地址" align="left"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="validFlag" label="状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.validFlag == 1">有效</span>
              <span v-else-if="scope.row.validFlag == 0">无效</span>
            </template>
          </el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="60px" prop="voiceEdition" label="版本号" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="createManName" label="创建人" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="150px" prop="createTime" label="创建时间" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="updateManName" label="修改人" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="150px" prop="updateTime" label="修改时间" align="center"></el-table-column>
        </el-table>
      </div>
      <div class="common-foot-style">
       <el-pagination v-loading="dataLoading" @size-change="pageSizeChange" @current-change="pageCurrentChange"
          :current-page="page.pageNum" :page-sizes="[100, 500, 1000]" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalPage">
        </el-pagination>
      </div>
      <!-- <div ref="editTitle" class="common-title-div" style="border-top: 1px solid #d5d5d5;">编辑区
      </div> -->
      <div ref="editDiv" class="commom-edit-div" style="border-top: 1px solid #d5d5d5; margin-top: 10px">
        <el-form ref="baseData" label-width="80px" :inline="true" :rules="ruleValidate" :model="baseData">
              <el-form-item prop="voiceName" label="语音名称">
                <el-input v-model="baseData.voiceName" size="small"  clearable placeholder="请输入"  style="width:120px"></el-input>
              </el-form-item>
              <el-form-item prop="voiceFileName" label="文件名称">
                <el-input v-model="baseData.voiceFileName" size="small"  style="width:120px" placeholder="" readonly disabled></el-input>
              </el-form-item>
              <el-form-item>
                <el-upload
                  class="upload"
                  action=""
                  :multiple="false"
                  :show-file-list="false"
                  accept=""
                  :http-request="httpRequest">
                  <el-button size="small">浏览</el-button>
               </el-upload>
              </el-form-item>
              <el-form-item prop="voiceFileType" label="文件类型">
                <el-input v-model="baseData.voiceFileType" size="small"  style="width:120px" placeholder="" readonly disabled></el-input>
              </el-form-item>
            <!-- <el-col :span="5">
              <el-form-item prop="voiceFileUrl" label="文件存放地址">
                <el-input v-model="baseData.voiceFileUrl" size="small" placeholder="" readonly disabled></el-input>
              </el-form-item>
            </el-col> -->
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
 import {
   meterbasevoices,
   download
  } from '../../../utils/api.js';
 import {
    discard,
    Recovery,
    add,
    modify
  } from '../../../utils/httpRequest.js';
  import pinyinUtils from '../../../utils/pinyin/pinyinUtils.js';
  // import axios from '@/config/axios.js'
  import axios from 'axios'
  import {
  getCookie
} from '@/utils/util.js';
import {
  cookieUserId,
  cookieUserName
} from '@/config/config.js';
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
  export default {
    data () {
      return {
        dataLoading: false,
        operateLoading: false,
        icoreFilterFlag: true,
        baseData: {
          voiceName: '',
          voiceFileName: '',
        //   carrierUnitName: '',
          voiceFileType: '',
          voiceFileUrl: ''
          // carrierUnitType: '0'
        },
        page: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        table: {
          list: [],
          list1: []
        },
        multipleSelection: [],
        file: [],
        tableHeight: 0,
        ruleValidate: {
          voiceName: [{
            required: true,
            message: '语音名称不能为空',
            trigger: 'change'
          }],
          voiceFileName: [{
            required: true,
            message: '文件名称不能为空，请点击浏览按钮选择文件！',
            trigger: 'change'
          }],
          voiceFileType: [{
            required: true,
            message: '文件类型不能为空，请点击浏览按钮选择文件！',
            trigger: 'change'
          }],
          voiceFileUrl: [{
            required: true,
            message: '文件存放地址不能为空，请点击浏览按钮选择文件！',
            trigger: 'change'
          }]
        },
        activeMenu: ''
      }
    },
    created(){
      this.tableHeight = (window.innerHeight - 220) > 500 ? (window.innerHeight - 220) : 500 ;
      this.activeMenu = window.top.localStorage.getItem('activeMenu')
    },
    mounted () {
      // this.tableHeight = this.getTableHeight(this.$refs['dataTable'].$el) - 80;
      this.getDataList();
    },
    methods: {
      rowChange (row, column, event) {
         this.baseData = Object.assign ({}, row);
      },
       addData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
          _this.operateLoading = true;
          let baseDataAdd = {}
          baseDataAdd.voiceName = _this.baseData.voiceName
          baseDataAdd.voiceFileName = _this.baseData.voiceFileName
          baseDataAdd.voiceFileType = _this.baseData.voiceFileType
          baseDataAdd.voiceFileUrl = _this.baseData.voiceFileUrl
          baseDataAdd.createManName = userName;
          baseDataAdd.createManNo = userId;
          // let obj = {baseData: _this.baseData}
          let obj = JSON.stringify(baseDataAdd)
           add(meterbasevoices, baseDataAdd, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          // let uploadFile = new FormData()
          // uploadFile.append('model', obj)
          // uploadFile.append('file', _this.file)
          // let config = {
          //   headers: {
          //     'Content-Type': 'multipart/form-data'
          //   }
          // }
          //  _this.axios.post('pass/systemBase/v1/meterbasevoices/', uploadFile, config).then(res => {
          //     // console.log(res, 'res..')
          //      _this.getDataList();
          //     if (res.succeed) {
          //       this.$message.success('新增成功');
          //       _this.getDataList();
          //       _this.file = [];
          //       } else {
          //         this.$message.error(res.message)
          //       }
          //       }).catch(e => {
          //         this.$message.error(e.message)
          //         })
          }
        });
      },
      // voiceNameIsRepeat (rule, value, callback) {
      //   console.log(this.baseData.voiceName)
      //   if (this.baseData.voiceName) {
      //    for (let i = 0; i < this.table.list1.length; i++) {
      //     if (this.baseData.voiceName === this.table.list1[i].voiceName) {
      //       console.log(1)
      //       callback(new Error('名称不允许重复！'))
      //     }
      //    }
      //     callback()
      //   } else {
      //     callback()
      //   }
      //   if (!patrn.test(this.baseData.upperLimitWeight)) {
      //     callback(new Error('请输入正确的格式！'))
      //   } else if (Number (this.baseData.upperLimitWeight) >= 1000) {
      //     callback(new Error('请输入正确的格式！'))
      //   } else{
      //     callback()
      //  }
      // },
      modifyData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
            _this.operateLoading = true;
            modify(meterbasevoices + _this.baseData.voiceNo + '/', _this.baseData, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      recoveryData () {
        let _this = this;
        _this.operateLoading = true;
        Recovery(meterbasevoices + 'Recovery', _this.multipleSelection, (e) => {
          _this.operateLoading = false;
          if (!e) {
            _this.getDataList();
          }
        });
      },
      abolishData () {
        let _this = this;
        _this.operateLoading = true;
        discard(meterbasevoices + 'abolish', _this.multipleSelection, (e) => {
          _this.operateLoading = false;
          if (!e) {
            _this.getDataList();
          }
        });
      },
      httpRequest: function (e) {
        let _this = this;
        let file = e.file;
        if (!file) {
          // 没有文件
           return false
        } else if (!/\.(wav|cda|mp3|mp3pro|wma)$/.test(file.name.toLowerCase())) {
          // 格式根据自己需求定义
          this.$message.error('上传文件格式不正确，请上传音频文件！')
          return false
        }
        let arr = file.name.split('.');
        _this.file = file;
        _this.baseData.voiceFileName = arr[0];
        _this.baseData.voiceFileType = arr[1];
        let uploadFile = new FormData()
        uploadFile.append('file', _this.file)
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        _this.axios.post('pass/systemBase/v1/download/testSingleUpload', uploadFile, config).then(res => {
           if (res.succeed) {
             _this.baseData.voiceFileUrl = res.data
           } else {
            this.$message.error(res.message)
           }
           }).catch(e => {
            this.$message.error(e.message)
          })
      },
      handleSelectionChange (val) {
        this.multipleSelection = val;
      },
      getTableHeight (dom) {
        return (window.innerHeight - dom.offsetTop);
      },
      pageSizeChange (size) {
        this.page.pageSize = size;
        this.getDataList();
      },
      tableRowClassName ({
        row,
        rowIndex
      }) {
        if (row.validFlag !== '1') {
          return 'error-row2';
        }
        return '';
      },
      pageCurrentChange (index) {
        this.page.pageNum = index;
        this.getDataList();
      },
      getDataList () {
        this.dataLoading = true;
        this.axios.get(meterbasevoices + '?pageNum=' + this.page.pageNum + '&pageSize=' + this.page.pageSize)
          .then(res => {
            this.dataLoading = false;
            this.table.list = res.data.list;
            this.table.list1 = res.data.list;
            this.page.totalPage = res.data.total;
          }).catch(e => {
            this.dataLoading = false;
          });
      },
      myBlur () {
        if (this.baseData.voiceName) {
          this.baseData.mnemonicCode = pinyinUtils.initial(this.baseData.voiceName);
        }
      }
    }
  }
</script>

<style scoped>
  .el-select {
    width: 100%;
  }
</style>
