<template>
  <div>
    <a-modal
      :width="800"
      v-model="visible"
      @cancel="visible = false"
      class="dec-sourceModal"
    >
      <template slot="title">
        <div class="dec-flex-row">
          <a-upload
            class="upload-demo"
            :show-upload-list="false"
            :customRequest="dealUpLoadData"
            :before-upload="beforeAvatarUpload"
          >
            <a-button type="primary" key="search"
              >上传{{ ismp4 ? "视" : "音" }}频</a-button
            >
          </a-upload>
          <div class="m-search">
            最大支持 {{ sourceSizeLimit }} MB 以内格式为{{
              ismp4 ? "mp4的视频" : "mp3的音频"
            }}文件
          </div>
        </div>
      </template>
      <div class="img-list">
        <div class="left-nav">
          <div
            v-for="item in sourceType"
            :key="item.id"
            class="nav-item"
            :class="{ selected: sourceTypeId === item.id }"
            @click="sourceTypeChange(item.id)"
          >
            {{ item.name }}
          </div>
        </div>
        <div
          class="right-source"
          style="padding: 20px"
          v-if="sourceTypeId === '0'"
        >
          <a-textarea
            v-model="source"
            placeholder="请输入外部资源链接"
            :auto-size="{ minRows: 2, maxRows: 4 }"
          />
        </div>
        <div class="right-source" v-else>
          <div
            class="source-box"
            v-for="(item, index) in tableData"
            :key="index"
          >
            <div
              class="source-wrap"
              @click="iNum = index"
              :class="{ selected: index == iNum }"
            >
              <span class="icon-wrap"></span>
              <a-icon class="ic-check" type="check-circle" />
              <div class="source-info">
                <img
                  class="source-img"
                  :src="decAxios.decImgDomain('', 'play.png')"
                  alt
                  v-if="!item.isPlay"
                  @click="playing($event, item)"
                  draggable="false"
                />
                <img
                  class="source-img"
                  :src="decAxios.decImgDomain('', 'playing.gif')"
                  alt
                  v-else
                  @click="playing($event, item)"
                  draggable="false"
                />
                <div class="source-name dec-truncate">
                  <div>{{ item.fileName }}</div>
                  <div class="source-size">
                    Added by {{ item.createBy }} on {{ item.createTime }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template slot="footer">
        <div class="dec-flex-between">
          <a-pagination
            size="small"
            :total="total"
            :pageSize="pageSize"
            :current="current"
            :showSizeChanger="false"
            @change="pageChange"
            show-size-changer
            show-quick-jumper
          />
          <a-button
            class="btn-right"
            key="submit"
            type="primary"
            @click="handleOk"
            >确定</a-button
          >
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { sourceSizeLimit, sourceFomatLimit } from "../util/setting.js";
export default {
  inject: ["decAxios"],
  props: {
    ismp4: {
      type: Boolean,
      default() {
        return false;
      },
    },
  },
  data() {
    return {
      visible: false, //弹窗控制参数
      iNum: -1, // 选中参数
      tableData: [],
      spinning: false,
      pageSize: 10,
      total: 0,
      current: 1,
      source: "",
      newName: "",
      sourceSizeLimit: sourceSizeLimit,
      sourceType: [
        {
          id: "0",
          name: "外部资源",
        },
        {
          id: "1",
          name: "内部资源",
        },
      ],
      sourceTypeId: "1",
    };
  },
  created() {},
  watch: {
    visible: function (curVal, oldVal) {
      if (curVal === oldVal) return;
      if (curVal) {
        // 设置要获取的图片类型，获取图片数据，设置上传图片的路径
        this.current = 1;
        this.getVoice();
      }
    },
  },
  methods: {
    //获取音频数据
    getVoice() {
      this.iNum = -1;
      this.spinning = true;
      let params = {
        pageNo: this.current,
        pageSize: this.pageSize,
        fileCate: "4",
      };
      this.decAxios.getSource(params).then((res) => {
        this.spinning = false;
        if (res.code == 200) {
          this.tableData = res.result.records;
          this.total = res.result.total;
        } else {
          this.tableData = [];
          this.total = 0;
        }
      });
    },
    // 弹出
    show() {
      this.visible = true;
      this.iNum = -1;
      this.sourceTypeId = "1";
      this.source = "";
    },
    playing(e, item) {
      if (e && e.stopPropagation) {
        e.stopPropagation();
      } else {
        window.event.cancelBubble = true;
      }
      item.isPlay = !item.isPlay;
    },
    handleOk() {
      let haha =
        "https://img.cdn.aliyun.dcloud.net.cn/guide/uniapp/%E7%AC%AC1%E8%AE%B2%EF%BC%88uni-app%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D%EF%BC%89-%20DCloud%E5%AE%98%E6%96%B9%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B@20200317.mp4";
      if (this.sourceTypeId === "0") {
        if (this.source && /^htt(p|ps):\/\//.test(this.source)) {
          this.$emit("choose", { fileUrl: this.source, fileName: "外部资源" });
          // this.$emit("choose", { fileUrl: haha, fileName: "外部资源" });
          this.visible = false;
        } else {
          this.$message.warning("请输入正确的资源链接地址");
        }
      } else {
        if (this.iNum != -1) {
          var obj = this.tableData[this.iNum];
          this.$emit("choose", obj);
          this.visible = false;
        } else {
          this.$message.warning("请选择资源文件");
        }
      }
    },
    dealUpLoadData(result) {
      let file = result.file;
      let fileName = file.name.split(".");

      let fileInfo = {
        fileCate: "4",
        fileTyle: fileName.length > 1 ? fileName[fileName.length - 1] : "",
        fileName: "",
        biz: "tempSource",
        file: file,
      };
      const that = this;
      function successCallback() {
        that.getVoice();
      }
      function failCallback(mes) {
        mes && that.$message.error(mes);
      }

      const uploadHandle = (name) => {
        fileInfo.fileName = name;
        this.decAxios
          .uploadSource(fileInfo, successCallback, failCallback)
          .then((res) => {
            if (res.code === 200) {
              !res.message && successCallback();
            } else {
              failCallback(res.message);
            }
          });
      };
      this.newName = fileName[0];
      this.$confirm({
        title: "确认上传文件？",
        content: (h) => {
          return h("div", [
            h("span", "文件重命名:"),
            h("a-input", {
              style: { marginLeft: "10px", width: "230px" },
              props: {
                placeholder: "重命名文件便于查询",
                value: that.newName,
              },
              on: {
                input: (e) => {
                  this.newName = e.target.value;
                },
              },
            }),
          ]);
        },
        okText: "确定",
        cancelText: "取消",
        onOk() {
          uploadHandle(that.newName);
        },
      });
    },
    beforeAvatarUpload(file) {
      let obj = this.ismp4 ? "video/mp4" : "audio/mpeg";
      const extension = file.type === obj;
      let isLt2M =
        file.size / Math.pow(1024, sourceSizeLimit) < sourceSizeLimit;
      if (!extension) {
        this.$message.warning("文件只能为音频或视频文件格式！");
      }
      if (!isLt2M) {
        this.$message.warning(`文件大小不能超过${sourceSizeLimit}MB!`);
      }
      return extension && isLt2M;
    },
    pageChange(obj) {
      obj && (this.current = obj) && this.getVoice();
    },
    sourceTypeChange(id) {
      if (this.sourceTypeId !== id) {
        this.sourceTypeId = id;
        this.current = 1;
        this.source = "";
        id === "1" && this.getVoice();
      }
    },
  },
};
</script>
