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: '单曲点播'

/** 计算畅学卡时间 */
export const discountTimer = (discountEndTime: any, period: string, isFlag?: false) => {
  const startTime = discountEndTime || new Date()
  let endTime = dayjs(new Date()).format('YYYY-MM-DD')
  if (period === 'MONTH') {
    endTime = dayjs(startTime).add(1, 'month').format('YYYY-MM-DD')
  } else if (period === 'QUARTERLY') {
    endTime = dayjs(startTime).add(3, 'month').format('YYYY-MM-DD')
  } else if (period === 'YEAR_HALF') {
    endTime = dayjs(startTime).add(6, 'month').format('YYYY-MM-DD')
  } else if (period === 'YEAR') {
    endTime = dayjs(startTime).add(1, 'year').format('YYYY-MM-DD')
  }
  return {
    startTime: isFlag ?  dayjs(startTime).add(1, 'day').format('YYYY-MM-DD') : dayjs(startTime).format('YYYY-MM-DD'),
    endTime
  }
}

interface IAmount {
  couponAmount: number
  discountPrice: number
  expectPrice: number
  activityType: string
}
export const formatOrderDetail = async (item: any, amount?: IAmount) => {
  const type = item.goodType
  let tempList: any = {}
  switch (type) {
    case 'LIVE': case "GROUP":
      {
        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,
            price: 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': case 'VIP_COURSE': {
      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,
          price: lessonGroup.lessonPrice,
          teacherName: lessonGroup.username,
          teacherId: lessonGroup.teacherId,
          avatar: lessonGroup.avatar,
          courseInfo: detailList
        }
      } catch (e: any) {
        throw new Error(e.message)
      }
      break
    }
    case 'VIP':
    case 'SVIP':
      {
        try {
          // // couponAmount 总的优惠金额
          // // discountPrice 优惠券金额
          // let tempPrice = amount?.expectPrice || item.actualPrice
          
          // // 如果是赠送活动 就是一口价
          // if (item.activityType !== 'MEMBER') {
          //   if (amount?.couponAmount) {
          //     tempPrice = Number(
          //       (
          //         (amount?.expectPrice -
          //           (amount.couponAmount - amount.discountPrice)) / item.goodNum
          //       ).toFixed(2)
          //     )
          //   }
          // }

          // couponAmount 总的优惠金额
          // discountPrice 优惠券金额
          let tempPrice = amount?.expectPrice || item.actualPrice
          
          // 如果是赠送活动 就是一口价 amount?.activityType !== 'MEMBER' && 
          if (amount?.couponAmount) {
              tempPrice = Number(
                (
                  (amount?.expectPrice -
                    (amount.couponAmount - amount.discountPrice)) / item.goodNum
                ).toFixed(2)
              )
          } else {
            tempPrice = Number(
              tempPrice / item.goodNum
              ).toFixed(2)
          }
          // 判断是否有会员
          let startTime = new Date()
          if (item.goodType === 'SVIP') {
            startTime = dayjs(
              state.user.data.userVip.svipEndDate || new Date()
            ).toDate()
          } else if (item.goodType === 'VIP') {
            // 购买Vip时，先有vip的有效时间，如果没有则取SVIP有效时间，都没有默认当前
            startTime = dayjs(
              state.user.data.userVip.vipEndDate ||
                state.user.data.userVip.svipEndDate ||
                new Date()
            ).toDate()
          }
          let endTime = new Date()
          if (item.period === 'MONTH') {
            endTime = dayjs(startTime)
              .add(1 * item.goodNum, 'month')
              .toDate()
          } else if (item.period === 'QUARTERLY') {
            endTime = dayjs(startTime)
              .add(3 * item.goodNum, 'month')
              .toDate()
          } else if (item.period === 'YEAR_HALF') {
            endTime = dayjs(startTime)
              .add(6 * item.goodNum, 'month')
              .toDate()
          } else if (item.period === 'YEAR') {
            endTime = dayjs(startTime)
              .add(1 * item.goodNum, 'year')
              .toDate()
          }
          tempList = {
            orderType: item.goodType,
            goodName: item.goodName,
            num: item.goodNum,
            id: item.id,
            title: item.goodName || '',
            vipEndDays: item.vipEndDays,
            // 判断是否有优惠金额
            price: tempPrice,
            period: item.period,
            startTime: dayjs(startTime).format('YYYY-MM-DD'),
            endTime: dayjs(endTime).format('YYYY-MM-DD'),
            activityList: [], // 活动赠送的东西
            discountCardFlag: state.user.data.discountCardFlag,
            discountEndTime: state.user.data.discountEndTime, // 畅学卡结束时间
            discountStartTime: state.user.data.discountStartTime // 畅学卡开始时间
          }
          tempList.activityList = (item.activityList || []).map(item => {
            const { goodType, goodName, goodNum, giftFlag, bizId, period } = item
            if (goodType === 'DISCOUNT') {
              return {
                goodType,
                goodName,
                goodNum,
                bizContent: bizId,
                giftFlag,
                vipEndDays: null,
                goodsNum: goodNum,
                unit:period
              }
            }
            return {
              goodType,
              goodName,
              goodNum,
              bizContent: bizId,
              giftFlag,
              vipEndDays: null,
              goodsNum: goodNum,
              unit:period
            }
          })
        } catch (e: any) {
          throw new Error(e.message)
        }
      }
      break
    case 'DISCOUNT':
      {
        const users = state.user.data || {}
        const endTime = users.discountCardFlag ? dayjs(users.discountEndTime || new Date()).toDate() : new Date()
        tempList = {
          orderType: item.goodType,
          goodName: item.goodName,
          num: item.goodNum,
          id: item.id,
          title: item.goodName || '',
          // 判断是否有优惠金额
          price: item.expectPrice,
          ...discountTimer(endTime, item.period, users.discountCardFlag)
        }
      }
      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 '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
  // return tempList
  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('获取专辑详情失败')
  }
}

