<template>
  <view class="page">
 
    <!-- 权限申请提示 -->
    <view v-if="showRights" class="permission-tip">
		
		
		
		
		
      <text class="permission-title">正在获取相机、存储权限</text>
      <text class="permission-desc">该权限用于获取设备拍摄或获取本地应用相册，进行头像或图片上传。</text>
    </view>

    <!-- 顶部导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-left" @click="goBack">
        <text class="fa fa-angle-left"></text>
      </view>
      <view class="navbar-center">
        <view class="navbar-title" @click="goToUserHomepage(author.id)">
          <image class="navbar-avatar" :src="author.avator" mode="aspectFill"></image>
          <text class="navbar-text">{{ author.nickname }}</text>
          <!-- <text class="navbar-badge" v-if="author.is_vip > 0">VIP</text> -->
        </view>
      </view>
      <view class="navbar-right">
        <template v-if="!isItMe">
          <text class="followTheAuthor followTheAuthor1" v-if="author.is_attention == 0"
            @click="() => followTheAuthor(1)">+关注</text>
          <text class="followTheAuthor followTheAuthor0" v-if="author.is_attention == 1"
            @click="followTheAuthor(0)">已关注</text>
          </template>
        <image v-if="!isItMe" @click="showActionSheet(0)" src="../../static/icon/sy_icon_fenxiang.png" mode="widthFix">
        </image>
        <view v-else class="navbar-right" @click="showActionSheet(1)">
           <image src="@/static/icon/more2.png" style="width: 64rpx;height: 64rpx;  margin-top: 15rpx;" mode="widthFix"></image>
        </view>
      </view>
    </view>

    <!-- 灵感 -->
    <template v-if="articleInfo.task_type == 1">
      <view class="inspiration-content" v-if="home_image">
        <image v-if="home_image" :src="home_image" class="inspirationPictures" mode="widthFix" @click="previewImage(home_image)"></image>
      </view>
    </template>
    <!-- 音乐 -->
    <template v-else-if="articleInfo.task_type == 2">
      <view class="musicContentBox">
        <view class="headCard">
          <image :src="home_image" class="songCover"></image>
          <view class="songInfo">
            <view class="songTitle">{{ addBrackets(articleInfo.title) }}</view>
            <view class="songTag">
              <view class="tag" v-for="(item, index) in commaToArray(articleInfo.style)" :key="index + item">{{ item }}
              </view>
            </view>
          </view>
          <template v-if="articleInfo.task_type == 2">
            <image @click="toggleAudio" v-if="isPlaying" src="@/static/makedetail/cz_icon_zanting.png"
              class="playerButton"></image>
            <image @click="toggleAudio" v-else src="@/static/makedetail/cz_icon_bofang.png" class="playerButton">
            </image>
          </template>
        </view>
        <view class="contentHeader">
          <view class="musicContent">
            <text style="display: inline-block; max-width: 350rpx;"  > {{ articleInfo.lyrics }}</text>
            <image class="roll" src="@/static/icon/roll.png"></image>
          </view>
          <view class="maskLayer"></view>
        </view>
      </view>
    </template>

    <!-- 视频类型 -->
    <template v-else-if="articleInfo.task_type == 3">
      <view class="video-content">
        <video-player
          :src="articleInfo.video_url"
          :controls="true"
          :autoplay="false"
          :poster="home_image"
          :show-center-play-btn="true"
          :enable-progress-gesture="true"
          :show-fullscreen-btn="true"
          :show-play-btn="true"
          :object-fit="'contain'"
          @play="handleVideoPlay"
          @pause="handleVideoPause"
          @ended="handleVideoEnded"
          :videoStyle="{ width: '100%', height: '1000rpx' }"
        /> 
        <!-- <video-player
           src="https://media.w3.org/2010/05/sintel/trailer.mp4"
          :controls="true"
          :autoplay="false"
          :poster="home_image"
          :show-center-play-btn="true"
          :enable-progress-gesture="true"
          :show-fullscreen-btn="true"
          :show-play-btn="true"
          :object-fit="'contain'"
          @play="handleVideoPlay"
          @pause="handleVideoPause"
          @ended="handleVideoEnded"
          :videoStyle="{ width: '100%', height: '400rpx' }"
        />-->
      </view>
    </template>

    <!-- 作品描述 -->
    <view class="workDescription">
      <view class="workDescription-title">
        <view>创作说明 </view>
        <!-- <image class="pen" src="@/static/icon/wd_icon_bianji.png"></image> -->
      </view>
      <view class="workDescription-content">
        {{ content || "暂无内容" }}
      </view>
    </view>

    <view class="goCreate  blick-btn-animation" @click="goCreate()">去创作</view>
    <DialogBox ref="customConfirm"></DialogBox>

    <!-- 文章头图区域 -->
    <view class="topUser" v-if="false">
      <image :src="home_image" class="home_image" mode="aspectFill"></image>
      <!-- 图片指示器 -->
      <view class="image-indicator" v-if="image_list.length > 1">
        <text>{{ selImg + 1 }}/{{ image_list.length }}</text>
      </view>
      <!-- 音乐类型时显示歌词 -->
      <view class="lyrics-overlay" v-if="articleInfo.task_type == 2">
        <text class="lyrics-text">{{ articleInfo.lyrics }}</text>
      </view>
      <!-- 音乐类型时显示播放按钮 -->
      <view class="play-button" v-if="articleInfo.task_type == 2 && articleInfo.result_audio" @click="toggleAudio">
        <text class="fa" :class="isPlaying ? 'fa-pause' : 'fa-play'"></text>
      </view>
      <!-- 缩略图列表 -->
      <view class="list">
        <view class="img" :class="selImg == index ? 'active' : ''" v-for="(item, index) in image_list" :key="index"
          @click="selPhoto(item, index)">
          <image :src="item" mode="aspectFill"></image>
        </view>
      </view>
    </view>

    <!-- 音频元素 -->
    <audio id="audioPlayer" :src="articleInfo.result_audio" style="display: none" v-if="false"></audio>

 

    <!-- <view class="btn_submit" @click="chatTA()">
			<image class="icon" src="../../static/icon/icon_chat_white.png" mode="widthFix"></image>
			私聊
		</view> -->
    <view class="thread2"></view>
    <view class="thread2"></view>

    <previewImage ref="previewImage" :opacity="0.8" :circular="true" :imgs="imgs" :descs="descs"></previewImage>

    <!-- 评论区域 -->
    <CommentSection style="background: #fff; border-top-left-radius: 32rpx; border-top-right-radius: 32rpx;" v-if="userInfo.id != 0 && articleInfo.title" ref="commentSection" :myInfo="myInfo"
      :userInfo="userInfo" :articleId="arcID" @totalNumberOfComments="totalNumberOfComments" :articleInfo="articleInfo" :author="author"  find="work">
    </CommentSection>

    <!-- 自定义 ActionSheet -->
    <ActionSheet ref="actionSheet" :items="items" @select="handleActionSelect" @cancel="handleActionCancel" />
    <view class="thread2"></view>

    <SharePopup :visible="showShare" :userId="userId" :share-title="shareTitle" :share-desc="shareDesc"
      :share-img="shareImg" view="workDetail" @close="showShare = false" />
  </view>
