<template>
  <view style="padding: 5px;">
    <uni-list :border="false">
      <uni-swipe-action ref="swiper_action">
        <uni-swipe-action-item :right-options="options" v-for="item in docList" :key="item.id" :threshold="5"
          @click="(e: any) => handlerDocument(e, item)">
          <uni-list-item>
            <template v-slot:header>
              <view class="slot-box">
                <i v-if="fileSuffix.includes(item.extension)" :class="`my my-${item.extension}`"
                  style="width: 35px;height: 35px;"></i>
                <i v-else class="my my-other" style="width: 35px;height: 35px;"></i>
              </view>
            </template>
            <template v-slot:footer>
              <view class="slot-content" @click="redirectDocDetailPage(item.id)">
                <view class="slot-title">
                  <text v-if="!item.showDownloadProgress">{{ item.filename }}</text>
                  <custom-progress v-model:value="item.downloadProgress" :stroke-width="16" style="width: 100%"
                    v-else></custom-progress>
                </view>
                <view class="slot-subtitle">{{ formatBytesOptimized(item.size) }}</view>
              </view>
            </template>
          </uni-list-item>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </uni-list>
  </view>
</template>
<script lang="ts" setup>
import { getDownloadDocumentUrl, removeDocument } from '@/api/project-center/document';
import { PrjDocument } from '@/types/document';
import { formatBytesOptimized } from '@/utils'
import customProgress from '@/components/cu-progress/index.vue'
import { downloadFile, saveFile } from '@/api/base/client';
import { useEmitt } from '@/logics/mitt/useEmitt';
const swiper_action = ref()


const { emitter } = useEmitt()
const fileSuffix = [
  'png',
  'ppt',
  'jpg',
  'image',
  'ofd',
  'bmp',
  'mp4',
  'htm',
  'excel',
  'ceb',
  'ett',
  'dpt',
  'docx',
  'gif',
  'flv',
  'doc',
  'dps',
  'pdf',
  'jasper',
  'dwg',
  'java',
  'tiff',
  'jpeg',
  'rtf',
  'dot',
  'et',
  'wpt',
  'xsd',
  'txt',
  'pptx',
  'wps',
  'ps',
  'xlsx',
  'giff',
  'tif',
  'xls',
  'html',
  'word',
  'sep',
  'gd',
  'wt',
  'svg',
  'cebx',
  'xml',
  'zip'
]

const props = defineProps({
  docList: {
    type: Array as PropType<PrjDocument[]>
  },
  archived: {
    type: Boolean,
    default: () => {
      return undefined
    }
  }
})

// 获取swiper action操作按钮
const options = computed(() => {
  const list = [
    {
      text: '下载',
      style: {
        backgroundColor: '#007aff',
        margin: "5px 0"
      }
    },
    {
      text: '删除',
      style: {
        backgroundColor: '#dd524d',
        margin: "5px 0"
      }
    }
  ]
  return !props.archived ? list : list.filter(item=> item.text !=='删除')
})


// 左滑菜单点击
const handlerDocument = async (e: { index: number }, doc: PrjDocument) => {
  const { index } = e;
  const isDownload = index === 0;
  const isRemove = index === 1;
  if (isRemove) {
    uni.showModal({
      title: '警告',
      content: `是否删除文档：${doc.filename}`,
      success: async (res: { confirm: boolean }) => {
        const { confirm } = res;
        if (confirm) {
          await removeDocument({ id: doc.id })
          emitter.emit('get_doc_list')
        }
      }
    })
    return;
  }
  if (isDownload) {
    startDownloadContractFile(doc, doc.filename)
    swiper_action.value?.closeAll()
  }
}

// 选择下载后分享到好友，还是添加收藏
const startDownloadContractFile = async (doc: PrjDocument, filename?: string) => {
  uni.showActionSheet({
    itemList: ['分享到好友', '添加到收藏'],
    success: async (res: UniApp.ShowActionSheetRes) => {
      await handlerDownloadFile(doc, filename, res.tapIndex)
    }
  });

}

// 监听下载进度条
const onDownloadProgressResult = (e: UniApp.OnProgressDownloadResult, doc: PrjDocument) => {
  doc.showDownloadProgress = true
  doc.downloadProgress = e.progress
}




// 下载文档文件
const handlerDownloadFile = async (doc: PrjDocument, filename?: string, sheetIndex?: number) => {
  try {
    const { url } = await getDownloadDocumentUrl({ id: doc.id })
    const { savedFilePath } = await downloadFile({ url, downloadProgress: onDownloadProgressResult, otherParams: doc, filename })
    await saveFile(savedFilePath, filename, sheetIndex)
    doc.showDownloadProgress = false
    doc.downloadProgress = 0
  } catch (_e) {
    doc.showDownloadProgress = false
    doc.downloadProgress = 0
  }
}


// 跳转到项目文档详情
const redirectDocDetailPage = (id: string) => {
  uni.navigateTo({ url: `/pages/project/components/doc-detail?id=${id}&source=${props.archived?1:0}` })
}

</script>

<script lang="ts">
export default {
  options: {
    styleIsolation: 'shared', //解除样式隔离
  }

}
</script>
<style scoped>
.c-nav-bar {
  width: 100%
}

.slot-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-right: 10px;
}


.slot-content {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  width: 100%;
}

.slot-panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  line-height: 18px;
  justify-content: left;
}

.slot-title {
  font-size: 12px;
  color: #3b4144;
  overflow-wrap: anywhere;
  text-overflow: ellipsis;
  white-space-collapse: collapse;
  text-wrap: wrap;
  overflow: hidden;
  line-height: 1.5715;
  white-space: normal;
}

.slot-subtitle {
  font-size: 12px;
  color: #999;
  padding-top: 5px;
}

:deep(.uni-list-item > .uni-list-item__container) {
  align-items: center !important;
  padding: 10px !important;
}

:deep(.uni-list-item__content) {
  display: none;
}



:deep(.ayi-progress__text) {
  text-align: right !important;
  width: 50rpx !important;
}
</style>
