<script setup lang="ts">
import Tabbar from '../components/tabbar.vue'
import { filterDay, timeFormat } from '../utils'
import { StaticUrl } from '@/config'

const route = useRoute()
const router = useRouter()
const addressStore = useAddressStore()
const { Location } = storeToRefs(addressStore)
definePage({
  name: 'film-movie',
  islogin: false,
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '电影演出',
    backgroundColorBottom: '#fff',
  },
})
const active = ref(route.query?.active || 0)
const tabList = reactive([
  { title: '热映', path: 'film-index' },
  { title: '影院', path: 'film-movie' },
  { title: '待映', path: 'film-order' },
])

const { data: hotList, isLastPage, page, reload, error, refresh } = usePagination((pageNum, pageSize) =>
  Apis.film.getMovieList({ data: { showSt: 1, pageNum, pageSize } }), {
  data: resp => resp.data?.records,
  initialData: [],
  initialPage: 1,
  initialPageSize: 10,
  append: true,
  immediate: false,
})

const { data: filmList, isLastPage: isLastPage1, page: page1, reload: reload1, error: error1, refresh: refresh1 } = usePagination(() =>
  Apis.film.getFilmList({ data: { movieId: '', lat: Location.value.latitude, lng: Location.value.longitude } }), {
  data: resp => resp.data,
  initialData: [],
  initialPage: 1,
  initialPageSize: 10,
  append: true,
  immediate: false,
})

const { data: comingSoonList, isLastPage: isLastPage2, page: page2, reload: reload2, error: error2, refresh: refresh2 } = usePagination((pageNum, pageSize) =>
  Apis.film.getMovieList({ data: { showSt: 2, pageNum, pageSize } }), {
  data: resp => resp.data?.records,
  initialData: [],
  initialPage: 1,
  initialPageSize: 10,
  append: true,
  immediate: false,
})

const state = computed(() => {
  if (active.value === 0) {
    return error.value ? 'error' : !isLastPage.value ? 'loading' : 'finished'
  }
  else if (active.value === 1) {
    return error1.value ? 'error' : !isLastPage2.value ? 'loading' : 'finished'
  }
  else {
    return error2.value ? 'error' : !isLastPage2.value ? 'loading' : 'finished'
  }
})
function loadData() {
  console.log('loadData')
  if (active.value === 0) {
    reload()
  }
  else if (active.value === 1) {
    reload1()
  }
  else if (active.value === 2) {
    reload2()
  }

  uni.pageScrollTo({
    scrollTop: 0, // 滚动目标位置（0 = 页面最顶部，核心参数）
    duration: 0, // 滚动动画时长，单位ms（可选，默认300，设0为无动画瞬间滚动）
  })
}

function refreshData() {
  if (Number(active.value) === 0) {
    refresh()
  }
  else if (Number(active.value) === 1) {
    refresh1()
  }
  else if (Number(active.value) === 2) {
    refresh2()
  }
}
function addPageNum() {
  if (active.value === 0) {
    if (!isLastPage.value) {
      page.value++
    }
  }
  else if (active.value === 1) {
    if (!isLastPage1.value) {
      page1.value++
    }
  }
  else if (active.value === 2) {
    if (!isLastPage2.value) {
      page2.value++
    }
  }
}

onLoad((options) => {
  console.log('onload', options)

  active.value = Number(options?.active || 0)
  refreshData()
})
onReachBottom(() => {
  console.log('onReachBottom', state.value)
  addPageNum()
})

function handleItem(index: number) {
  active.value = index
  loadData()
  console.log('handle', state.value)
}

function handleFilm(title: string, movieId: string, cinemaId: string) {
  router.push({
    name: 'film-select-time',
    params: {
      id: '2221',
      title,
      movieId,
      cinemaId,
    },
  })
}

function handleBuy(item: Api.filmMovieList) {
  router.push({ name: 'film-movie-detail', params: { id: item.id as string, movieId: item.movieId as string } })
}

function handleWant(item: Api.filmMovieList) {
  router.push({ name: 'film-movie-detail', params: { id: item.id as string, movieId: item.movieId as string } })

  // useGlobalToast().show('敬请期待')
}

onMounted(() => {
  if (!Location.value.latitude) {
    useAddressStore().getLocation()
  }
})
</script>

