<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
  <cu-custom bgImage="/static/bg.png" :isBack="true">
    <template v-slot:content>
	  <text class="text-black">收藏夹</text>
    </template>
    <template v-slot:right>
      <text class="cuIcon cuIcon-add text-bold text-black" @click="handleEdit(null)"></text>
    </template>
  </cu-custom>
  <view>
    <scroll-view scroll-x class="bg-white nav text-center">
      <view class="cu-item" :class="index===checkIndex?'text-zblue text-bold cur':'text-bold text-black'" v-for="(item,index) in menuList" :key="index"
            @click="changCollect(index,item.type)" :data-id="index">
        {{ item.text }}
      </view>
    </scroll-view>
    <view class="cu-list menu">
      <view class="cu-item collect" :class="modalName=='move-box-'+ index?'move-cur':''" v-for="(item,index) in list"
            :key="index" :data-target="'move-box-' + index"
            @touchstart="ListTouchStart" @touchmove="ListTouchMove" @touchend="ListTouchEnd">
        <view class="content">
          <view class="text-grey">
            <rich-text v-if="!item.messageType||item.messageType===MessageType.text" style="word-break: break-all;"
                       :nodes="ChatUtils.transform(item.content)"></rich-text>
            <image style="max-width: 150upx;" v-if="item.messageType===MessageType.image && item.extend"
                   :src="item.extend.url"
                   mode="widthFix"></image>
            <view v-if="item.messageType===MessageType.file && item.extend && item.extend.url && item.extend.fileName">
              <text class="cuIcon cuIcon-down" style="color: #666666;"></text>
              <uni-link color="#666666" class="text-black" :href="item.extend.url"
                        :text="item.extend.fileName"></uni-link>
            </view>
            <view v-if="item.messageType===MessageType.voice" class="main">
              <view @click="handleAudio(item)">
                <text>{{ item.extend?.time }}"</text>
                <text class="cuIcon-sound text-xxl padding-right-xl"></text>
              </view>
            </view>
            <view v-if="item.messageType===MessageType.forward" class="main">
              <message-multiple-forward :message="item"/>
            </view>
            <view v-if="item.messageType===MessageType.video && item.extend && item.extend.url" class="main">
              <video :src="item.extend.url" controls style="width: 70vw"></video>
              <dom-video :src="item.extend.url" :controls='true' objectFit="contain"/>
            </view>
          </view>
          <view class="text-gray text-sm">
            <user-name-tag :id="item.fromId"/>
          </view>
        </view>
        <view class="action">
          <view class="text-grey text-xs">
            <Time :time="item.createTime"></Time>
          </view>
        </view>
        <view class="move">
          <view class="bg-orange" v-if="item.messageType === MessageType.text" @click="handleEdit(item.id)">编辑</view>
          <view class="bg-red" @click="handleDelete(item.id)">删除</view>
        </view>
      </view>
    </view>
  </view>

  <view class="cu-modal" :class="showAddCollect?'show':''">
    <view class="cu-dialog">
      <view class="cu-bar bg-white justify-end">
        <view class="content text-bold text-black">收藏</view>
        <view class="action" @tap="showAddCollect = false">
          <text class="cuIcon-close text-red"></text>
        </view>
      </view>
      <view class="padding-xl bg-gray">
        <textarea v-model="collectContent" rows="10"></textarea>
      </view>
      <view class="cu-bar bg-white">
        <view class="action margin-0 flex-sub text-green solid-left text-bold" @tap="showAddCollect = false">取消</view>
        <view class="action margin-0 flex-sub  solid-left text-bold" @tap="margeCollect">确定</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import {onActivated, ref} from "vue";
import Auth from "@/api/Auth";


import CollectApi from "@/api/CollectApi";
import type Collect from "@/mode/Collect";
import MessageType from "@/utils/MessageType";
import UserNameTag from "@/components/UserNameTag.vue";
import {match} from "pinyin-pro";
import CuCustom from "@/colorui/components/cu-custom.vue";
import Time from "@/components/Time.vue";
import ChatUtils from "@/utils/ChatUtils";
import UniLink from "@/uni_modules/uni-link/components/uni-link/uni-link.vue";
import MessageMultipleForward from "@/components/messages/MessageMultipleForward.vue";
import type Message from "@/mode/Message";

import domVideo from "@/components/ls-dom-video/ls-dom-video.vue";

