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'
import GroupPlanStep from '@/business-components/group-plan-step'
import TheSticky from '@/components/the-sticky'
interface IProps {
  courseTime: string
  coursePlan: string
  teacherName: string
  subjectName: 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'
          )}` || '',
        buyNum: 0,
        type: 'group',
        mixStudentNum: createState.live.mixStudentNum,
        lessonPrice: createState.live.coursePrice,
        lessonNum: createState.live.courseNum,
        lessonDesc: createState.live.courseIntroduce,
        subjectName: createState.live.subjectName,
        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,
          teacherName: state.user.data?.username,
          subjectName: createState.live.subjectName,
          liveState: item.liveState,
          coursePlan: item.plan,
          id: item.courseId
        })
      })
      return tempArr || []
    }
  },
  data() {
    return {
      submitLoading: false
    }
  },
  methods: {
    async onSubmit() {
      if(this.submitLoading) return
      this.submitLoading = true;
      
      try {
        const params = {
          ...createState.live,
          startTime: createState.live.coursePlanList[0].startTime,
          backgroundPic:
            createState.live.backgroundPic ||
            createState.live.backgroundPicTemplate,
          teacherId: state.user.data?.userId,
          version: state.version,
          platform: state.platformType === 'STUDENT' ? 'ios-student' : 'ios-teacher',
        }
        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
        })
      }
      this.submitLoading = false;
    },

    async onUpdate() {
      if(this.submitLoading) return
      this.submitLoading = true;
      
      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
      })
      this.submitLoading = false
      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>

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

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