// index.js
// 获取应用实例
import {
  VueLikePage
} from "../../utils/page";
import {
  CDN_URL,
  API_BASE_URL,
  VIDEO_BASE_URL,
  app
} from "../../config/index";


var g_app = getApp();

VueLikePage([], {
  data: {
    cdn_url: CDN_URL,
    baseUrl: API_BASE_URL + "/",
    url_link: "",
    id: "1",
    type: "",
    loadCompele: false,
    filePath: ''
  },
  methods: {
    onLoad: function (options) {
      let {
        rdw,
        id,
        type
      } = options;

      let link = "";
      if (type == "0") {
        link = `${VIDEO_BASE_URL}4dvedio/${rdw}.mp4`;
      } else {
        link = `${VIDEO_BASE_URL}4dpic/${rdw}.jpg`;
      }

      this.setData({
        url_link: link,
        id,
        type,
      });

      this.downloadF(data => {
        this.setData({
          filePath: data
        })
      })
    },
    loadcompele() {
      this.setData({
        loadCompele: true,
      });
    },
    cancel() {
      // wx.reLaunch({
      //   url: "/pages/work/index",
      // });

      wx.navigateBack();
    },

    downloadF(cb = () => {}) {
      let link = this.data.url_link,
        m_type = "";

      if (this.data.type == "1") {
        m_type = "jpeg";
      } else {
        m_type = "video";
      }


      wx.downloadFile({
        url: link,
        success: (res) => {
          if (res.statusCode == '404') {
            return app.showAlert("作品暂未生成，请稍后再试", () => {
              wx.navigateBack()
            });
          }
          //判断是否为数组
          let typeType =
            Object.prototype.toString.call(res.header["Content-Type"]) == "[object String]" ? res.header["Content-Type"] : res.header["Content-Type"][0];


          //判断不是xml文件
          if (typeType.indexOf(m_type) > -1) {
            cb(res.tempFilePath)
          }
        },
        fail: () => {
          app.showAlert("作品暂未生成，请稍后再试");
        },
      });
      this.setData({
        showModal: false,
      });
    },

    saveAlbum() {
      let type = this.data.type;

      wx.showLoading({
        title: "保存中…",
        mask: true,
      });

      if (this.data.filePath) {
        let api =
          type == "0" ? "saveVideoToPhotosAlbum" : "saveImageToPhotosAlbum";
        wx[api]({
          filePath: this.data.filePath,
          success() {
            wx.showModal({
              title: "提示",
              content: "已保存到相册，快去分享吧",
              showCancel: false,
            });
          },
          fail: (e) => {
            if (!(e.errMsg.indexOf('cancel') > -1)) {
              wx.showModal({
                title: "提示",
                content: "保存失败，请检查是否开启相册保存权限，可在「右上角」 - 「设置」里查看",
                showCancel: false,
              });
            }
          },
          complete: () => {
            wx.hideLoading();
          },
        });
      }

    },
  },
});