const fontValue=ref(Auth.getfontSize());

const Audio = ref(uni.createInnerAudioContext());
const menuList = ref([
  {
    icon: "icon-v-quanbu",
    text: "全部",
    type: "",
    active: true,
  },
  {
    icon: "icon-v-24gl-fileText",
    text: "文本",
    type: MessageType.text,
    active: false,
  },
  {
    icon: "icon-v-tupian1",
    text: "图片",
    type: MessageType.image,
    active: false,
  },
  {
    icon: "icon-v-wj-wjj",
    text: "文件",
    type: MessageType.file,
    active: false,
  },
  {
    icon: "icon-v-yuyin",
    text: "语音",
    type: MessageType.voice,
    active: false,
  },
]);
const list = ref(new Array<Collect>());
const checkIndex = ref(0);
const showAddCollect = ref(false);
const collectContent = ref("");
const keyword = ref("");
const collect = ref<Collect>({
  id: undefined,
  fromId: undefined,
  content: "",
  messageType: MessageType.text,
  extend: undefined,
});

//控制播放还是暂停音频文件
const handleAudio = (item: any) => {
  Audio.value.paused ? playAudio(item) : stopAudio();
}
//播放音频
const playAudio = (item: any) => {
  Audio.value.src = item.extend.url
  Audio.value.play();
}
//停止音频
const stopAudio = () => {
  Audio.value.src = '';
  Audio.value.stop();
}
const listTouchStart = ref(0);
const listTouchDirection = ref();
const modalName = ref();

// ListTouch触摸开始
const ListTouchStart = (e: any) => {
  listTouchStart.value = e.touches[0].pageX
}
// ListTouch计算方向
const ListTouchMove = (e: any) => {
  listTouchDirection.value = e.touches[0].pageX - listTouchStart.value > 0 ? 'right' : 'left'
}
// ListTouch计算滚动
const ListTouchEnd = (e: any) => {
  if (listTouchDirection.value == 'left') {
    modalName.value = e.currentTarget.dataset.target
  } else {
    modalName.value = null
  }
  listTouchDirection.value = null
}
const keywordFilter = (items: any[], keyword: string): any[] => {
  return items.filter((item) => {
    if (keyword.trim() === "" || match(item.content, keyword)) {
      return true;
    } else if (
        item.extend &&
        item.extend.fileName &&
        match(item.extend.fileName, keyword)
    ) {
      return true;
    } else {
      return false;
    }
  });
};

/**
 * 选择收藏类型
 * @param index 索引
 * @param type 选中项
 */
const changCollect = (index: number, type: string) => {
  checkIndex.value = index;
  loadData(type);
};

/**
 * 加载数据
 * @param type 收藏类型
 */
const loadData = (type: string) => {
  CollectApi.list(type).then((res) => {
    list.value = res.data.map((item: any) => {
      if (item.extend) {
        item.extend = JSON.parse(item.extend);
      }
      return item;
    });
  });
};

onActivated(() => {
  // 初始化加载数据
  loadData(menuList.value[checkIndex.value].type);
});

loadData('')
/**
 * 编辑收藏
 * @param id 收藏id
 */
const handleEdit = (id: string | undefined) => {
  showAddCollect.value = true;
  collectContent.value = "";
  if (typeof id === "string") {
    CollectApi.get(id).then((res) => {
      collect.value = res.data;
      collectContent.value = res.data.content;
    });
  }
};

/**
 * 删除收藏
 * @param id 收藏id
 */
const handleDelete = (id: string | undefined) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除吗？',
    cancelText: '取消',
    confirmText: '删除',
    success: res => {
      if (res.confirm && id) {
        CollectApi.delete(id).then(() => {
          loadData(menuList.value[checkIndex.value].type);
        });
      }
    }
  })
}

/**
 * 保存或者删除
 */
const margeCollect = () => {
  collect.value.content = collectContent.value;
  const p = collect.value.id
      ? CollectApi.update(collect.value)
      : CollectApi.save(collect.value);
  p.then(() => {
    showAddCollect.value = false;
    checkIndex.value = 0;
    loadData("");
    collect.value = {
      id: undefined,
      fromId: undefined,
      content: "",
      messageType: MessageType.text,
      extend: undefined,
    };
  });
};
</script>

<style scoped lang="scss">
.collect {
  margin-top: 15px;
}
</style>