<template>
  <view class="movies">
    <wd-navbar
      title="" :bordered="false" :z-index="99" safe-area-inset-top left-arrow placeholder fixed
      @click-left="router.back()"
    >
      <template #left>
        <view class="flex items-center">
          <wd-icon name="arrow-left" size="22px" color="#000" />
        </view>
      </template>
      <template #title>
        <view class="tabbar">
          <view v-for="(item, index) in tabList" :key="index" class="item" @click="handleItem(index)">
            <view class="title" :class="[active == index ? 'active' : '']">
              {{ item.title }}
            </view>
          </view>
        </view>
      </template>
    </wd-navbar>

    <!-- 热映 列表 -->
    <view v-if="active == 0" class="list">
      <view v-for="(item, index) in hotList" :key="index" class="item">
        <view class="img-box">
          <image class="img" :src="item.posterUrl" />
          <view class="tag">
            {{ item.version }}
          </view>
        </view>
        <view class="info">
          <view class="title">
            {{ item.name }}
          </view>
          <view class="num-box">
            <view class="score-box">
              <view class="label">
                评分
              </view>
              <view class="score">
                {{ item.score }}
              </view>
            </view>
            <view class="num">
              {{ item.wish }}人想看
            </view>
          </view>
          <view class="type-box">
            <view class="type">
              {{ item.category }} |
            </view>
            <view class="time">
              {{ item.duration }}分钟
            </view>
          </view>
          <view class="director">
            导演：{{ item.director }}
          </view>
          <view class="actor">
            演员：{{ item.star }}
          </view>
        </view>
        <view class="btn-box">
          <image class="img" :src="`${StaticUrl}/film-movie-icon.png`" mode="scaleToFill" />
          <view class="btn" @click="handleBuy(item)">
            购票
          </view>
        </view>
      </view>
    </view>

    <!-- 影院 列表 -->
    <view v-else-if="active == 1" class="film-list">
      <view
        v-for="(item, index) in filmList" :key="index" class="film-item"
        @click="handleFilm(item.name, '', item.cinemaId)"
      >
        <view class="name-box">
          <view class="name w-450rpx overflow-hidden text-ellipsis whitespace-nowrap">
            {{ item.name }}
          </view>
          <view class="price-box">
            <view class="num">
              ￥{{ item.sellPrice }}
            </view>
            <div class="label">
              起
            </div>
          </view>
        </view>
        <view class="address-box">
          <view class="address overflow-hidden text-ellipsis whitespace-nowrap">
            {{ item.address }}
          </view>
          <view class="distance">
            {{ item.distance }}km
          </view>
        </view>
        <div class="cantact">
          {{ item.phone || '暂无联系方式' }}
        </div>
        <div class="movie-box">
          <!-- 今日热映：《疯狂动物城2》《阿凡达3》《匿杀》《惊天魔... -->
        </div>
      </view>
    </view>

    <!-- 待映映 列表 -->
    <view v-else-if="active == 2" class="list soon-list">
      <view v-for="(item, index) in comingSoonList" :key="index" class="item">
        <view class="img-box">
          <image class="img" :src="item.posterUrl" />
          <view class="tag">
            {{ item.version }}
          </view>
        </view>
        <view class="info">
          <view class="title">
            {{ item.name }}
          </view>
          <view class="num-box">
            <view class="score-box">
              <view class="label">
                想看:
              </view>
              <view class="score">
                {{ item.wish }}人
              </view>
            </view>
            <!-- <view class="num">
              {{ item.wish }}人想看
            </view> -->
          </view>
          <view class="type-box">
            <view class="type">
              上映时间： {{ `${timeFormat(item.releaseTime, 'MM-dd')} (${filterDay(timeFormat(item.releaseTime, 'yyyy-MM-dd'))})` }}
            </view>
          </view>
          <view class="director">
            导演：{{ item.director }}
          </view>
          <view class="actor">
            演员：{{ item.star }}
          </view>
        </view>
        <view class="btn-box">
          <image class="img" :src="`${StaticUrl}/film-movie-icon.png`" mode="scaleToFill" />
          <view class="btn" @click="handleWant(item)">
            想看
          </view>
        </view>
      </view>
    </view>
    <wd-loadmore :state="state" :loading-props="{ color: '#9ED605', size: 20 }" @reload="reload" />

    <Tabbar :active="1" />
  </view>
