<template>
  <div>
    <Navbar title="上传操作视频" :is-go-back="true" />
    <div class="flex-header">
      <div class="form-inline">
        <div class="form-group">
          <label for="maintenanceSheetName">保养表单名称</label>
          <input
            v-model="maintenanceSheetName" autocomplete="off" class="form-control" placeholder="保养表单名称" aria-describedby="basic-addon1"
            @keyup.enter="getDatas"
          />
        </div>
        <div class="form-group">
          <label for="maintenanceName">保养项目名称</label>
          <input
            v-model="maintenanceName" autocomplete="off" class="form-control" placeholder="保养项目名称" aria-describedby="basic-addon1"
            @keyup.enter="getDatas"
          />
        </div>
        <div class="form-group">
          <a-button type="primary" @click="getDatas">查询</a-button>
        </div>
      </div>
    </div>
    <a-table
      :columns="columns" :data-source="maintenanceDetails"
      :scroll="{ y: 400 }" :pagination="pagination"
    >
      <template #bodyCell="{ column,record }">
        <template v-if="column.dataIndex === 'uploadVideo'">
          <a-button type="primary" @click="showModel(record.key)">上传视频</a-button>
        </template>
      </template>
    </a-table>
    <Modal ref="modal" v-model:show="showModal" :full="true">
      <div>
        <label for="exampleInputFile" class="label-btn">
          上传视频
        </label>
        <input id="exampleInputFile" autocomplete="off" type="file" class="inputfile" @change="uploadFile" />
      </div>
      <hr />
      <div class="row">
        <div v-for="item,index in videoSrcs" :key="index" style="display: table-cell" class="col-xs-3 col-sm-3 col-md-2 col-lg-2">
          <div v-if="item != undefined" class="file-div">
            <div class="file-image-div">
              <div class="fa fa-file-o my-icon" />
              <div class="clearfix" />
            </div>
            <div class="attachment-label">{{ item }}</div>
            <div class="clearfix" />
          </div>
          <div>
            <a role="button" style="display:inline;" class="btn btn-link btn-sm" @click="download(item)">
              <i class="fa fa-download" /> &nbsp;下载
            </a>
            <a role="button" style="display:inline;" class="btn btn-link btn-sm" @click="deleteVideo(index)">
              <i class="fa fa-trash-o" /> &nbsp;删除
            </a>
          </div>
        </div>
      </div>
      <template #header>上传&预览文件</template>
    </Modal>
    <Loading v-if="loading" />
  </div>
</template>

<script>
import Common from '../common/Common.js';
import { SqlApi } from 'pc-component-v3';
import { Notify } from 'pc-component-v3';
import DownloadService from '../common/DownloadService.js';
import MaintenanceSheetLineResource from '../api/pad/MaintenanceSheetLineResource.js';