/** 处理选择了畅学卡之后的显示 */
// const formatOrder = (orderDetailList: any, orderType: string) => {
//   let discountJson: any = {}
//   orderDetailList.forEach((item: any) => {
//     if(item.goodType === orderType) {
//       discountJson = item.discountJson ? JSON.parse(item.discountJson) : {}
//     }
//   })
//   orderDetailList.forEach((item: any) => {
//     if(item.goodType === "DISCOUNT") {
//       item.discountPrice = discountJson.DISCOUNT || 0
//     }
//   })
//   return orderDetailList
// }

const moveToEnd = () => {
  const orderList = orderStatus.orderObject.orderList || []
  const index = orderList.findIndex((item: any) => item.orderType === 'DISCOUNT')
    if (index !== -1) {
      const i = orderList.splice(index, 1)
      orderStatus.orderObject.orderList = [
        ...orderList,
        ...i
      ]
    }
}

// 为了处理继续支付逻辑
export const tradeOrder = async (result: any, callBack?: any) => {
  const {
    orderNo,
    actualPrice,
    orderDesc,
    orderName,
    orderType,
    orderDetailList,
    couponAmount, // 优惠金额
    cardDiscountPrice,
    discountPrice,
    paymentConfig,
    paymentVendor,
    paymentVersion,
    activityType, // 活动类型
    expectPrice
  } = result
  orderStatus.orderObject.orderType = orderType
  orderStatus.orderObject.orderName = orderName
  orderStatus.orderObject.orderDesc = orderDesc
  orderStatus.orderObject.actualPrice = actualPrice
  orderStatus.orderObject.orderNo = orderNo
  orderStatus.orderObject.discountCardPrice = cardDiscountPrice
  orderStatus.orderObject.discountPrice = discountPrice
  orderStatus.orderObject.couponAmount = couponAmount
  orderStatus.orderObject.paymentConfig = {
    ...paymentConfig,
    paymentVendor,
    paymentVersion
  }
  orderStatus.orderObject.orderList = []
  try {
    // 排除活动商品
    const orderDetails: any[] = []
    const orderDetailsActivity: any[] = []
    orderDetailList.map(item => {
      if (item.giftFlag) {
        orderDetailsActivity.push(item)
      } else {
        orderDetails.push(item)
      }
    })
    orderDetails[0] && (orderDetails[0].activityList = orderDetailsActivity)
    for(let i = 0; i < orderDetails.length; i++) {
      await formatOrderDetail(orderDetails[i], {
        couponAmount,
        discountPrice,
        expectPrice,
        activityType
      })
      
      moveToEnd()
    }

    callBack && callBack()
  } catch {
    //
  }
}
