<template>
  <div>
    <Row>
      <!--操作-->
      <Col span="24" style="margin-bottom: 10px" />
      <div class="btns-menu">
        <!--查看方式-->
        <Select v-model="viewVal" style="width:150px" placeholder="请选择查看方式" @on-change="_view">
          <Option v-for="item in checkList" :key="item.value" :value="item.value">
            {{ item.name }}
          </Option>
        </Select>
        <!--上传-->
        <label>
          <Upload
            :action="action"
            :on-success="_handelsuccess"
            :before-upload="_beupload"
            :on-progress="_handelprogress"
            :data="dataObj"
            :with-credentials="true"
            :show-upload-list="false"
          >
            <Button>
              <Icon type="ios-upload" />&nbsp;上传
            </Button>
          </Upload>
        </label>
        <!--一系列操作-->
        <!--非表格-->
        <Button
          v-for="item in menusListA"
          v-show="viewStyle === 2 || viewStyle === 3"
          :key="item.name"
          @click="_radioChange(item.value)"
        >
          <Icon :type="item.type" />&nbsp;{{ item.name }}
        </Button>
        <!--表格-->
        <Button
          v-for="item in menusList"
          v-show="viewStyle === 1"
          :key="item.name"
          style="margin-right: 5px"
          @click="_tableChange(item.value)"
        >
          <Icon :type="item.type" />&nbsp;{{ item.name }}
        </Button>
      </div>
      </Col>

      <Col span="24" style="margin-bottom: 10px" />
      <!-- 默认是详细模式 -->
      <div v-if="viewStyle === 1">
        <el-table
          ref="moveTable"
          v-loading="loading"
          stripe
          border
          size="small"
          highlight-current-row
          :data="getPage.records"
          style="width: 100%"
          :height="tableHeight"
          @select-all="_selectAll"
          @selection-change="_selectRowChange"
          @cell-click="_cellClick"
        >
          <el-table-column
            type="selection"
            width="55"
            fixed="left"
            align="center"
          />
          <el-table-column
            v-for="item in pageColumns"
            :key="item.key"
            show-overflow-tooltip
            sortable
            :prop="item.key"
            :label="item.title"
            :width="item.width"
          >
            <template slot-scope="scope">
              <span v-if="item.dateTime">{{ scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM:ss'):'' }}</span>
              <span v-else>{{ scope.row[item.key] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="100"
            fixed="right"
          >
            <template slot-scope="scope">
              <IconList
                :msg="(scope.row['type'] === 'jpg' || scope.row['type'] === 'png')?iconMsg:iconMsgDis"
                :row-data="scope.row"
                @on-result-change="_iconClick"
              />
            </template>
          </el-table-column>
        </el-table>
        <Page
          :total="getPage.total"
          :page-size="getPage.size"
          :current="getPage.current"
          placement="top"
          show-elevator
          show-total
          show-sizer
          style="margin-top: 10px;"
          @on-change="_pageChange"
          @on-page-size-change="_pageSizeChange"
        />
      </div>
      <!--/-->
      <!--缩略图 模式-->
      <div v-else-if="viewStyle === 2">
        <ul class="thumbnailStyle" :style="{ 'height': tableHeight + 'px' }">
          <CheckboxGroup v-model="selectIds" @on-change="_chkVal">
            <li v-for="item in getPage.records" :key="item.id">
              <div class="thumbnailStyleImg">
                <Tooltip placement="top">
                  <img :src=" bigUrl+item.type+'.png' ">
                  <div slot="content" style="white-space: normal">
                    <p>名称：{{ item.fileName }}</p>
                  </div>
                </Tooltip>
              </div>
              <div class="thumbnailStyleCheck clearCheck">
                <Checkbox :label="item.id">
                  <span class="inline-span" style="display: inline">{{ item.fileName }}</span>
                </Checkbox>
              </div>
            </li>
          </CheckboxGroup>
        </ul>
        <div style="margin-top: 10px">
          共 {{ getPage.total }} 条
        </div>
      </div>
      <!--/-->
      <!--列表 模式-->
      <div v-else-if="viewStyle === 3">
        <ul class="listStyle" :style="{ 'height': tableHeight + 'px' }">
          <CheckboxGroup v-model="selectIds" @on-change="_chkVal">
            <li v-for="item in getPage.records" :key="item.id">
              <div class="listStyleCheck clearCheck">
                <Tooltip placement="top">
                  <span class="spanImg">
                    <img :src=" smallUrl+item.type+'.png' ">
                  </span>
                  <span>
                    <Checkbox :label="item.id"><span>{{ item.fileName }}</span></Checkbox>
                  </span>
                  <div slot="content" style="white-space: normal">
                    <p>名称：{{ item.fileName }}</p>
                  </div>
                </Tooltip>
              </div>
            </li>
          </CheckboxGroup>
        </ul>
        <div style="margin-top: 10px">
          共 {{ getPage.total }} 条
        </div>
      </div>
        <!--/-->
      </Col>
    </Row>
    <!--上传loading-->
    <div v-show="isLoad">
      <Spin fix>
        <Icon type="load-c" size="18" class="file-spin-icon-load" />
        <div>正在上传,请稍后...</div>
      </Spin>
    </div>
    <!--图片预览-->
    <div>
      <vue-gallery-slideshow
      :images="imgViewList"
      :index="imgViewIndex"
      @close="imgViewIndex = null"
      ></vue-gallery-slideshow>
    </div>
  </div>
</template>
<script>
/* eslint-disable prettier/prettier */

import global from '../../api/config'
import IconList from './IconList'

export default {
  components: { IconList },
  data: function() {
    return {
      imgViewList: [],
      imgViewIndex: null,
      loading: false,
      iconMsg: [
        { type: 'pt-a-trash', id: '', name: '删除' },
        { type: 'pt-a-download', id: '', name: '下载' },
        { type: 'pt-a-view', id: '', name: '预览' }
      ],
      iconMsgDis: [
         {type: 'pt-a-trash', id: '', name: '删除'},
        { type: 'pt-a-download', id: '', name: '下载' },
        { type: 'pt-a-view', id: '', name: '预览', disabled: true }
      ],
      heightSearch: '',
      selectIds: [],
      getPage: {},
      pageParams: {
        rows: 20
      },
      pageColumns: [
        { title: '文件名', key: 'fileName' },
        { title: '类型', key: 'type', width: 120 },
        { title: '上传时间', key: 'ctime', width: 140, dateTime: true }
        // {title: '上传人', key: 'cname', width: 120},
      ],
      viewVal: 1,
      viewStyle: 1,
      menusList: [
        { name: '下载', value: 'down', type: 'arrow-down-a' },
        { name: '删除', value: 'delete', type: 'trash-a' }
      ],
      menusListA: [
        //  {name: '删除', value: 'delete', type: 'trash-a'},
      ],
      checkList: [
        { name: '详细模式', value: 1 },
        { name: '缩略图模式', value: 2 },
        { name: '列表模式', value: 3 }
      ],
      Ids: [],
      smallUrl: `${global.staticURL}/img/smallfile/`,
      bigUrl: `${global.staticURL}/img/bigfile/`,

      action: '',
      dataObj: {
        file: ''
        // contractId: ''
      },
      isLoad: false, // 是否显示loading...
      id: '', // 合同、委托、样品id
      idKey: '', // 判断是哪种附件（合同、委托、样品）
      objectKey: [],
      downloadFileUrlFile: ''
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('tableModal')
    }
  },
  methods: {
    // 点击单元格触发
    _cellClick(row, event, column) {
      if (event.label !== '操作') {
        this.$refs.moveTable.toggleRowSelection(row)
      }
    },
    _iconClick(res, data) {
      switch (res) {
        case '下载':
          this._download(data.id)
          break
        case '删除':
          this._deleteById([data.id])
          break
        case '预览':
          this._viewImg(data)
          break
      }
    },
    // 预览图片（该合同下所有的）
    _viewImg(data) {
      // let uri = ''
      // let viewUri = ''
      // switch (this.idKey) {
      //   case 'contractId':
      //     uri = 'FoodContractAttachment/getByContractId'
      //     viewUri = 'contract_attachment/view'
      //     break
      //   case 'sampleId':
      //     uri = 'FoodSampleAttachment/getBySampleId'
      //     viewUri = 'sample_attachment/view'
      //     break
      //   case 'subcontractorId':
      //     uri = 'FoodSubContractAttachment/getBySubcontractorId'
      //     viewUri = ' '
      //     break
      // }

      // 单张显示
      const imgViewList = []
      imgViewList.push(global.baseURL + this.downloadFileUrlFile + data.id)
      this.imgViewList = imgViewList
      this.imgViewIndex = 0
      // 多张显示
      // this.$store.dispatch(uri, this.id).then(() => {
      //   let result = '';
      //   if (this.idKey === 'contractId') {
      //     //委托
      //     result = this.$store.state.ManufactContractAttachment.list;
      //   } else {
      //   }
      //   let imgViewList = [];
      //   for (let i = 0; i < result.length; i++) {
      //     imgViewList.push(global.baseURL + '/wjl/v1/' + viewUri + '?id=' + result[i].id + '&objectKey=' + result[i].objectKey);
      //   }
      //   this.imgViewList = imgViewList;
      //   //打开的是当前第几张图片
      //   let salesUri = global.baseURL + '/wjl/v1/' + viewUri + '?id=' + data.id + '&objectKey=' + data.objectKey;
      //   let index = this.imgViewList.findIndex((item) => item === salesUri);
      //   if (index === -1) {
      //     this.imgViewIndex = 0;
      //   } else {
      //     this.imgViewIndex = index;
      //   }
      // });
    },
    _open(data, height) {
      this.getPage = data
      this.selectIds = []
    },
    _setUploadData(data, idKey) {
      this.idKey = idKey
      this.isLoad = false
      this.id = data.id
      this.action = global.baseURL + data.uploadFileUrl + data.id
      this.downloadFileUrlFile = data.downloadFileUrl
    },
    _pageChange(page) {
      this.$emit('on-result-change', 'page', page)
    },
    _selectRowChange(data) {
      const idList = []
      const objectKey = []
      for (let i = 0; i < data.length; i++) {
        idList.push(data[i].id)
        objectKey.push(data[i].objectKey)
      }
      this.Ids = idList
      this.objectKey = objectKey
    },
    _selectAll: function(data) {
      this._selectRowChange(data)
    },
    _pageSizeChange(rows) {
      this.$emit('on-result-change', 'rows', rows)
    },
    // 删除
    _deleteById(id) {
      this.$emit('on-result-change', 'delete', id)
    },
    // 下载
    _download(id) {
      this.$emit('on-result-change', 'down', id)
    },
    // 查看方式改变
    _view(val) {
      this.viewStyle = val
      this.selectIds = []
    },
    _chkVal(val) {
      this.selectIds = val
    },
    // 一系列操作返回的值
    _radioChange(val) {
      if (val === 'down') {
        if (this.objectKey.length === 0) {
          this.$Message.warning('请至少选择一条数据!')
        } else {
          this._downloadAll(this.objectKey)
        }
      }
      if (val === 'delete') {
        if (this.selectIds.length === 0) {
          this.$Message.warning('请选择一条数据!')
        } else {
          this._deleteById(this.selectIds)
        }
      }
    },
    _tableChange(val) {
      if (val === 'down') {
        if (this.Ids.length === 0) {
          this.$Message.warning('请至少选择一条数据!')
        } else {
          this._downloadAll(this.Ids)
        }
      }
      if (val === 'delete') {
        if (this.Ids.length === 0) {
          this.$Message.warning('请选择一条数据!')
        } else {
          this._deleteById(this.Ids)
        }
      }
    },
    // 批量打包下载
    _downloadAll(ids) {
      let uri = ''
      switch (this.idKey) {
        case 'contractId':
          uri = '/wjl/v1/contract_attachment/download_batch'
          break
        case 'sampleId':
          uri = '/llgt/v1/sample_attachment/download_batch'
          break
        case 'subcontractorId':
          uri = '/food/v1/subcontractor_attachment/download_batch'
          break
        case 'partId':
          uri = '/wjl/v1/sample_part_attachment/download_batch'
      }
      window.open(global.baseURL + uri + '?ids=' + ids)
    },
    _beupload(file) {
      this.dataObj.file = file.name
    },
    _handelprogress(event, file, fileList) {
      this.isLoad = true
    },
    _handelsuccess(response, file, fileList) {
      // 上传成功
      if (response.success) {
        this.isLoad = false
        this.$Message.success('上传成功！')
        this.$emit('on-result-change', 'refresh')
      } else {
        this.isLoad = true
        this.$Message.error(response.msg)
      }
    }
  }
}
</script>
<style>
.radio-display.ivu-radio-group-button .ivu-radio-wrapper:first-child {
  border-radius: 4px !important;
  margin-right: 5px !important;
}

.radio-display.ivu-radio-group-button .ivu-radio-wrapper:last-child {
  border-radius: 4px !important;
  border-left: 1px solid #dddee1 !important;
}
.thumbnailStyle li {
  float: left;
  margin: 10px 5px;
}
.thumbnailStyle,
.listStyle {
  overflow: hidden;
  padding: 10px;
  border: 1px dashed #666;
  border-radius: 4px;
  -webkit-border-radius: 4px;
}
.listStyleCheck {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.thumbnailStyleCheck {
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.thumbnailStyleImg {
  width: 90px;
  height: 90px;
  line-height: 90px;
  text-align: center;
  border: 1px solid #ddd;
  margin-bottom: 5px;
}
.btns-menu .ivu-upload {
  display: inline;
}
</style>
