<template>
  <div class="playerList">
    <!-- <div class="top">
      <div class="playBody">
        <div class="box">
          <div
            class="byted-card byted-card-inner-line byted-card-bordered css-deu8f5"
            v-for="item in playerList"
            :key="item.id"
          >
            <div class="byted-card-body">
              <div class="media">
                <div class="main_img">
                  <img
                    src="https://sf3-ttcdn-tos.pstatp.com/obj/union-fe/tmpl/file/2020082420341062812025.png"
                    alt="图片加载失败"
                  />
                </div>
                <div class="hoverBody">
                  <div class="blackBG">
                    <a-button type="primary" @click="preview(item)" style="margin-bottom: 30px">弹窗预览</a-button>
                    <a-button type="primary" @click="previewVisible=true">使用模板</a-button>
                  </div>
                </div>
              </div>
              <div>
                <h5 class="css-1lrzuem">
                  <span class="tip">{{ item.product }}</span>
                  {{ item.type }}
                </h5>
                <div class="css-vfnok7"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div> -->

    <a-card :bordered="false">
      <a-button @click="addModules" style="margin: 0 0 15px 0" type="primary">新增模板</a-button>
      <div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :loading="loading"
        >
          <span slot="action" slot-scope="text, record">
            <a @click="downloadZip(record)">导出</a>

            <a-divider type="vertical" />
            <a @click="changeView(record)">替换素材</a>

            <a-divider type="vertical" />
            <a @click="preview(record)">预览</a>

            <a-divider type="vertical" />

            <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>
      <!-- table区域-end -->
    </a-card>
    <div class="previewBody" v-if="previewBody">
      <div class="content">
        <div class="content-inner">
          <div class="phone">
            <iframe :src="playerSrc" width="274" height="487" frameborder="0"></iframe>
          </div>
          <a-button type="default" @click="closePreview" size="large" class="closePreviewBtn">关闭预览</a-button>
        </div>
      </div>
    </div>
    <a-modal
      title="模板上传"
      :visible="previewVisible"
      @cancel="handleCancel"
      :width="1000"
      @ok="saveFile"
      :confirm-loading="confirmLoading"
    >
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="模板所属账户">
          <Treeselect :appId.sync="appId" :multiple="false" request="1,3" ref="treeSelect" style="width: 100%" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="模板类型">
          <a-input
            placeholder="请输入模板类型"
            v-decorator.trim="['fileType', { rules: [{ required: true, message: '请输入模板类型' }] }]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="模板文件">
          <a-upload
            name="file"
            action="http://192.168.1.251/jeecg-boot"
            :customRequest="customRequest"
            :fileList="defaultFileList"
          >
            <a-button> <a-icon type="upload" /> Click to Upload </a-button>
          </a-upload>
          <!-- <input type="file" @change="customRequest"> -->
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      title="替换素材"
      :visible="changeVisible"
      @cancel="changeVisible = false"
      :width="1000"
      @ok="changeFile"
      :confirm-loading="changeLoading"
    >
      <a-list class="demo-loadmore-list" :loading="loading" item-layout="horizontal" :data-source="dataList">
        <!-- <a-list-item slot="renderItem" slot-scope="item, index"> -->
        <a-list-item-meta style="margin-bottom: 10px">
          <a slot="title">是否重新生成</a>
          <div slot="description">
            <a-radio-group v-model="create" button-style="solid">
              <a-radio-button value="1"> 是 </a-radio-button>
              <a-radio-button value="2"> 否 </a-radio-button>
            </a-radio-group>
          </div>
        </a-list-item-meta>
        <a-list-item-meta v-if="create == '1'">
          <a slot="title">请输入试玩名称(不填默认拼接时间)</a>
          <div slot="description">
            <a-input placeholder="请输入试玩名称" v-model="fileName" />
          </div>
        </a-list-item-meta>

        <!-- </a-list-item> -->
        <a-list-item slot="renderItem" slot-scope="item, index">
          <a-upload
            name="file"
            action="http://192.168.1.251/jeecg-boot"
            :customRequest="customRequestChange"
            :beforeUpload="beforeUpload"
            :fileList="defaultFileList"
            slot="actions"
            v-if="item.fileSuffix == 'png' || item.fileSuffix == 'jpg' || item.fileSuffix == 'gif'"
          >
            <a @click="getIndex(item, index)">替换素材</a>
          </a-upload>

          <a-list-item-meta v-if="item.fileSuffix == 'png' || item.fileSuffix == 'jpg' || item.fileSuffix == 'gif'">
            <a slot="title"
              >{{ item.fileName }} (请上传大小为{{ item.width + '*' + item.height }}的图片，格式为{{
                item.fileSuffix
              }})</a
            >
            <div
              slot="description"
              style="width: 300px; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center"
            >
              <img :src="item.fileUrl" alt="" style="width: 50%; heihgt: auto; margin: 0 auto" />
              <img
                :src="item.imgPviewsUrl"
                v-if="item.imgPviewsUrl"
                alt=""
                style="width: 50%; heihgt: auto; margin: 0 auto"
              />
            </div>
          </a-list-item-meta>
          <!-- <a-list-item-meta v-else-if="item.fileSuffix == 'mp3'">
            <a slot="title">{{ item.fileName }}</a>
            <div
              slot="description"
              style="width: 200px; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center"
            >
              <audio
                loop
                muted
                :src="item.fileUrl"
                controls=""
                style="width: 100%; height: 20px; margin: 5px auto"
              ></audio>
            </div>
          </a-list-item-meta>
          <a-list-item-meta v-else-if="item.fileSuffix == 'mp4'">
            <a slot="title">{{ item.fileName }}</a>
            <div
              slot="description"
              style="width: 200px; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center"
            >
              <video :src="item.fileUrl" controls="controls" style="width: 50%; heihgt: auto; margin: 0 auto">
                您的浏览器不支持 video 标签。
              </video>
            </div>
          </a-list-item-meta> -->
          <!-- <div>content</div> -->
        </a-list-item>
      </a-list>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction, uploadAction } from '../../api/manage'
