import CoursePlanStep from '@/business-components/course-plan-step'
import SectionDetail from '@/business-components/section-detail'
import UserDetail from '@/business-components/user-detail'
import request from '@/helpers/request'
import { state } from '@/state'
import { Button, Dialog, Sticky, Toast } from 'vant'
import { defineComponent } from 'vue'
import { createState } from './createState'
import styles from './detail.module.less'
import dayjs from 'dayjs'
import { postMessage } from '@/helpers/native-message'
interface IProps {
  courseTime: string
  coursePlan: string
  videoPosterUrl?: string
  roomUid?: string
  liveState?: number
  id?: number | string
}
export default defineComponent({
  name: 'detail',
  computed: {
    userInfo() {
      const startTime = createState.live.coursePlanList[0].startTime
      const endTime = createState.live.coursePlanList[0].endTime
      return {
        headUrl: state.user.data?.heardUrl,
        username:
          state.user.data?.username || `游客${state.user.data?.userId || ''}`,
        startTime:
          `${dayjs(startTime).format('YYYY-MM-DD')} ${dayjs(startTime).format(
            'HH:mm'
          )}~${dayjs(endTime).format('HH:mm')}` || '',
        buyNum: 0,
        lessonPrice: createState.live.coursePrice,
        lessonNum: createState.live.courseNum,
        lessonDesc: createState.live.courseIntroduce,
        lessonCoverUrl:
          createState.live.backgroundPic ||
          createState.live.backgroundPicTemplate,
        lessonName: createState.live.name,
        auditVersion:0
      }
    },
    courseInfo() {
      const tempArr = [] as IProps[]
      const coursePlanList = createState.live.coursePlanList || []
      coursePlanList.forEach((item: any) => {
        tempArr.push({
          courseTime: `${dayjs(item.startTime).format('YYYY-MM-DD')} ${dayjs(
            item.startTime
          ).format('HH:mm')}~${dayjs(item.endTime).format('HH:mm')}`,
          roomUid: item.roomUid,
          liveState: item.liveState,
          coursePlan: item.plan,
          id: item.courseId
        })
      })
      return tempArr || []
    }
  },
  methods: {
    async onSubmit() {
      try {
        const params = {
          ...createState.live,
          startTime: createState.live.coursePlanList[0].startTime,
          backgroundPic:
            createState.live.backgroundPic ||
            createState.live.backgroundPicTemplate,
          teacherId: state.user.data?.userId
        }
        await request.post('/api-teacher/courseGroup/addLiveCourse', {
          data: params
        })
        Toast.success('创建成功')
        setTimeout(() => {
          postMessage({ api: 'back' })
        }, 1000)
      } catch (e: any) {
        // 报错时需要重置日历表的数据
        const message = e.message
        Dialog.alert({
          title: '提示',
          confirmButtonColor: 'var(--van-primary)',
          message
        }).then(() => {
          createState.active = 3
          createState.selectCourseList = []
          createState.live.salesStartDate = ''
          createState.live.salesEndDate = ''
          createState.live.mixStudentNum = null
          createState.live.backgroundPic = ''
          createState.live.backgroundPicTemplate = ''
          createState.coursePlanStatus = false
        })
      }
    },

    async onUpdate(){
      
      const params = {
        id: createState.live.courseGroupId,
        ...createState.live,
        startTime: createState.live.coursePlanList[0].startTime,
        backgroundPic:
          createState.live.backgroundPic ||
          createState.live.backgroundPicTemplate,
      }
      console.log({...params})
      await request.post('/api-teacher/courseGroup/updateLiveCourse', {
        data: params
      })
      Toast({
        type: 'success',
        message: '编辑成功',
        duration: 1000,
        onClose: () => {
          postMessage({ api: 'back' })
        }
      })
    }
  },
  render() {
    return (
      <div class={[styles['detail']]}>
        <UserDetail userInfo={this.userInfo} />
        <SectionDetail>
          <p class={styles.introduction}>{this.userInfo.lessonDesc}</p>
        </SectionDetail>

        <SectionDetail
          title="课程安排"
          icon="courseList"
          titleShow={false}
          class={'mb12'}
          contentStyle={{ paddingTop: '0' }}
        >
          <CoursePlanStep courseInfo={this.courseInfo} />
        </SectionDetail>

        <Sticky offsetBottom={0} position="bottom">
          <div class={['btnGroup', 'btnMore']}>
            <Button
              block
              round
              type="primary"
              plain
              onClick={() => {
                createState.active = 4
              }}
            >
              返回编辑
            </Button>
            {createState.live.courseGroupId ? (
              <Button block round type="primary" onClick={this.onUpdate}>
                确认修改
              </Button>
            ) : (
              <Button block round type="primary" onClick={this.onSubmit}>
                创建成功
              </Button>
            )}
            
          </div>
        </Sticky>
      </div>
    )
  }
})
