import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch,
  nextTick
} from 'vue'
import {
  Image,
  Tabs,
  Tab,
  List,
  Button,
  Popup,
  Dialog,
  Sticky,
  Swipe,
  SwipeItem
} from 'vant'
import styles from './index.module.less'
import TheSticky from '@/components/the-sticky'
import ColHeader from '@/components/col-header'
import { useWindowScroll, useEventListener } from '@vueuse/core'
import request from '@/helpers/request'
import iconMenu from './images/icon-menu.png'
import iconRightTop from './images/icon-right-top.png'
import iconAlbumCover from '../../images/icon-album-cover.png'
import iconTimer from './images/icon-timer.png'
import { state as baseState, setLogout } from '@/state'
import Song from '../component/song'
import { useRoute, useRouter } from 'vue-router'
import ColResult from '@/components/col-result'
import { moneyFormat } from '@/helpers/utils'
import { orderStatus } from '@/views/order-detail/orderStatus'
import { postMessage } from '@/helpers/native-message'
import { browser } from '@/helpers/utils'
// Import Swiper Vue.js components
// import Swiper core and required modules
import { Pagination } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/vue'
// Import Swiper styles
import 'swiper/css'
import 'swiper/css/pagination'
import CourseItem from '../lessonCourseware/component/CourseItem'