import playerList from './playerData'
import { mapGetters } from 'vuex'
import Treeselect from '@/views/modules/Statistics/components/Treeselect.vue'
import qs from 'qs'
export default {
  components: {
    Treeselect,
  },
  data() {
    return {
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      thisItem: null,
      thisIndex: null,
      defaultFileList: [],
      fileAll: null,
      playerList,
      previewBody: false,
      playerSrc: '',
      previewVisible: false,
      changeVisible: false,
      changeLoading: false,
      loading: false,
      dataSource: [],
      dataList: [],
      form: this.$form.createForm(this),
      appId: '',
      fileName: '',
      create: '1',
      zipName: null,
      columns: [
        {
          title: '试玩名称',
          align: 'center',
          dataIndex: 'fileName',
        },
        {
          title: '试玩分类',
          align: 'center',
          dataIndex: 'fileType',
        },
        {
          title: '上传时间',
          align: 'center',
          dataIndex: 'createTime',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: {
            customRender: 'action',
          },
        },
      ],
    }
  },
  methods: {
    downloadZip(item) {
      let eleLink = document.createElement('a')
      eleLink.download = item.fileName
      eleLink.href = item.fileUrl
      eleLink.click()
      eleLink.remove()
    },
    beforeUpload(file, fileList) {
      let that = this
      return new Promise(function (resolve, reject) {
        var imgInfo = {}

        let fileReader = new FileReader()
        fileReader.readAsDataURL(file) //根据图片路径读取图片
        fileReader.onload = function (e) {
          let base64 = this.result
          let img = new Image()
          img.src = base64
          img.onload = function () {
            imgInfo = {
              width: img.naturalWidth,
              height: img.naturalHeight,
            }
            console.log(imgInfo)
            if (imgInfo.width != that.thisItem.width || imgInfo.height != that.thisItem.height) {
              alert(`请选择${that.thisItem.width}*${that.thisItem.height}大小的文件！`)
              reject()
            } else {
              resolve()
            }
          }
        }
      })
      //  const fileOvesize = (file.size > this.size * oneKB)
    },
    getIndex(item, index) {
      console.log(item, index)
      this.thisItem = item
      this.thisIndex = index
    },
    customRequest(data) {
      var dataAll = {
        uid: '1',
        name: data.file.name,
        status: 'done',
      }

      this.defaultFileList = [dataAll]
      this.fileAll = data.file
      // this.saveFile(data.file)
    },
    customRequestChange(data) {
      console.log(data)
      var dataAll = {
        uid: '1',
        name: data.file.name,
        status: 'done',
      }

      // this.defaultFileList = []
      if (data.file) {
        var that = this
        that.thisItem.newFile = data.file

        var fr = new FileReader()
        fr.onload = function () {
          that.thisItem.imgPviewsUrl = this.result
        }
        fr.readAsDataURL(data.file)
      }

      // this.saveFile(data.file)
    },
    changeFile(e) {
      this.changeLoading = true
      var dataArr = this.dataList.filter((i) => {
        return i.newFile != null
      })
      console.log(this.dataList, dataArr)
      let formData = new FormData()
      formData.append('file', dataArr[0].newFile)
      formData.append('userId', this.userInfo().id)
      formData.append('updateName', dataArr[0].fileName)
      formData.append('id', dataArr[0].parentId)
      formData.append('fileType', dataArr[0].fileType)
      if (dataArr[0].accountId) {
        formData.append('accountId', dataArr[0].accountId)
      }

      formData.append('isCreate', this.create == '1' ? 1 : null)
      formData.append('newFileName', this.fileName == '' ? this.zipName : this.fileName+'.zip')

      postAction('/shiwan/shiwanFileUpload/createNewZipFile', formData).then((res) => {
        if (res.success) {
          this.changeLoading = false
          this.changeVisible = false
          this.getPlayableList()
          this.fileName = ''
        }
      })

      // for (let i = 0; i < dataArr.length; i++) {
      //   if (i == 0) {

      //   }
      // }
    },
    saveFile(e) {
      this.confirmLoading = true
      this.form.validateFields((err, values) => {
        if (!err) {
          let that = this
          let formData = new FormData()
          console.log(this.defaultFileList)
          formData.append('file', this.fileAll)
          formData.append('userId', this.userInfo().id)
          formData.append('fileType', values.fileType)
          uploadAction('/shiwan/shiwanFileUpload/saveOrUpdateFile', formData).then((res) => {
            if (res.success) {
              this.confirmLoading = false
              this.defaultFileList = []
              this.fileAll = null
              this.form.resetFields()
              this.previewVisible = false
              this.getPlayableList()
            } else {
              this.confirmLoading = false
              this.$message.error(res.message)
              this.defaultFileList = []
              this.fileAll = null
            }
          })
        }
      })
    },

    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    changeView(item) {
      getAction('/shiwan/shiwanFileUpload/selectListByParentId', { id: item.id }).then((res) => {
        if (res.success) {
          var data = []
          data = res.result.filter((i) => {
            if (i.fileSuffix == 'png' || i.fileSuffix == 'jpg' || i.fileSuffix == 'gif') {
              return i
            }
          })
          this.dataList = data.map((i) => {
            return {
              ...i,
              width: null,
              height: null,
              imgPviewsUrl: '',
              newFile: null,
            }
          })
          for (let i = 0; i < this.dataList.length; i++) {
            this.getImgWidth(this.dataList[i])
          }
          this.changeVisible = true
          this.zipName = item.fileName
        }
      })
    },
    preview(item) {
      console.log(item)

      getAction('/shiwan/shiwanFileUpload/selectListByParentId', { id: item.id }).then((res) => {
        if (res.success) {
          this.previewBody = true
          this.playerSrc = res.result.filter((i) => {
            return i.fileSuffix == 'html'
          })[0].fileUrl
        }
      })
    },
    closePreview() {
      this.previewBody = false
    },
    handleCancel() {
      this.previewVisible = false
    },
    addModules() {
      this.previewVisible = true
    },
    handleDelete(item) {
      postAction('/shiwan/shiwanFileUpload/edit', { id: item, fileStatus: '0' }).then((res) => {
        if (res.success) {
          this.getPlayableList()
        }
      })
    },
    getPlayableList() {
      getAction('/shiwan/shiwanFileUpload/list', {
        pageNo: 1,
        pageSize: 1000,
      }).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
        }
      })
    },
    getImgWidth(item) {
      // this.$nextTick(() => {
      // 记录当前时间戳
      var start_time = new Date().getTime()
      // 图片地址
      var img_url = item.fileUrl
      // 创建对象
      var img = new Image()
      // 改变图片的src
      img.src = img_url
      // 定时执行获取宽高
      var checkAll = ''
      var that = this
      var check = function () {
        // 只要任何一方大于0
        // 表示已经服务器已经返回宽高
        if (img.width > 0 || img.height > 0) {
          var diff = new Date().getTime() - start_time
          item.width = img.width
          item.height = img.height
          that.$set(item, 'width', img.width)
          that.$set(item, 'height', img.height)
          clearInterval(set)
        }
      }
      var set = setInterval(check, 40)
      // 加载完成获取宽高
      img.onload = function () {
        var diff = new Date().getTime() - start_time
        item.width = img.width
        item.height = img.height
        that.$set(item, 'width', img.width)
        that.$set(item, 'height', img.height)
        // console.log(item.width, item.height)
      }
      // })
    },
  },
  mounted() {
    this.getPlayableList()
  },
}
</script>

