import { memberType } from '@/constant'
import request from '@/helpers/request'
import { state } from '@/state'
import { orderStatus } from '@/views/order-detail/orderStatus'
import dayjs from 'dayjs'

const apiSuffix =
  state.platformType === 'STUDENT' ? '/api-student' : '/api-teacher'
// LIVE: '直播课',
// PRACTICE: '陪练课',
// VIDEO: '视频课',
// VIP: '开通会员',
// MUSIC: '单曲点播'
interface IAmount {
  couponAmount: number
  discountPrice: number
}
export const formatOrderDetail = async (item: any, amount?: IAmount) => {
  const type = item.goodType
  let tempList: any = {}

  switch (type) {
    case 'LIVE':
      {
        try {
          const live = await getLiveDetail(item.bizId)
          const courseInfo: any[] = []
          const coursePlanList = live.planList || []
          coursePlanList.forEach((item: any) => {
            const startTime = item.startTime || new Date()
            const endTime = item.endTime || new Date()
            courseInfo.push({
              courseTime: `${dayjs(startTime).format('YYYY-MM-DD')} ${dayjs(
                startTime
              ).format('HH:mm')}~${dayjs(endTime).format('HH:mm')}`,
              coursePlan: item.plan,
              id: item.courseId
            })
          })
          tempList = {
            orderType: item.goodType,
            goodName: item.goodName,
            courseGroupId: live.courseGroupId,
            courseGroupName: live.courseGroupName,
            coursePrice: live.coursePrice,
            teacherName: live.userName || `游客${live.teacherId || ''}`,
            teacherId: live.teacherId,
            avatar: live.avatar,
            courseInfo
          }
        } catch (e: any) {
          throw new Error(e.message)
        }
      }
      break
    case 'PRACTICE': {
      const bizContent: any = JSON.parse(item.bizContent)
      tempList = {
        ...bizContent,
        teacherName: item.username,
        starGrade: item.starGrade,
        avatar: item.avatar
      }
      break
    }
    case 'VIDEO': {
      try {
        const res = await getVideoDetail(item.bizId)
        const { lessonGroup, detailList } = res
        tempList = {
          orderType: item.goodType,
          goodName: item.goodName,
          courseGroupId: lessonGroup.id,
          courseGroupName: lessonGroup.lessonName,
          coursePrice: lessonGroup.lessonPrice,
          teacherName: lessonGroup.username,
          teacherId: lessonGroup.teacherId,
          avatar: lessonGroup.avatar,
          courseInfo: detailList
        }
      } catch (e: any) {
        throw new Error(e.message)
      }
      break
    }
    case 'VIP':
      {
        try {
          const res = await getVipDetail(item.id)
          tempList = {
            orderType: item.goodType,
            goodName: item.goodName,
            id: item.id,
            title: memberType[res.period] || '',
            // 判断是否有优惠金额
            price: amount?.couponAmount
              ? Number(
                  (
                    res.salePrice -
                    amount.couponAmount +
                    amount.discountPrice
                  ).toFixed(2)
                )
              : res.salePrice || item.actualPrice,
            startTime: dayjs(res.startTime).format('YYYY-MM-DD'),
            endTime: dayjs(res.endTime).format('YYYY-MM-DD')
          }
        } catch (e: any) {
          throw new Error(e.message)
        }
      }
      break
    case 'MUSIC':
      {
        try {
          const res = await getMusicDetail(item.bizId)
          tempList = {
            orderType: item.goodType,
            goodName: item.goodName,
            ...res
          }
        } catch (e: any) {
          throw new Error(e.message)
        }
      }
      break
    case 'ALBUM':
      {
        try {
          const res = await getAlbumDetail(item.bizId)
          tempList = {
            orderType: item.goodType,
            goodName: item.goodName,
            ...res
          }
        } catch (e: any) {
          throw new Error(e.message)
        }
      }
      break
    case 'TENANT_ALBUM':
      {
        try {
          const res = await getTenantAlbumDetail(item.bizId)
          tempList = {
            orderType: item.goodType,
            goodName: item.goodName,
            ...res,
            purchaseNum: item.bizInfo?.bizValidTime || res.purchaseNum
          }
        } catch (e: any) {
          throw new Error(e.message)
        }
      }
      break
    case 'ACTI_REGIST':
      {
        try {
          const res = await getMusicActiveTrack(item.bizId)
          tempList = {
            orderType: item.goodType,
            goodsName: res.activityName,
            activityId: res.id,
            actualPrice: res.registrationPrice
          }
        } catch (e: any) {
          throw new Error(e.message)
        }
      }
      break
  }
  tempList.orderType = type
  tempList.goodName = item.goodName
  orderStatus.orderObject.orderList.push(tempList)
}
// 获取视频课详情
export const getVideoDetail = async (groupId: any) => {
  try {
    const res = await request.get(
      `${apiSuffix}/videoLesson/selectVideoLesson`,
      {
        params: {
          groupId
        }
      }
    )
    return res.data
  } catch {
    throw new Error('获取视频课详情失败')
  }
}

