<template><page-meta
  :page-font-size="$baseFontSize() + 'px'"
  :root-font-size="$baseFontSize() + 'px'"
></page-meta>
  <view class="page container commonPageBox commonDetailPage">
    <player
      ref="player"
      :videoId="videoId"
      :userId="userId"
      :apiKey="apiKey"
      :verificationCode="verificationCode"
      :customId="customId"
      :autoPlay="autoPlay"
      :lists="lists"
      videoMode="fill"
      qualityOrder="descending"
      :barrageOpen="barrageOpen"
      :settingBarrageMode="settingBarrageMode"
      :logo="logo"
      @onSendBarrage="toggleFixedFooter"
      @onSettingBarrage="handleToggleBarrageSetting"
      @onDownload="onDownload"
      @changeVideo="changeVideo"
      @requestAndroidDownloadPermission="requestAndroidDownloadPermission"
    >
    </player>
    <!-- <video-list
		v-if="showVideoList"
		:pick-mode="pickMode"
		:is-pushing="isPushing"
		:lists="lists"
		:currentVideo="videoId"
		@listClick="changeVideo">
			<template v-slot:title>
				<view class="list-header">
					<text class="list-title">课程目录</text>
					<picker
					mode="selector"
					:value="selectedDefinition"
					:range="definitions"
					range-key="desp"
					@change="handleDefinitionChange"
					>
						<view class="picker-inner">
							<text class="select-text">{{ definitions[selectedDefinition].desp }}</text>
							<image class="pick-icon" src="@/static/arrow-down-black@2x.png"></image>
						</view>
					</picker>	
				</view>
			</template>
			<template v-slot:footer>
				<download-footer
				:pick-mode="pickMode"
				@changePickMode="changePickMode"
				@downloadConfirm="downloadConfirm"
				></download-footer>
			</template>
		</video-list> -->
  </view>
</template>

<script>
import { setFullScreen } from "@/utils/tool.js";
import download from "@/mixins/download.js";

import Player from "@/components/player/player.vue";
import VideoList from "@/components/list/VideoList.nvue";
import downloadFooter from "@/components/download/downloadFooter.vue";

import { getList } from "@/api/list.js";
import { mapState, mapMutations } from "vuex";

const { platform } = uni.getSystemInfoSync();

import permision from "@/js_sdk/wa-permission/permission.js";

const definitions = [
  {
    quality: 20,
    desp: "高清",
  },
  {
    quality: 10,
    desp: "清晰",
  },
];