</template>

<script>
import htmlParser from "../../common/html-parser";
import previewImage from "@/components/kxj-previewImage/kxj-previewImage.vue"; //引用插件
import CommentSection from "@/components/CommentSection/CommentSection.vue";
import ActionSheet from "@/components/ActionSheet/ActionSheet.vue";
import SharePopup from "@/components/SharePopup/SharePopup.vue";
import VideoPlayer from "@/components/VideoPlayer/VideoPlayer.vue";
import permission from '@/common/permission.js';
function parseImgs(nodes) {
  nodes.forEach((node) => {
    if (node.name === "img" && node.attrs && node.attrs["data-img-size-val"]) {
      const sizes = node.attrs["data-img-size-val"].split(",");
      const width = uni.upx2px(720 * 0.9);
      const height = parseInt(width * (sizes[1] / sizes[0]));
      node.attrs.style = `width:${width};height:${height};`;
    }
    if (Array.isArray(node.children)) {
      parseImgs(node.children);
    }
  });
  return nodes;
}
export default {
  components: {
    previewImage,
    CommentSection,
    ActionSheet,
    SharePopup,
    VideoPlayer
  },
  data() {
    return {
      title: "",
      arcID: 0,
      selImg: 0,
      home_image: "", 
      tag_list: [],
      image_list: [],
      imgs: [],
      descs: [],
      list_wish: [],
      content: "",
      author: {},
      showShare: false,
      shareTitle: "",
      shareDesc: "",
      shareImg: "",
      userId: 0,
      // 添加文章信息字段
      articleInfo: {
        title: "",
        content: "",
        create_time: "",
        images: "",
        view_count: 0,
        author: "",
        like_count: 0,
        is_like: false,
      },
      items: [],
      myInfo: {
        user_id: getApp().globalData.user_id, // 用户id
        user_name: getApp().globalData.nickname, // 用户名
        user_avatar: getApp().globalData.avator, // 用户头像地址
      },
      // 文章作者信息(提示: 一般来自localstorage, 如果是实时获取的话, 那么获取到数据后再v-if显示评论组件)
      userInfo: {
        user_id: 0, // 用户id
        user_name: "", // 用户名
        user_avatar: "", // 用户头像地址
      },
      deleteMode: "all", //删除模式
      // 评论总数
      tableTotal: 4,
      // 评论表
      tableData: [],
      isPlaying: false, // 添加播放状态
      audioPlayer: null, // 添加音频播放器实例
      sms_id: 0,
      isMessage: true,
      isItMe: false,
      showRights: false,
    };
  },
  onLoad(parms) {
    let self = this;
    this.arcID = parms.id
    if (parms.type == "sms") {
      this.isMessage = false;
    }
    if (parms.sms_id) {
      this.sms_id = parms.sms_id;
    }
  },
  onShow() {
    uni.$emit("check_update");
    this.loadData();
    this.$nextTick(() => {
      if (this.$refs.commentSection) {
        this.$refs.commentSection.loadCommentData();
      }
    });
  },
  onReady() {
    // 初始化音频播放器
    this.audioPlayer = uni.createInnerAudioContext();
    this.audioPlayer.onEnded(() => {
      this.isPlaying = false;
    });
  },
  onUnload() {
    // 页面卸载时停止音频播放
    if (this.audioPlayer) {
      this.audioPlayer.stop();
      this.audioPlayer.destroy();
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1,
      });
    },
    totalNumberOfComments(tableTotal) {
      this.tableTotal = tableTotal;
    },
    onLinqu(item) {
      uni.navigateTo({
        url: "/pages/my/wishHelp?id=" + item.myid,
      });
    },
    selPhoto(item, sel) {
      this.selImg = sel;
      this.home_image = this.image_list[sel];
    },
    toArr(imgs) {
      let arr = imgs.split("|");
      return arr;
    },
    previewOpen(imgs1, index) {
      this.imgs = imgs1.split("|");
      setTimeout(() => this.$refs.previewImage.open(index), 0);
      // 传入当前选中的图片地址或序号
      return; //如需测试和uni原生预览差别可注释这两行
    },
    loadData() {
      uni.request({
        url: this.$apiHost + "/Work/getinfo",
        data: {
          uuid: getApp().globalData.uuid,
          id: this.arcID,
        },
        header: {
          "content-type": "application/json",
          sign: getApp().globalData.headerSign,
        },
        success: (res) => {
          console.log("文章信息:", res.data);
          
          if (res.data.success === "yes") {
            console.log("文章信息:", res.data.data);
        
            // 更新文章信息
            this.articleInfo = res.data.data; 
            
            if (res.data.data&&res.data.data.video_url) {
              this.articleInfo.task_type = 3
            }
            if (res.data.article) {
              this.articleInfo = res.data.article;
            }
            this.articleInfo.sms_id = this.sms_id;
            this.content = res.data.data.content;
            this.home_image = res.data.data.images;
            this.author = res.data.author;

            // 更新分享相关数据
            this.shareTitle = this.articleInfo.title || '萌创星球';
            this.shareDesc = this.articleInfo.content;
            this.shareImg = this.home_image;
            this.userId =res.data.author.id;
            this.isItMe = 	res.data.author.id == getApp().globalData.user_id
								? true
								: false;
            this.userInfo.user_id = res.data.id; // 用户id
            this.userInfo.user_name = res.data.nickname; // 用户名
            this.userInfo.user_avatar = res.data.avator; // 用户头像地址
          } else {
            uni.showToast({
              title: "获取信息失败",
              icon: "none",
            });
          }
        },
        complete: (com) => {
          // uni.hideLoading();
        },
        fail: (e) => {
          console.log("请求失败:", e);
          uni.showToast({
            title: "网络请求失败",
            icon: "none",
          });
        },
      });
    },
    // 唤起新评论弹框
    openComment() {
      if (this.$refs.commentSection) {
        this.$refs.commentSection.openComment();
      }
    },
    // 文章点赞
    likeArticle() {
      uni.request({
        url: this.$apiHost + "/Work/like",
        data: {
          uuid: getApp().globalData.uuid,
          id: this.arcID,
        },
        header: {
          "content-type": "application/json",
          sign: getApp().globalData.headerSign,
        },
        success: (res) => {
          console.log("点赞结果:", res.data);
          if (res.data.success === "yes") {
            // 更新点赞状态
            if (!this.articleInfo.is_like) {
              this.articleInfo.like_count =
                (this.articleInfo.like_count || 0) + 1;
              this.articleInfo.is_like = true;
              uni.showToast({
                title: "点赞成功",
                icon: "none",
              });
            } else {
              this.articleInfo.like_count =
                (this.articleInfo.like_count || 0) - 1;
              this.articleInfo.is_like = false;
              uni.showToast({
                title: res.data.str,
                icon: "none",
              });
            }
          } else {
            uni.showToast({
              title: res.data.str,
              icon: "none",
            });
          }
        },
        fail: (e) => {
          console.log("点赞失败:", e);
          uni.showToast({
            title: "网络请求失败",
            icon: "none",
          });
        },
      });
    },
    // 关注作者
    followTheAuthor(n) {
      uni.$emit('check_login', () => {
        uni.request({
          url: this.$apiHost + "/Member/attention",
          data: {
            uuid: getApp().globalData.uuid,
            id: this.author.id,
          },
          header: {
            "content-type": "application/json",
            sign: getApp().globalData.headerSign,
          },
          success: (res) => {
            console.log("点赞结果:", res.data);
            uni.showToast({
              title: res.data.str,
              icon: "none",
            });
            if (res.data.success === "yes") {
              console.log("关注结果:", res.data, n);

              this.author.is_attention = n;
            }
          },
          fail: (e) => {
            console.log("关注失败:", e);
            uni.showToast({
              title: "网络请求失败",
              icon: "none",
            });
          },
        });
      })
    },
    // 分享文章
    shareArticle() {
      // 如果在微信小程序环境
      if (uni.getSystemInfoSync().platform === "mp-weixin") {
        uni.showShareMenu({
          withShareTicket: true,
          menus: ["shareAppMessage", "shareTimeline"],
        });
      } else {
        // 其他环境，如APP
        uni.share({
          provider: "weixin",
          scene: "WXSceneSession",
          type: 0,
          title: this.articleInfo.title,
          summary: this.articleInfo.content.substring(0, 40) + "...",
          imageUrl: this.home_image,
          success: function (res) {
            console.log("分享成功：" + JSON.stringify(res));
          },
          fail: function (err) {
            console.log("分享失败：" + JSON.stringify(err));
          },
        });
      }
    },
    // 切换音频播放状态
    toggleAudio() {
      if (!this.articleInfo.result_audio) return;

      if (this.isPlaying) {
        this.audioPlayer.pause();
        this.isPlaying = false;
      } else {
        this.audioPlayer.src = this.articleInfo.result_audio;
        this.audioPlayer.play();
        this.isPlaying = true;
      }
    },
    // 新增过滤器方法
    commaToArray(str) {
      if (!str) return "";
      return str.split(",");
    },

    // 新增过滤器方法
    addBrackets(str) {
      if (!str) return "";
      if (!str.startsWith("《")) {
        str = "《" + str;
      }
      if (!str.endsWith("》")) {
        str = str + "》";
      }
      return str;
    },
    getInfoData() {
      uni.request({
        url: this.$apiHost + "/Member/getinfoData",
        data: {
          uuid: getApp().globalData.uuid,
        },
        header: {
          "content-type": "application/json",
        },
        success: (res) => {
          console.log("用户信息", res.data);
        },
      });
    },
    showActionSheet(n) {
      uni.$emit('check_login', () => {
        if (n == 0) {
          // 如果只有一个分享按钮，直接唤醒分享弹窗
          this.showShare = true;
          return;
        }
        if (n == 1) {
          this.items = [
            {
              text: "分享作品",
              icon: "../../static/icon/cz_icon_fenxiangzuopin.png",
            },
            // {
            //   text: "修改封面",
            //   icon: "../../static/icon/cz_icon_xiugaifengmian.png",
            // },
            {
              text: "举报",
              icon: "../../static/icon/jubao.png",
            },
            {
              text: "删除作品",
              icon: "../../static/icon/sy_icon_shanchu.png",
              danger: true,
            },
          ];
        }
        this.$refs.actionSheet.show();
      })
    },
    handleActionCancel() {
      console.log("ActionSheet cancelled");
    },
    handleActionSelect(index, item) {
      console.log("ActionSheet selected index:", item.text);
      if (item.text === "分享作品") {
        this.showShare = true;
      } else if (item.text === "修改封面") {
        // 修改封面
        if (this.articleInfo.status == 3) {
          uni.showToast({
            title: '作品已完成，无法修改封面！',
            icon: 'none'
          });
          return;
        }
        this.editCover();
      } else if (item.text === "删除作品") {
        // 删除作品
        this.deleteWork();
      } else if (item.text === "举报") {
				this.handleReport();
			}
		},
		handleReport() {
			// 实现举报功能
			uni.$emit('check_login', () => {
				uni.navigateTo({
					url: '/pages/my/feedback'
				})
			})

		},
    // 修改封面
    editCover() {
      uni.showActionSheet({
        itemList: ['拍照', '从相册选择'],
        success: (res) => {
          const sourceType = res.tapIndex === 0 ? 'camera' : 'album';
          this.chooseImage(sourceType);
        }
      });
    },
    // 删除作品
    deleteWork() {
      this.$refs["customConfirm"]
        .confirm({
          title: "确认删除",
          content: "确定要删除这个作品吗？",
          DialogType: "inquiry",
          btn1: "再考虑一下",
          btn2: "确认解绑",
          animation: 0,
        })
        .then((res) => {
          if (res.confirm) {
            // 用户点击确定，执行删除操作
            this.confirmDelete();
          }
        });
    },
    // 确认删除
    confirmDelete() {
      uni.showLoading({
        title: '删除中...'
      });

      uni.request({
        url: this.$apiHost + '/Work/doAct',
        method: 'GET',
        data: {
          uuid: getApp().globalData.uuid,
          act: 'del',
          id: this.arcID
        },
        header: {
          'content-type': 'application/json',
          'sign': getApp().globalData.headerSign
        },
        success: (res) => {
          uni.hideLoading();
          if (res.data.success === "yes") {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            // 删除成功后返回上一页
            setTimeout(() => {
              uni.navigateBack({
                delta: 1
              });
            }, 1500);
          } else {
            uni.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        }
      });
    },
    goCreate() {
		console.log(222222222);
		let url=''
	if(this.articleInfo.lyrics ){
		url = "/pages/makedetail/makeMusicDetail"
	}else{
		url = "/pages/makedetail/makeImgDetail"
	}
	
	uni.navigateTo({
		url
	})
      // // 切换到标签页
      // uni.switchTab({
      //   // 指定要切换到的页面路径
      //   url: "/pages/make/index",
      // });
    },
    goToUserHomepage(id) {
      uni.$emit('check_login', () => {
        if (!id) {
          return;
        }
        uni.navigateTo({
          url: "/pages/my/userHomepage?id=" + id,
        });
      })
    },
    // 预览图片
    previewImage(url) {
      if (!url) return;
      uni.previewImage({
        urls: [url],
        current: url,
        indicator: 'number',
        loop: true,
				showmenu:false
      });
    },
    async chooseImage(sourceType) {
      try {
        let hasPermission = false;
        
        if (sourceType === 'camera') {
          hasPermission = await this.checkCameraPermission();
        } else if (sourceType === 'album') {
          hasPermission = await this.checkPhotoLibraryPermission();
        }

        if (!hasPermission) {
          uni.showToast({
            title: '未获得权限',
            icon: 'none'
          });
          return;
        }

        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: [sourceType],
          success: async (res) => {
            console.log('res:', res)
            if (res.tempFilePaths.length > 0) {
              this.imglocal = res.tempFilePaths[0]
              const tempFilePath = res.tempFilePaths[0];
              console.log('tempFilePaths:', tempFilePath);
              await this.uploadImage(tempFilePath);
            }
          },
          fail: (err) => {
            console.error('选择图片失败：', err);
            uni.showToast({
              title: '选择图片失败',
              icon: 'none'
            });
          }
        });
      } catch (error) {
        console.error('权限检查失败：', error);
        uni.showToast({
          title: '权限检查失败',
          icon: 'none'
        });
      }
    },
    async checkCameraPermission() {
      const hasPermission = await permission.request(permission.PermissionType.CAMERA, {
       title: '“萌创星球”想访问你的相机',
				describe: '萌创星球想访问您的摄像头，便于拍摄获取图片来替换原有作品封面图'
      });
      return hasPermission;
    },
    async checkPhotoLibraryPermission() {
      const hasPermission = await permission.request(permission.PermissionType.PHOTO_LIBRARY, {
       	title: '“萌创星球”想访问你的照片图库',
				describe: '萌创星球想访问您本地照片图库，便于获取图片来替换原有作品封面图'
      });
      return hasPermission;
    },
    uploadImage(tempFilePath) {
      const _self = this;
      const uploadTask = uni.uploadFile({
        url: _self.$apiHost + '/Xweb/upload_img?skey=' + _self.skey,
        filePath: tempFilePath,
        name: 'file',
        success: function(uploadFileRes) {
          let resdata = JSON.parse(uploadFileRes.data);
          console.log('Success:', uploadFileRes);
          console.log('Upload data:', resdata);
          if (resdata.success == 'yes') {
            _self.showRights = false;
            _self.home_image = resdata.url;
            uni.showToast({
              title: '图片上传成功',
              icon: 'success',
              duration: 1500
            });
          } else {
            uni.showToast({
              title: resdata.msg || '上传失败',
              icon: 'none',
              duration: 1500
            });
          }
        },
        fail: function(uploadFileFail) {
          console.error('Error:', uploadFileFail);
          uni.showToast({
            title: '上传失败，请重试',
            icon: 'none',
            duration: 1500
          });
        },
        complete: () => {
          console.log('Upload complete');
        }
      });

      // 显示上传进度
      uploadTask.onProgressUpdate((res) => {
        console.log('上传进度' + res.progress);
        console.log('已经上传的数据长度' + res.totalBytesSent);
        console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
      });
    },


    // 播放视频组件
    handleVideoPlay(e) {
      console.log('视频开始播放', e);
    },
    handleVideoPause(e) {
      console.log('视频暂停', e);
    },
    handleVideoEnded(e) {
      console.log('视频播放结束', e);
    },
  },
};
</script>

<style scoped lang="scss">
@import "workDetail.scss";

.permission-tip {
  width: 100%;
  height: 300rpx;
  background-color: rgba(255, 255, 255, 0.9);
  position: fixed;
  top: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 999;

  .permission-title {
    width: 90%;
    color: #000000;
    font-size: 38rpx;
    text-align: left;
    padding: 10rpx 20rpx;
    padding-top: 10rpx;
  }

  .permission-desc {
    width: 90%;
    color: #666666;
    font-size: 28rpx;
    text-align: left;
    padding: 10rpx 20rpx;
  }
}

.video-content {
  width: 100%;
  margin: 20rpx 0;
  background-color: #f5f5f5;
}
</style>