</template>

<style lang="scss" scoped>
.movies{
  padding: 16rpx 24rpx 350rpx;
  background: #F9F9F9;

  .tabbar {
      display: flex;
      justify-content: space-between;
      padding: 0 60rpx;
      .item {
          flex: 1;
          text-align: center;

          .title {
              font-weight: bold;
              font-size: 36rpx;
              color: #AAAAAA;

              &.active {
                  color: #222222;
              }
          }

      }
  }
  .list{
    .item{
      background: #FFFFFF;
      border-radius: 16rpx 16rpx 16rpx 16rpx;
      display: flex;
      padding: 28rpx 24rpx;
      position: relative;
      margin-bottom: 20rpx;
      .img-box{
        position: relative;
        margin-right: 24rpx;
        .img{
          width: 152rpx;
          height: 208rpx;
          border-radius: 16rpx;
          vertical-align: top;
        }
        .tag{
          line-height: 26rpx;
          background: rgba(34, 34, 34, 0.7);
          border-radius: 8rpx 8rpx 8rpx 8rpx;
          font-size: 18rpx;
          color: #FFFFFF;
          padding: 0 10rpx;
          position: absolute;
          top: 4rpx;
          right: 4rpx;

        }
      }
      .info{
        .title{
          font-weight: bold;
          font-size: 32rpx;
          color: #222222;
          width: 330rpx;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
        .num-box{
          display: flex;
          align-items: flex-end;
          margin-top: 8rpx;
          line-height: 28rpx;
          .score-box{
            display: flex;
            align-items: flex-end;
            .label{
              font-size: 24rpx;
              color: #AAAAAA;
            }
            .score{
              font-weight: bold;
              font-size: 28rpx;
              color: #FF4D3A;
              margin-left: 6rpx;
            }
          }
          .num{
            font-size: 24rpx;
            color: #AAAAAA;
            margin-left: 8rpx;
          }
        }
        .type-box{
          display: flex;
          margin-top: 8rpx;

            .type {
            font-size: 24rpx;
            color: #AAAAAA;
          }
          .time{
            font-size: 24rpx;
            color: #AAAAAA;
          }
        }
        .director{
          font-size: 24rpx;
          color: #AAAAAA;
          margin-top: 8rpx;
          }
        .actor{
          font-size: 24rpx;
          color: #AAAAAA;
          margin-top: 8rpx;
          width: 470rpx;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
          }
      }
      .btn-box{
        position: absolute;
        top: 0;
        right: 0;
        .img{
          width: 172rpx;
          height: 150rpx;
        }
        .btn{
          position: absolute;
          bottom: 0;
          left: calc(50% - 60rpx);
          width: 120rpx;
          height: 52rpx;
          line-height: 52rpx;
          text-align: center;
          background: #9ED605;
          border-radius: 26rpx 26rpx 26rpx 26rpx;
          font-size: 28rpx;
          color: #FFFFFF;
        }
      }
    }
  }
  .list.soon-list .btn-box .btn{
    background: #FFB639;
  }

    .film-list {

      .film-item {
        background: #FFF;
        border-radius: 16rpx 16rpx 16rpx 16rpx;
        padding: 24rpx;
        margin-bottom: 20rpx;

        .name-box {
          display: flex;
          justify-content: space-between;
          margin-bottom: 16rpx;

          .name {
            font-weight: bold;
            font-size: 28rpx;
            color: #222222;
          }

          .price-box {
            display: flex;
            align-items: center;

            .num {
              font-weight: bold;
              font-size: 36rpx;
              color: #FF4D3A;
            }

            .label {
              font-size: 24rpx;
              color: #AAAAAA;
            }
          }
        }

        .address-box {
          display: flex;
          justify-content: space-between;
          font-size: 24rpx;
          color: #AAAAAA;
          margin-bottom: 16rpx;

          .address {
            font-size: 24rpx;
            color: #AAAAAA;
          }

          .distance {}
        }

        .cantact {
          font-size: 24rpx;
          color: #AAAAAA;
          margin-bottom: 16rpx;
        }

        .movie-box {
          font-size: 24rpx;
          color: #222222;
          width: 100%;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }
    }
}
</style>
