<template>
  <u-popup v-model="visible" mode="bottom" border-radius="24" height="75%">
    <view class="gallery-panel">
      <view class="gallery-header">
        <text class="gallery-title">从文件库选择</text>
        <text class="gallery-close" @click="close">关闭</text>
      </view>

      <scroll-view scroll-x class="type-scroll" :show-scrollbar="false">
        <view class="type-tabs">
          <view
            v-for="tab in tabs"
            :key="tab.value"
            class="type-tab"
            :class="{ active: activeType === tab.value }"
            @click="switchType(tab.value)"
          >
            <text>{{ tab.label }}</text>
          </view>
        </view>
      </scroll-view>

      <view class="search-bar">
        <input
          v-model="keyword"
          class="search-input"
          placeholder="按文件名搜索"
          confirm-type="search"
          @confirm="onSearch"
          @input="onSearch"
        />
      </view>

      <scroll-view scroll-y class="gallery-scroll" @scrolltolower="loadMore">
        <view v-if="loading && !items.length" class="gallery-loading">加载中...</view>
        <view v-else-if="!items.length" class="gallery-empty">暂无文件</view>
        <view v-else class="gallery-grid">
          <view
            v-for="item in items"
            :key="item.id"
            class="gallery-item"
            @click="selectItem(item)"
          >
            <image v-if="item.type === 0" :src="item.url" class="gallery-thumb" mode="aspectFill" />
            <view v-else class="gallery-file-icon">
              <text class="file-type-tag">{{ item.type_text || '文件' }}</text>
              <text class="file-name">{{ item.file_name || item.original_name || '未命名' }}</text>
            </view>
            <text class="gallery-name">{{ item.file_name || item.original_name || '-' }}</text>
            <text class="gallery-size">{{ item.file_size_text || '' }}</text>
          </view>
        </view>
        <view v-if="loadingMore" class="gallery-loading">加载更多...</view>
        <view v-if="total > 0" class="gallery-total">共 {{ total }} 条</view>
      </scroll-view>
    </view>
  </u-popup>
</template>

<script>
import { req } from '@/common/js/index.js'
import { unwrapClinicRes } from '@/api/clinicAdmin.js'
import { cancelGalleryPick, resolveGalleryPick } from '@/subPackages/sub_salesperson/common/imageGalleryBridge.js'

const SALESPERSON_PREFIX = '/newApi/salesperson-file-gallery/'
const PLATFORM_PREFIX = '/newApi/platform-admin-file-gallery/'
const ALL_TYPE_VALUE = -1
const STORAGE_KEY = 'file-picker-active-type'

function getGalleryApiConfig() {
  const mode = uni.getStorageSync('loginMode')
  const prefix = mode === 'platform_admin' ? PLATFORM_PREFIX : SALESPERSON_PREFIX
  const headerKey = mode === 'platform_admin' ? '_platformAdmin' : '_salesperson'
  return { prefix, headerKey }
}

function galleryRequest(path, params) {
  const { prefix, headerKey } = getGalleryApiConfig()
  return req.request({
    url: `${prefix}${path}`,
    method: 'GET',
    data: params,
    header: { [headerKey]: '1' },
  })
}