export default {
  components: {
    Player,
    VideoList,
    downloadFooter,
  },
  data() {
    return {
      videoId: "",
      userId: "",
      apiKey: "",
      verificationCode: "",
      customId: "",
      lists: [],
      showVideoList: true,
      pickMode: false, // 批量下载选择模式
      definitions,
      selectedDefinition: 0,
      logo: {
        url: "https://www.bokecc.com/Site/Default/Uploads/kindeditor/image/20210207/logo6.png",
        position: "tr", // 默认：左上 tr：右上 bl: 左下 br: 右下
        // width: '100px',
        // height: '100px',
        offsetX: "15rpx", // position垂直偏移量
        offsetY: "15rpx", // position水平偏移量
      },
      autoPlay: false,
    };
  },
  computed: {
    ...mapState({
      // userId: state => state.baseInfo.userId,
      // apiKey: state => state.baseInfo.apiKey,
      // verificationCode: state => {
      // 	if (Array.isArray(state.baseInfo)) {
      // 		const item = state.baseInfo.find(i => i.userId === this.userId)
      // 		if (item) return item.verificationCode
      // 	} else {
      // 		return state.baseInfo.verificationCode
      // 	}
      // },
      // customId: state => {
      // 	if (Array.isArray(state.baseInfo)) {
      // 		const item = state.baseInfo.find(i => i.userId === this.userId)
      // 		if (item) return item.customId
      // 	} else {
      // 		return state.baseInfo.customId
      // 	}
      // },
      baseInfo: (state) => state.baseInfo,
      isPushing: (state) => state.isPushing,
      pipVideoId: (state) => state.pipInfo.videoId,
    }),
  },
  watch: {
    userId(newVal) {
      console.log("watch userId", newVal);
      if (newVal) {
        if (Array.isArray(this.baseInfo)) {
          const item = this.baseInfo.find((i) => i.userId === newVal);
          if (item) {
            this.apiKey = item.apiKey;
            this.verificationCode = item.verificationCode;
            this.customId = item.customId;
          }
        } else {
          this.apiKey = this.baseInfo.apiKey;
          this.verificationCode = this.baseInfo.verificationCode;
          this.customId = this.baseInfo.customId;
        }
      }
    },
  },
  onLoad(option) {
    let _this = this;
    this.videoId = option.videoId;
    this.userId = option.userId;
    if (!option.from) {
      uni.$emit("removePIP");
    }
    getList((data) => {
      this.lists = data.map((item) => {
        if (!Array.isArray(this.baseInfo)) {
          item.userId = this.baseInfo.userId;
        }
        return item;
      });
      console.log("getList", data);
    });
    uni.$on("setFullScreenStatus", (status) => {
      this.showVideoList = !status;
    });
  },
  onReady() {
    uni.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: "#282828",
      success: () => {
        console.log("设置导航条颜色成功");
      },
      fail: (e) => {
        console.log("设置导航条颜色失败", e);
      },
    });
  },
  onShow() {
    console.log("detail page onShow");
    // if (this.$refs.player) {
    // 	this.$refs.player.start()
    // }
    if (this.pipVideoId && this.pipVideoId !== this.videoId) {
      this.setPipInfo({
        videoId: "",
        userId: "",
      });
    }
  },
  onHide() {
    // if (this.$refs.player) {
    // 	this.$refs.player.pause();
    // }
  },
  onUnload() {
    console.log("detail page Unload");
    if (this.$refs.player && platform === "ios") {
      this.$refs.player.destroy();
    } else {
      this.$refs.player.stop();
    }
  },
  onBackPress(options) {
    console.log("detail page onBackPress", options);
    // 安卓端手势返回上一页，强制竖屏
    setFullScreen(false);
    if (options.from == "backbutton") {
      uni.$emit("removePIP");
    }
  },
  methods: {
    ...mapMutations(["setPipInfo"]),
    changeVideo(item) {
      this.videoId = item.videoId;
      this.userId = item.userId;
    },
    changePickMode(tag) {
      if (platform === "android") {
        // this.requestAndroidPermission('android.permission.READ_EXTERNAL_STORAGE');
        if (!tag) {
          this.pickMode = tag;
        } else {
          this.requestAndroidPermission(
            "android.permission.WRITE_EXTERNAL_STORAGE"
          );
        }
      } else {
        this.pickMode = tag;
      }
    },
    downloadConfirm() {
      try {
        let list = JSON.parse(JSON.stringify(this.lists));
        list = list.filter((item) => item.selected == true);
        console.log("downloadConfirm", list);
        // 补充清晰度配置
        list = list.map((item) => {
          item.definition = Number(
            this.definitions[this.selectedDefinition].quality
          );
          return item;
        });
        this.pickMode = false;
        if (list.length) {
          setTimeout(() => {
            uni.$emit("startDownload", list);
          }, 300);
          uni.showToast({
            title: "文件已加入下载队列",
            icon: "none",
            position: "bottom",
          });
        }
      } catch (e) {
        console.log(e);
      }
    },
    onDownload(videoId, quality) {
      const list = JSON.parse(JSON.stringify(this.lists));
      const item = list.find((video) => video.videoId === videoId);
      item.definition = Number(quality);
      if (item) {
        setTimeout(() => {
          uni.$emit("startDownload", item);
        }, 300);
      }
    },
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      var strStatus;
      if (result === 1) {
        strStatus = "已获得授权";
        this.pickMode = true;
        uni.$emit("getStoragePermission");
      } else {
        uni.showModal({
          content: "下载需获取存储权限，请先手动开启",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              permision.gotoAppPermissionSetting();
            }
          },
        });
      }
    },
    handleDefinitionChange(e) {
      this.selectedDefinition = e.detail.value;
      console.log("selectedDefinition", this.selectedDefinition);
    },
    requestAndroidDownloadPermission() {
      this.requestAndroidPermission(
        "android.permission.WRITE_EXTERNAL_STORAGE"
      );
    },
  },
};
</script>

<style lang="stylus" scoped>
.page
   width 100%
   height 100vh
	flex 1
	.list-header
		flex-direction: row
		justify-content: space-between
		align-items: center
		margin-top 30rpx
		margin-bottom 5rpx
		.list-title
			font-size: 30rpx
		.picker-inner
			flex-direction: row
			align-items: center
			.select-text
				font-size: 26rpx;
				font-weight: 600;
				color: rgba(0,0,0,0.85);
			.pick-icon {
				margin-left: 8rpx;
				width: 26rpx;
				height: 15rpx;
			}
</style>