<style lang="scss" scoped>
.playerList {
  position: relative;
  .top {
    width: calc(100% - 160px);
    margin: 0px auto;
  }
  .playBody {
    width: 100%;
    padding: 20px;
    .box {
      width: 100%;
      height: 100%;
      display: flex;
      flex-wrap: wrap;
      -webkit-box-pack: center;
      justify-content: flex-start;
      .css-deu8f5 {
        width: 224px;
        margin: 10px !important;
      }
      .byted-card-inner-line {
        padding: 0;
      }
      .byted-card-bordered {
        border: 1px solid #e0e0e0;
        box-shadow: none;
      }
      .byted-card {
        font-size: 14px;
        line-height: 22px;
        position: relative;
        color: #333;
        background: #fff;
        box-sizing: border-box;
        border-radius: 4px;
        box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.05);
        border: 1px solid transparent;
      }
      .byted-card > .byted-card-body {
        box-shadow: rgb(204, 204, 204) 0px 0px 10px;
        padding: 0px !important;
      }
      .byted-card > .byted-card-body .media {
        height: 392px;
        width: 100%;
        position: relative;
        cursor: pointer;
        overflow: hidden;
        border-bottom: 1px solid rgb(204, 204, 204);
      }
      .byted-card > .byted-card-body .media .main_img {
        width: 100%;
        height: 100%;
        display: flex;
        -webkit-box-align: center;
        align-items: center;
        position: absolute;
      }
      .byted-card > .byted-card-body .media .main_img img:last-child {
        width: 100%;
        position: absolute;
      }
      .byted-card > .byted-card-body .media .main_img img:first-child {
        width: 100%;
        height: 100%;
        // filter: blur(10px);
        position: absolute;
      }
      .css-1lrzuem {
        display: flex;
        -webkit-box-align: center;
        align-items: center;
        font-size: 14px;
        font-weight: 600;
        color: rgb(51, 51, 51);
        line-height: 20px;
        text-shadow: rgba(0, 0, 0, 0.08) 0px 2px 8px;
        word-break: keep-all;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin: 16px 16px 0px;
        overflow: hidden;
      }
      .css-vfnok7 {
        height: 40px;
        display: flex;
        flex-direction: row-reverse;
        -webkit-box-align: center;
        align-items: center;
      }
      .hoverBody {
        display: none;
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
      }
      .blackBG {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
        display: flex;
        -webkit-box-align: center;
        align-items: center;
        -webkit-box-pack: center;
        justify-content: center;
        background-color: rgba(0, 0, 0, 0.5);
        flex-flow: column;
      }
      .byted-card:hover {
        box-shadow: rgb(153, 153, 153) 0px 0px 20px;
      }
      .byted-card:hover .hoverBody {
        display: block;
      }
      .tip {
        display: inline-block;
        margin-right: 15px;
        background: #ff6633;
        width: 80px;
        padding: 2px 10px;
        text-align: center;
        border-radius: 10px;
      }
    }
  }
  .previewBody {
    background: rgba(0, 0, 0, 0.5);
    position: absolute;
    top: 0;
    left: 0;
    padding: 20px 80px;
    width: 100%;
    height: 100%;
    .content {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    }
    .content-inner {
      font-size: 14px;
      line-height: 22px;
      padding: 0 24px 8px;
      color: #666;
      text-align: center;
      position: fixed;
      top: 200px;
    }
    .phone {
      background-color: rgb(255, 255, 255);
      position: relative;
      padding: 9px 8px 7px;
      border-radius: 24px;
    }
    .phone iframe {
      border-radius: 18px;
    }
    .closePreviewBtn {
      margin-top: 30px;
    }
  }
}
</style>