export default defineComponent({
  name: 'train-tool',
  setup() {
    const sessionStorageToolSubject =
      sessionStorage.getItem('tool-subject-type')
    const toolSubject =
      sessionStorageToolSubject && JSON.parse(sessionStorageToolSubject)
    sessionStorage.removeItem('tool-subject-type')

    const route = useRoute()
    const router = useRouter()
    const background = ref<string>('rgba(55, 205, 177, 0)')
    const color = ref<string>('#fff')
    const state = reactive({
      details: {} as any,
      buy: route.query.buy as any,
      albumId: route.query.albumId || null,
      activeTab:
        toolSubject?.activeTab || route.query.subjectType || 'COURSEWARE', // 有缓存 默认用缓存,之后用请求头，最后默认
      loadingAlbum: false,
      loading: false,
      finished: false,
      isError: false,
      list: [] as any,
      popupStatus: false,
      selectMember: {} as any, // 购买的月份
      ensembleCounts: false,
      musicCounts: false,
      subjectCounts: false,
      coursewareCounts: false,
      tenantAlbumStatus: 0 as any,
      ablumStatus: false,
      heightV: 0,
      hasBuyStatus: true, // 是否能继续购买
      albumList: [] as any, // 专辑列表
      initialSlide: 0
    })
    const params = reactive({
      page: 1,
      rows: 20
    })
    const apiSuffix = ref(
      baseState.platformType === 'STUDENT' ? '/api-student' : '/api-teacher'
    )

    const isSingleAlbum = computed(() => {
      const query = route.query
      if (query.taId || (query.albumId && state.buy === '1')) {
        return true
      } else {
        return false
      }
    })

    const getDetails = async () => {
      state.loadingAlbum = true
      try {
        // tenantGroupAlbum/buyAlbumInfo
        // 当我的曲目过来的时候才走单个查询
        if (state.albumId && state.buy === '1') {
          let url = apiSuffix.value + '/userTenantAlbumRecord/detail'
          if (state.albumId) {
            url = url + '?albumId=' + state.albumId
          }
          const { data } = await request.post(url)
          state.albumList = [data || {}]
          state.details = data || {}
        } else {
          const url =
            apiSuffix.value +
            `/tenantGroupAlbum/buyAlbumInfo?tenantGroupAlbumId=${
              route.query.taId || ''
            }`
          //&tenantAlbumId=${state.albumId || ''}
          // if (state.albumId) {
          //   url = url + '?albumId=' + state.albumId
          // }
          const { data } = await request.get(url)
          state.albumList = data || []
          if (state.albumList.length > 0) {
            let index = 0
            // 以缓存为优先 其次 请求头 state.albumId
            if (toolSubject?.tenantGroupAlbumId || state.albumId) {
              index = state.albumList.findIndex(item => {
                return toolSubject?.tenantGroupAlbumId
                  ? (baseState.platformType === 'STUDENT'
                      ? item.tenantGroupAlbumId
                      : item.id) === toolSubject?.tenantGroupAlbumId
                  : item.id == state.albumId // 这里不全等 因为state.albumId为字符串 id为number
              })
              index < 0 && (index = 0)
            }
            state.initialSlide = index //默认展示第几个
            state.details = state.albumList[index] // 有缓存  就用缓存里面的数据
          } else {
            // state.albumList
            if (!browser().isApp) {
              Dialog.alert({
                title: '提示',
                message: '该教程不可购买',
                confirmButtonText: '确定',
                confirmButtonColor: '#2dc7aa'
              }).then(() => {
                if (browser().isApp) {
                  postMessage({ api: 'back' })
                } else {
                  setLogout()
                  router.replace({
                    path: '/login' as any,
                    query: {
                      returnUrl: '/train-tool',
                      ...route.query
                    }
                  })
                }
              })
            }
          }
        }
      } catch {
        //
      }
      state.loadingAlbum = false
    }

    watch(
      () => state.details,
      () => {
        state.ensembleCounts = state.details?.ensembleCounts ? true : false
        state.subjectCounts = state.details?.subjectCounts ? true : false
        state.musicCounts = state.details?.musicCounts ? true : false
        state.coursewareCounts = state.details?.coursewareCounts ? true : false
        if (state.details.buyTimesFlag) {
          if (state.details.buyedTimes >= state.details.buyTimes) {
            state.hasBuyStatus = false
          } else {
            state.hasBuyStatus = true
          }
        } else {
          state.hasBuyStatus = true
        }
      }
    )
    let listController
    const FetchList = async (hideLoading = false) => {
      if (!state.details.id) {
        return
      }
      if (listController) {
        listController.abort()
      }
      state.loading = true
      state.isError = false
      const tempParams = {
        albumId: state.details.id || null,
        subjectType: state.activeTab,
        ...params
      }

      try {
        listController = new AbortController()
        const { signal } = listController
        const { data } = await request.post(
          `${apiSuffix.value}/tenantAlbumMusic/page`,
          {
            hideLoading,
            data: tempParams,
            signal
          }
        )
        if (state.list.length > 0 && data.pageNo === 1) {
          return
        }
        state.list = state.list.concat(data.rows || [])
        params.page = data.pageNo + 1
        // showContact.value = state.list.length > 0
        state.loading = false
        state.finished = data.pageNo >= data.totalPage
        params.page = data.pageNo + 1
      } catch (error) {
        state.isError = true
      }
      state.loading = false
    }

    onMounted(async () => {
      // useEventListener(document, 'scroll', evt => {
      //   const { y } = useWindowScroll()
      //   if (y.value > 20) {
      //     background.value = `rgba(255, 255, 255)`
      //   } else {
      //     background.value = 'transparent'
      //   }
      // })

      state.loading = true
      state.loadingAlbum = true
      await getDetails()
      await FetchList()
      state.loadingAlbum = false
      state.loading = false

      // 为了处理 swiper 会不显示的问题
      document.body.scrollIntoView()
      window.scrollTo(1, 0)
    })
    function handleChangeActiveTab() {
      state.activeTab = state.details?.coursewareCounts
        ? 'COURSEWARE'
        : state.details?.subjectCounts
        ? 'SUBJECT'
        : state.details?.musicCounts
        ? 'MUSIC'
        : 'ENSEMBLE'
    }
    const onSubmit = async () => {
      const album = state.details
      const details = state.details
      orderStatus.orderObject.orderType = 'TENANT_ALBUM'
      orderStatus.orderObject.orderName = details.name
      orderStatus.orderObject.orderDesc = details.name
      orderStatus.orderObject.actualPrice = album.actualPrice
      // orderStatus.orderObject.recomUserId = route.query.recomUserId || 0
      // orderStatus.orderObject.activityId = route.query.activityId || 0
      orderStatus.orderObject.orderNo = ''
      orderStatus.orderObject.orderList = [
        {
          orderType: 'TENANT_ALBUM',
          goodsName: details.name,
          actualPrice: album.actualPrice,
          price: album.actualPrice,
          ...details,
          ...album
        }
      ]

      const res = await request.post('/api-student/userOrder/getPendingOrder', {
        data: {
          goodType: 'TENANT_ALBUM',
          bizId: details.id
        }
      })

      const result = res.data
      if (result) {
        state.popupStatus = false
        Dialog.confirm({
          title: '提示',
          message: '您有一个未支付的订单，是否继续支付？',
          theme: 'round-button',
          className: 'confirm-button-group',
          cancelButtonText: '取消订单',
          confirmButtonText: '继续支付'
        })
          .then(async () => {
            orderStatus.orderObject.orderNo = result.orderNo
            orderStatus.orderObject.actualPrice = result.actualPrice
            orderStatus.orderObject.discountPrice = result.discountPrice
            orderStatus.orderObject.paymentConfig = {
              ...result.paymentConfig,
              paymentVendor: result.paymentVendor,
              paymentVersion: result.paymentVersion
            }

            routerTo()
          })
          .catch(() => {
            Dialog.close()
            // 只用取消订单，不用做其它处理
            cancelPayment(result.orderNo)
          })
      } else {
        routerTo()
      }
    }
    const routerTo = () => {
      const album = state.details
      sessionStorage.setItem(
        'tool-subject-type',
        JSON.stringify({
          activeTab: state.activeTab,
          tenantGroupAlbumId:
            baseState.platformType === 'STUDENT'
              ? state.details.tenantGroupAlbumId
              : state.details.id // 老师用专辑id当唯一值
        })
      )
      router.push({
        path: '/orderDetail',
        query: {
          orderType: 'ALBUM',
          album: album.id
        }
      })
    }

    const cancelPayment = async (orderNo: string) => {
      try {
        await request.post('/api-student/userOrder/orderCancel/v2', {
          data: {
            orderNo
          }
        })
      } catch {
        //
      }
    }
    return () => (
      <div class={styles.trainTool}>
        {!state.loading && !state.details.id && state.buy != '1' ? (
          <>
            <TheSticky
              class={styles.theSticky}
              position="top"
              onBarHeight={(height: any) => {
                console.log(height, 'height', height)
                state.heightV = height
              }}
            >
              <ColHeader border={false} isFixed={false} />
            </TheSticky>
            {!state.loading && (
              <div
                class={styles.colResultBox}
                style={{
                  height: 'calc(100vh - var(--header-height))',
                  display: 'flex',
                  alignItems: 'center'
                }}
              >
                <ColResult
                  tips="暂无教程"
                  classImgSize="SMALL"
                  btnStatus={false}
                />
              </div>
            )}
          </>
        ) : (
          !state.loadingAlbum && (
            <>
              <TheSticky
                class={styles.theSticky}
                position="top"
                onBarHeight={(height: any) => {
                  state.heightV = height
                }}
              >
                <ColHeader
                  background={background.value}
                  border={false}
                  isFixed={false}
                  hideHeader={route.query.taId ? true : false}
                  // color={color.value}
                  // backIconColor="white"
                />
              </TheSticky>

              {/* <img class={styles.bgImg} src={state.details?.coverImg} /> */}
              <div class={styles.musicContent}></div>
              <div class={styles.bg}>
                <div class={styles.alumWrap}>
                  {isSingleAlbum.value ? (
                    <div class={styles.singleAlbum}>
                      <div class={styles.img}>
                        {state.details?.buyTimesFlag && (
                          <span class={styles.quota}>
                            限购:{state.details?.buyedTimes}/
                            {state.details?.buyTimes}次
                          </span>
                        )}
                        <Image
                          class={styles.image}
                          width="100%"
                          height="100%"
                          fit="cover"
                          src={state.details?.coverImg || iconAlbumCover}
                          errorIcon={iconAlbumCover}
                        />
                        <div class={styles.iconPian}></div>
                      </div>
                    </div>
                  ) : (
                    state.albumList &&
                    state.albumList.length > 0 && (
                      <Swiper
                        initialSlide={state.initialSlide}
                        watchSlidesProgress={true}
                        slidesPerView={'auto'}
                        centeredSlides={true}
                        modules={[Pagination]}
                        pagination={{ clickable: true }}
                        // onTransitionEnd={(swiper: any) => {}} onSlideChange
                        onSlideChange={(swiper: any) => {
                          state.details = state.albumList[swiper.activeIndex]
                          // 等tab渲染完了之后再切换 不然tab会自动重新赋值
                          nextTick(() => {
                            // 当有初始值的时候不刷新
                            if (state.initialSlide) {
                              state.initialSlide = 0
                              return
                            }
                            handleChangeActiveTab()
                            params.page = 1
                            state.list = []
                            FetchList(true)
                          })
                        }}
                      >
                        {state.albumList.map((album: any) => (
                          <SwiperSlide>
                            <div class={styles.img}>
                              {album.buyTimesFlag && (
                                <span class={styles.quota}>
                                  限购{album.buyedTimes}/{album.buyTimes}次
                                </span>
                              )}
                              <Image
                                class={styles.image}
                                width="100%"
                                height="100%"
                                fit="cover"
                                src={album?.coverImg || iconAlbumCover}
                                errorIcon={iconAlbumCover}
                              />
                              <div class={styles.iconPian}></div>
                            </div>
                          </SwiperSlide>
                        ))}
                      </Swiper>
                    )
                  )}

                  <div class={styles.alumDes}>
                    <div class={[styles.alumTitle, 'van-ellipsis']}>
                      {state.details?.name}
                    </div>
                    <div
                      class={[styles.des, 'van-multi-ellipsis--l2']}
                      style={{
                        height: '32px',
                        lineHeight: '16px'
                      }}
                    >
                      {state.details?.describe}
                    </div>
                  </div>

                  {state.buy != '1' && baseState.platformType === 'STUDENT' && (
                    <div class={styles.albumPriceGroup}>
                      <div class={styles.albumTimer}>
                        <img src={iconTimer} class={styles.iconTimer} />
                        <span>有效期：{state.details?.purchaseNum || 0}天</span>
                      </div>
                      <div class={styles.albumPriceList}>
                        {(state.details?.originalPrice || 0) >
                          (state.details?.actualPrice || 0) && (
                          <del class={styles.originPrice}>
                            原价：¥
                            {moneyFormat(state.details?.originalPrice || 0)}
                          </del>
                        )}

                        <span class={styles.currentPrice}>
                          <span>
                            ¥{moneyFormat(state.details?.actualPrice || 0)}
                          </span>
                        </span>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <div class={styles.musicList}>
                <Sticky position="top" offsetTop={state.heightV}>
                  <Tabs
                    color="var(--van-primary)"
                    background="transparent"
                    lineWidth={20}
                    shrink
                    v-model:active={state.activeTab}
                    onClick-tab={val => {
                      state.activeTab = val.name
                      params.page = 1
                      state.list = []
                      FetchList()
                    }}
                  >
                    {state.coursewareCounts && (
                      <Tab title="云教程" name="COURSEWARE"></Tab>
                    )}
                    {state.subjectCounts && (
                      <Tab title="声部云练" name="SUBJECT"></Tab>
                    )}
                    {state.musicCounts && (
                      <Tab title="独奏云练" name="MUSIC"></Tab>
                    )}
                    {state.ensembleCounts && (
                      <Tab title="合奏云练" name="ENSEMBLE"></Tab>
                    )}
                  </Tabs>
                </Sticky>

                <div
                  class={[
                    styles.alumnList,
                    state.activeTab === 'COURSEWARE'
                      ? styles.alumnListCourseware
                      : ''
                  ]}
                >
                  <List
                    loading={state.loading}
                    finished={state.finished}
                    finished-text={' '}
                    onLoad={FetchList}
                    immediateCheck={false}
                    error={state.isError}
                  >
                    {state.list && state.list.length ? (
                      state.activeTab === 'COURSEWARE' ? (
                        <CourseItem
                          list={state.list.map(item => {
                            return {
                              name: item.musicSheetName,
                              coverImg: item.titleImg,
                              id: item.id
                            }
                          })}
                          onItemClick={row => {
                            sessionStorage.setItem(
                              'tool-subject-type',
                              JSON.stringify({
                                activeTab: state.activeTab,
                                tenantGroupAlbumId:
                                  baseState.platformType === 'STUDENT'
                                    ? state.details.tenantGroupAlbumId
                                    : state.details.id // 老师用专辑id当唯一值
                              })
                            )
                            router.push({
                              path: '/courseList',
                              query: {
                                id: row.id,
                                albumId: state.details.id,
                                taId: state.details.tenantGroupAlbumId, // 当通过我的曲目进来的时候 这个值为空
                                buyStatus: state.hasBuyStatus ? '0' : '1' //默认能购买
                              }
                            })
                          }}
                        />
                      ) : (
                        <Song
                          showNumber
                          list={state.list}
                          onDetail={(item: any) => {
                            sessionStorage.setItem(
                              'tool-subject-type',
                              JSON.stringify({
                                activeTab: state.activeTab,
                                tenantGroupAlbumId:
                                  baseState.platformType === 'STUDENT'
                                    ? state.details.tenantGroupAlbumId
                                    : state.details.id // 老师用专辑id当唯一值
                              })
                            )
                            router.push({
                              path: '/music-detail',
                              query: {
                                id: item.id,
                                tenantAlbumId: item.tenantAlbumId,
                                taId: state.details.tenantGroupAlbumId, // 当通过我的曲目进来的时候 这个值为空
                                buyStatus: state.hasBuyStatus ? '0' : '1' //默认能购买
                              }
                            })
                          }}
                        />
                      )
                    ) : (
                      !state.loading && (
                        <ColResult
                          tips={
                            state.activeTab === 'COURSEWARE'
                              ? '暂无教材'
                              : '暂无曲目'
                          }
                          classImgSize="SMALL"
                          btnStatus={false}
                        />
                      )
                    )}
                  </List>
                </div>
              </div>
              {baseState.platformType === 'STUDENT' && state.buy != '1' && (
                <TheSticky position="bottom">
                  <div class={styles.btnGroup}>
                    <Button
                      round
                      block
                      disabled={!state.hasBuyStatus}
                      color="linear-gradient(270deg, #FF204B 0%, #FE5B71 100%)"
                      onClick={onSubmit}
                    >
                      开通训练教程
                    </Button>
                  </div>
                </TheSticky>
              )}
            </>
          )
        )}
      </div>
    )
  }
})