export default {
  components: {
    DownloadService,
    MaintenanceSheetLineResource,
  },

  data: function() {
    return {
      pagination: {
        pageNo: 1,
        pageSize: 20, // 默认每页显示数量
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: total => `共 ${total} 条`, // 显示总数
        onShowSizeChange: (current, pageSize) => this.onSizeChange(current, pageSize), // 改变每页数量时更新显示
        onChange: (page, pageSize) => this.onPageChange(page, pageSize), //点击页码事件
        total: 0, //总条数
      },
      inventoryInstanceStwc: [],
      maintenanceDetails: [],
      className: 'com.leanwo.prodog.model.pad.MaintenanceSheetLine',
      videoSrcs: [],
      videoList: '',
      maintenanceSheetLineId: undefined,
      showModal: false,
      loading: false,
      columns: [{
        title: '上传视频',
        dataIndex: 'uploadVideo',
        width: 180,
      },
      {
        title: '保养表单名称',
        dataIndex: 'maintenanceSheetName',
        width: 200,
      }, {
        title: '保养项目名称',
        dataIndex: 'maintenanceName',
        width: 200,
      },
      ],
    };
  },
  mounted: function() {
    this.getDatas();
  },

  methods: {

    onPageChange: function(page, pageSize) {
      this.pagination.pageNo = page;
      this.getDatas();
    },
    onSizeChange: function(current, pageSize) {
      this.pagination.pageNo = 1;
      this.pagination.pageSize = pageSize;
      this.getDatas();
    },

    showModel: function(id) {
      var _self = this;
      _self.maintenanceSheetLineId = id;
      this.showModal = true;
      _self.viewFlie();
    },

    /**
       * 修改每页显示的数量
       * @param {Object} newPageSize
       */
    gridSizeSelect: function(newPageSize) {
      this.pagination.per_page = newPageSize;
      this.page = newPageSize;
      this.pagination.current_page = 1;
      // 刷新界面
      this.getDatas();
    },

    getDatas: function() {
      var _self = this;
      _self.maintenanceDetails = [];
      var param = {
        maintenanceName: _self.maintenanceName,
        maintenanceSheetName: _self.maintenanceSheetName,
        start: (_self.pagination.pageNo - 1) * _self.pagination.pageSize,
        length: _self.pagination.pageSize,
      };
      SqlApi.execute('20221104_135826', param).then(
        successData => {
          console.log(successData);
          if (successData.errorCode == 0) {
            successData.dataList.forEach(function(item) {
              var maintenanceSheetLine = {
                key: item.id,
                maintenanceName: item.maintenanceName,
                criteria: item.criteria,
                inspectionName: item.inspectionName,
                maintenanceSheetName: item.maintenanceSheetName,
              };
              _self.maintenanceDetails.push(maintenanceSheetLine);
            });
            _self.pagination.total = successData.total;
            console.log(_self.maintenanceDetails);
          } else {
            Notify.error(
              '查询保养表单明细信息异常',
              successData.errorMessage,
              true,
            );
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },

    /**
       * 查看下载的文件
       * @param {Object} item
       * @author GuoZhiBo 20210107
       */
    viewFlie: function() {
      var _self = this;
      _self.queryVideoListById(_self.maintenanceSheetLineId);

    },

    queryVideoListById: function(maintenanceSheetLineId) {
      var _self = this;
      MaintenanceSheetLineResource.queryVideoListById(maintenanceSheetLineId).then(successData => {
        console.log(successData);
        if (successData.errorCode == 0) {
          _self.videoList = successData.data;
          _self.videoSrcs = [];
          if (_self.videoList != undefined && _self.videoList.length > 0) {
            if (_self.videoList.indexOf(',') == -1) {
              _self.videoSrcs.push(_self.videoList);
            } else {
              _self.videoSrcs = _self.videoList.split(',');
            }
          }
          console.log(_self.videoSrcs);
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },

    /**
       * 上传文件
       */
    uploadFile: function(event) {
      var _self = this;

      let fileList = event.target.files;
      var selectedFile = null;
      if (fileList.length > 0) {
        selectedFile = fileList[0];
      }
      if (selectedFile == null) {
        return;
      }
      var formData = new FormData();
      formData.append('file', selectedFile);
      formData.append('className', _self.className);
      _self.loading = true;
      var attachments = [];
      $.ajax({
        url: Common.getApiURL('file/multipleAttachmentUpload'),
        type: 'post',
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        data: formData,
        contentType: false,
        processData: false,
        success: function(data) {
          _self.loading = false;
          if (data.success) {
            var fileNames = data.fileNames;
            if (fileNames != undefined && fileNames.length > 0) {

              fileNames.forEach(function(item) {
                attachments.push(item.nameAfterSave);
                _self.saveFile(attachments);
              });
              console.log(fileNames);
            }
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
       * 保存视频地址
       */
    saveFile: function(fileNames) {
      var _self = this;
      var videoSrcs = [];
      if (_self.videoList != undefined && _self.videoList.length > 0) {
        if (_self.videoList.indexOf(',') == -1) {
          videoSrcs.push(_self.videoList);
        } else {
          videoSrcs = _self.videoList.split(',');
        }
      }
      videoSrcs.push(fileNames);
      var videoListStr = videoSrcs.join(',');
      var maintenanceSheetLineDto = {
        maintenanceSheetLineId: _self.maintenanceSheetLineId,
        videoListStr: videoListStr,
      };
      if (maintenanceSheetLineDto != null) {
        MaintenanceSheetLineResource.saveFile(maintenanceSheetLineDto).then(successData => {
          console.log(successData);
          if (successData.errorCode == 0 && successData.data != null) {
            _self.viewFlie();
          }
        }, errorData => {
          Common.processException(errorData);
        });
      } else {
        Common.showDialog('提示', '请选择要保存的单据', 'error');
      }
    },

    /**
       * 下载附件
       * @param {Object} item
       * @author LiangZhiCheng 20220920
       */
    download: function(item) {
      var _self = this;
      var url = Common.getApiURL('file/fileDownload') + '?className=' + _self.className
        + '&fileName=' + window.encodeURIComponent(item);
      var a = document.createElement('a');
      a.setAttribute('href',url);
      a.setAttribute('download',item);
      a.click();
    },

    /**
       * 删除视频
       *@author LiangZhiCheng 20220920
       */
    deleteVideo(index) {
      var _self = this;
      _self.videoSrcs.splice(index, 1);
      _self.saveFileVideo();
      Common.showDialog('提示', '删除成功', 'success');
    },

    saveFileVideo: function() {
      var _self = this;
      var videoListStr = _self.videoSrcs.join(',');
      var maintenanceSheetlineDto = {
        maintenanceSheetLineId: _self.maintenanceSheetLineId,
        videoListStr: videoListStr,
      };
      if (maintenanceSheetlineDto != null) {
        MaintenanceSheetLineResource.saveFile(maintenanceSheetlineDto).then(successData => {
          if (successData.errorCode == 0 && successData.data != null) {
            _self.viewFlie();
          }
        }, errorData => {
          Common.processException(errorData);
        });
      } else {
        Common.showDialog('提示', '请选择要删除的单据', 'error');
      }
    },
  },
};
</script>

<style scoped>
  .flex-container {
    display: flex;
    /* 垂直*/
    flex-direction: column;
    width: 100%;
    /*视口被均分为100单位的vh 占据整个窗口，扣掉顶部topNav的距离后，计算得到container的高度*/
    height: calc(100vh - 150px);
  }

  .flex-content {
    flex: 1;
    overflow: scroll;
    width: 100%;
    height: 0;
  }

  .fixed-table {
    table-layout: fixed;
    width: 800px !important;
    min-width: 800px !important;
  }

  table.fixed-table tr {
    height: 40px;
  }

  table.fixed-table th,
  table.fixed-table td {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .flex-header {
    height: 80px;
    /*放大缩小比例为0 */
    flex: 0 0 100px;
  }

  .flex-footer {
    margin-top: 0.8em;
    height: 35px;
    /*放大缩小比例为0 */
    flex: 0 0 35px;
  }

  .form-inline .form-group button {
    width: 250px;
    text-align: center;
    margin: 30px;
  }

  .form-inline .form-group label {
    width: 100px;
    text-align: right;
    padding-right: 5px;
  }

  .form-inline .form-group input,
  .form-inline .form-group select {
    width: 200px;
  }

  .file-image-div {
    width: 150px;
    height: 120px;
    text-align: center;
  }

  .my-icon {
    font-size: 100px !important;
    padding: 10px;
  }

  .attachment-label {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-size: small;
    max-width: 150px;
  }

  .attachment-label:hover {
    text-overflow: inherit;
    overflow: visible;
  }
</style>