export default {
  name: 'ImageGalleryPicker',
  data() {
    return {
      visible: false,
      loading: false,
      loadingMore: false,
      items: [],
      fileTypes: [],
      tabs: [{ value: ALL_TYPE_VALUE, label: '全部' }],
      activeType: ALL_TYPE_VALUE,
      keyword: '',
      page: 1,
      pageSize: 24,
      total: 0,
      searchTimer: null,
    }
  },
  created() {
    uni.$on('salesperson:open-gallery', this.open)
  },
  beforeDestroy() {
    uni.$off('salesperson:open-gallery', this.open)
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
  },
  methods: {
    async open() {
      this.visible = true
      this.page = 1
      this.items = []
      this.keyword = ''
      await this.loadFileTypes()
      this.restoreActiveType()
      await this.fetchList(true)
    },
    close() {
      this.visible = false
      cancelGalleryPick()
    },
    restoreActiveType() {
      const saved = uni.getStorageSync(STORAGE_KEY)
      if (saved === '' || saved === null || saved === undefined) {
        this.activeType = ALL_TYPE_VALUE
        return
      }
      const parsed = parseInt(saved, 10)
      if (parsed === ALL_TYPE_VALUE || this.tabs.some((t) => t.value === parsed)) {
        this.activeType = parsed
      } else {
        this.activeType = ALL_TYPE_VALUE
      }
    },
    async loadFileTypes() {
      try {
        const res = await galleryRequest('file-types')
        const data = unwrapClinicRes(res) || []
        this.fileTypes = Array.isArray(data) ? data : []
        this.tabs = [
          { value: ALL_TYPE_VALUE, label: '全部' },
          ...this.fileTypes.map((item) => ({ value: item.value, label: item.name, icon: item.icon })),
        ]
      } catch (e) {
        this.tabs = [{ value: ALL_TYPE_VALUE, label: '全部' }]
      }
    },
    buildParams() {
      const params = {
        page: this.page,
        page_size: this.pageSize,
        pid: 0,
      }
      if (this.activeType !== ALL_TYPE_VALUE) {
        params.type = this.activeType
      }
      const kw = (this.keyword || '').trim()
      if (kw) {
        params.keyword = kw
      }
      return params
    },
    async fetchList(reset) {
      if (reset) {
        this.loading = true
      } else {
        this.loadingMore = true
      }
      try {
        const res = await galleryRequest('list', this.buildParams())
        const data = unwrapClinicRes(res) || {}
        const list = data.items || []
        this.total = data.total || 0
        this.items = reset ? list : [...this.items, ...list]
      } catch (e) {
        uni.showToast({ title: '图库加载失败', icon: 'none' })
      } finally {
        this.loading = false
        this.loadingMore = false
      }
    },
    switchType(value) {
      this.activeType = value
      uni.setStorageSync(STORAGE_KEY, String(value))
      this.page = 1
      this.fetchList(true)
    },
    onSearch() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      this.searchTimer = setTimeout(() => {
        this.page = 1
        this.fetchList(true)
      }, 300)
    },
    loadMore() {
      if (this.loadingMore || this.items.length >= this.total) return
      this.page += 1
      this.fetchList(false)
    },
    selectItem(item) {
      if (!item || !item.url) return
      this.visible = false
      resolveGalleryPick(item.url)
    },
  },
}
</script>

<style scoped lang="scss">
.gallery-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}
.gallery-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.gallery-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1d2129;
}
.gallery-close {
  font-size: 28rpx;
  color: #86909c;
}
.type-scroll {
  white-space: nowrap;
  border-bottom: 1rpx solid #f0f0f0;
}
.type-tabs {
  display: inline-flex;
  padding: 16rpx 24rpx;
  gap: 16rpx;
}
.type-tab {
  padding: 10rpx 24rpx;
  border-radius: 999rpx;
  background: #f5f5f5;
  font-size: 24rpx;
  color: #4e5969;
  &.active {
    background: #e8f3ff;
    color: #165dff;
  }
}
.search-bar {
  padding: 16rpx 24rpx;
}
.search-input {
  width: 100%;
  height: 64rpx;
  padding: 0 24rpx;
  border-radius: 12rpx;
  background: #f5f5f5;
  font-size: 26rpx;
}
.gallery-scroll {
  flex: 1;
  height: 0;
}
.gallery-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
  padding: 24rpx;
}
.gallery-item {
  border-radius: 12rpx;
  overflow: hidden;
  background: #f5f5f5;
}
.gallery-thumb {
  width: 100%;
  height: 200rpx;
  display: block;
}
.gallery-file-icon {
  height: 200rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 12rpx;
}
.file-type-tag {
  font-size: 22rpx;
  color: #165dff;
  background: #e8f3ff;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}
.file-name {
  font-size: 22rpx;
  color: #4e5969;
  text-align: center;
  word-break: break-all;
}
.gallery-name {
  display: block;
  font-size: 22rpx;
  color: #1d2129;
  text-align: center;
  padding: 8rpx 8rpx 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.gallery-size {
  display: block;
  font-size: 20rpx;
  color: #86909c;
  text-align: center;
  padding: 4rpx 0 12rpx;
}
.gallery-loading,
.gallery-empty {
  text-align: center;
  padding: 80rpx 0;
  color: #86909c;
  font-size: 28rpx;
}
.gallery-total {
  text-align: center;
  padding: 16rpx 0 32rpx;
  color: #86909c;
  font-size: 24rpx;
}
</style>