// 获取直播课详情
export const getLiveDetail = async (groupId: any) => {
  try {
    const res = await request.get(
      `${apiSuffix}/courseGroup/queryLiveCourseInfo`,
      {
        params: {
          groupId
        }
      }
    )
    return res.data
  } catch {
    throw new Error('获取直播课详情失败')
  }
}

// 获取会员详情
export const getVipDetail = async (id: any) => {
  try {
    const setting = await request.get(`${apiSuffix}/vipCardRecord/detail/` + id)
    return setting.data || []
  } catch {
    throw new Error('获取会员详情失败')
  }
}

// 获取曲目详情
export const getMusicDetail = async (id: any) => {
  try {
    const res = await request.get(`${apiSuffix}/music/sheet/detail/${id}`)
    return res.data
  } catch {
    throw new Error('获取曲目详情失败')
  }
}

// 活动列表
// 获取曲目详情
export const getMusicActiveTrack = async (id: any) => {
  try {
    const res = await request.post(`${apiSuffix}/open/activity/info/${id}`)
    return res.data
  } catch {
    throw new Error('获取曲目详情失败')
  }
}

// 获取专辑详情
export const getAlbumDetail = async (id: any) => {
  try {
    const res = await request.post(`${apiSuffix}/music/album/detail`, {
      data: { id }
    })
    return res.data
  } catch {
    throw new Error('获取专辑详情失败')
  }
}

// 获取机构专辑详情
export const getTenantAlbumDetail = async (id: any) => {
  try {
    const res = await request.post(
      `${apiSuffix}/userTenantAlbumRecord/detail`,
      {
        data: { albumId: id }
      }
    )
    return res.data
  } catch {
    throw new Error('获取机构专辑详情失败')
  }
}

// 为了处理继续支付逻辑
export const tradeOrder = (result: any, callBack?: any) => {
  const {
    orderNo,
    actualPrice,
    orderDesc,
    orderName,
    orderType,
    orderDetailList,
    couponAmount, // 优惠金额
    discountPrice,
    paymentConfig, // v2 类型的订单才会用
    paymentVendor,
    paymentVersion
  } = result
  orderStatus.orderObject.orderType = orderType
  orderStatus.orderObject.orderName = orderName
  orderStatus.orderObject.orderDesc = orderDesc
  orderStatus.orderObject.actualPrice = actualPrice
  orderStatus.orderObject.orderNo = orderNo
  orderStatus.orderObject.discountPrice = discountPrice
  orderStatus.orderObject.orderList = []
  orderStatus.orderObject.paymentConfig = {
    ...paymentConfig,
    paymentVendor,
    paymentVersion
  }
  try {
    orderDetailList.forEach(async (item: any) => {
      await formatOrderDetail(item, {
        couponAmount,
        discountPrice
      })
    })
    callBack && callBack()
  } catch {
    //
  }
}
