<template>
  <div>
    <Row>
      <!--操作-->
      <Col span="24" style="margin-bottom: 10px">
        <div class="btns-menu">
          <!--查看方式-->
          <Select v-model="viewVal" @on-change="_view" style="width:150px;float: left" placeholder="请选择查看方式">
            <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"
              style="float: left">
              <Button>上传</Button>
            </Upload>
          </label>
          <Button @click="_batchUpload">批量上传</Button>
          <!--一系列操作-->
          <!--非表格-->
<!--          <Button  v-if="viewStyle === 2 || viewStyle === 3" v-for="item in menusListA" :key="item.name" @click="_radioChange(item.value)"-->

<!--          >{{item.name}}-->
<!--          </Button>-->
<!--          &lt;!&ndash;表格&ndash;&gt;-->
<!--          <Button   v-if="viewStyle === 1"  v-for="item in menusList" :key="item.name" @click="_tableChange(item.value)"-->
<!--                 style="margin-right: 5px">{{item.name}}-->
<!--          </Button>-->
        </div>
      </Col>

      <Col span="24" style="margin-bottom: 10px">
        <!-- 默认是详细模式 -->
        <div v-show="viewStyle === 1">
          <PTVXETable ref="pageTable" :pageColumns="pageColumns" :tableHeight="tableHeight"
                      @on-result-change="_tableResultChange" :getPage="getPage" select-data>
            <vxe-table-column
              :field="item.key"
              :title="item.title"
              :min-width="item.width?item.width:200"
              :fixed="item.fixed?item.fixed:undefined"
              v-for="item in pageColumns"
              :key="item.key" sortable>
              <template slot-scope="scope">
                <span v-if="item.dateTime">{{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM'):''}}</span>
                <span v-else>{{scope.row[item.key]}}</span>
              </template>
            </vxe-table-column>
            <vxe-table-column
              title="操作"
              align="center"
              width="100"
              fixed="right">
              <template slot-scope="scope">
                <VXEIconList
                  :msg="iconMsg"
                  @on-result-change="_iconClick" :rowData="scope.row"></VXEIconList>
              </template>
            </vxe-table-column>
          </PTVXETable>
        </div>
        <!--/-->
        <!--缩略图 模式-->
        <div v-show="viewStyle === 2">
          <ul :style="{ 'height': 'auto' }" class="thumbnailStyle">
            <CheckboxGroup @on-change="_chkVal" v-model="selectIds">
              <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-show="viewStyle === 3">
          <ul :style="{ 'height': 'auto' }" class="listStyle">
            <CheckboxGroup @on-change="_chkVal" v-model="selectIds">
              <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>
    <BatchUpload ref="batchUpload" @on-result-change="_page"></BatchUpload>
    <BatchUploadSample ref="batchUploadSample" @on-result-change="_page"></BatchUploadSample>
    <!--上传loading-->
    <div v-show="isLoad">
      <Spin fix>
        <Icon type="load-c" size=18 class="file-spin-icon-load"></Icon>
        <div>正在上传,请稍后...</div>
      </Spin>
    </div>
    <!--图片预览-->
<!--    <div>-->
<!--      <vue-gallery-slideshow :images="imgViewList" :index="imgViewIndex"-->
<!--                             @close="imgViewIndex = null"></vue-gallery-slideshow>-->
<!--    </div>-->

  </div>
</template>
<script>
// import VueGallerySlideshow from 'vue-gallery-slideshow'
import global from '../../../api/config'
import { meterEntrust } from '../../../api'
import BatchUpload from './BatchUpload'
import BatchUploadSample from './BatchUploadSample'
/**
 * 公共组件modal 弹框（支持上传，下载，预览，删除附件等操作）
 */
export default {
  components: { BatchUpload, BatchUploadSample },
  props: {
    fileName: null
  },
  data() {
    return {
      imgViewList: [],
      imgViewIndex: null,
      iconMsg: [
        { type: 'md-remove-circle', id: '', name: '删除' },
        { type: 'ios-download', id: '', name: '下载' }
        // { type: 'ios-eye', id: '', name: '预览' }
      ],
      iconMsgDis: [
        { type: 'trash-a', id: '', name: '删除' },
        { type: 'ios-download', id: '', name: '下载' },
        { type: 'images', id: '', name: '预览', disabled: true }
      ],
      selectIds: [],
      getPage: {},
      pageColumns: [
        { title: '文件名', key: 'fileName' },
        { title: '类型', key: 'type', width: 120 },
        { title: '上传时间', key: 'ctime', width: 140, dateTime: true }
        // {title: '上传人', key: 'cname', width: 120},
      ],
      formObj: {
        contractId: undefined,
        entrustId: undefined
      },
      viewVal: 1,
      viewStyle: 1,
      menusList: [
        { name: '下载', value: 'down' },
        { name: '删除', value: 'delete' }
      ],
      menusListA: [{ name: '删除', value: 'delete' }],
      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
      objectKey: [],
      urlData: {},
      idsObj: {}
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('tableModal')
    }
  },
  methods: {
    _batchUpload() {
      if (this.formObj.aloneSampleId) {
        this.$refs.batchUploadSample._open(this.id)
      } else {
        this.$refs.batchUpload._open(this.id)
      }
    },
    _setUploadData(data, idsObj, idKey) {
      this.selectIds = []
      this.imgViewIndex = null
      this.isLoad = false
      this.id = data.id
      const pageKey = idKey
      console.log(pageKey)
      this.$set(this.formObj, pageKey, data.id)
      console.log(this.formObj)
      // this.formObj.contractId = data.id
      // this.formObj.entrustId = data.id
      // 各个ids
      this.idsObj = idsObj
      this.urlData = data
      this.action = global.baseURL + data.uploadFileUrl + data.id
      this.$nextTick(() => {
        this._page()
      })
    },
    _page: async function(fileName) {
      if (fileName) {
        this.formObj.fileName = fileName
      } else {
        this.formObj.fileName = undefined
      }
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      const result = await meterEntrust.attachmentPage(
        this.urlData.pageUrl,
        this.formObj
      )

      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    // _page: async function() {
    //   Object.assign(this.formObj, this.$refs.pageTable._searchParams())
    //   console.log('this.formObj', this.formObj)
    //   const result = await meterEntrust.attachmentPage(this.formObj)
    //   console.log('请求结果', result)
    //   if (result) {
    //     console.log(result)
    //     this.$refs.pageTable._hideLoading()
    //     this.getPage = result
    //   }
    // },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _searchParams() {
      const data = {}
      Object.assign(data, { fileName: this.fileName }, this.idsObj)
      return data
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this.Ids = []
          this.objectKey = []
          this.getPage = this.$store.state[this.urlData.msg].page
          break
        case 'selectData':
          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
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData)
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _iconClick(res, data) {
      switch (res) {
        case '下载':
          window.open(
            global.baseURL + this.urlData.downloadFileUrl + data.id,
            '_blank'
          )
          break
        case '删除':
          this._deleteById([data.id])
          break
        case '预览':
          this._viewImg(data)
          break
      }
    },
    // 预览图片（该合同下所有的）
    _viewImg: async function(data) {
      console.log(data)
      if (this.urlData.viewUri === '/meter/v1/entrust_attachment/preview/') {
        const id = data.entrustId
        const result = await meterEntrust.entrustPreview(id)
        console.log(result)
      } else {
        const id = data.contractId
        const result = await meterEntrust.attachmentPreview(id)
        console.log(result)
      }

      // this.$store.dispatch(this.urlData.uri, this.id).then(() => {
      //   const viewUri = this.urlData.viewUri
      //   const result = this.$store.state[this.urlData.msg].list
      //   const imgViewList = []
      //   for (let i = 0; i < result.length; i++) {
      //     imgViewList.push(
      //       global.baseURL +
      //         viewUri +
      //         '?id=' +
      //         result[i].id +
      //         '&objectKey=' +
      //         result[i].objectKey
      //     )
      //   }
      //   this.imgViewList = imgViewList
      //   // 打开的是当前第几张图片
      //   const salesUri =
      //     global.baseURL +
      //     viewUri +
      //     '?id=' +
      //     data.id +
      //     '&objectKey=' +
      //     data.objectKey
      //   const index = this.imgViewList.findIndex(item => item === salesUri)
      //   if (index === -1) {
      //     this.imgViewIndex = 0
      //   } else {
      //     this.imgViewIndex = index
      //   }
      // })
    },
    // 删除
    _deleteById(id) {
      this.$emit('on-result-change', 'delete', id)
    },
    // 查看方式改变
    _view(val) {
      this.viewStyle = val
      this.selectIds = []
      if (val === 1) {
        this._formSearch()
      }
    },
    _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.objectKey.length === 0) {
          this.$Message.warning('请至少选择一条数据!')
        } else {
          this._downloadAll(this.objectKey)
        }
      }
      if (val === 'delete') {
        if (this.Ids.length === 0) {
          this.$Message.warning('请至少选择一条数据!')
        } else {
          this._deleteById(this.Ids)
        }
      }
    },
    // 批量打包下载
    _downloadAll(ids) {
      window.open(
        global.baseURL + this.urlData.downloadBatch + '?objectKeys=' + 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._page()
      } else {
        this.isLoad = true
        this.$Message.error(response.msg)
        this.isLoad = false
      }
    }
  }
}
</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-wrapper:last-child {
  border-radius: 4px !important;
  border-left: 1px solid #dddee1 !important;
}
</style>
