import ColCropper from '@/components/col-cropper'
import request from '@/helpers/request'
import { verifiyNumberInteger } from '@/helpers/toolsValidate'
import { state } from '@/state'
import { scrollAnimation } from '@/util/scroll'
import {
  dayjs,
  ElButton,
  ElCol,
  ElDatePicker,
  ElDialog,
  ElForm,
  ElFormItem,
  ElImage,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElRadio,
  ElRadioGroup,
  ElRow,
  ElTabPane,
  ElTabs
} from 'element-plus'
import { defineComponent } from 'vue'
import CoursePreview from '../course-preview'
import { createState } from '../createState'
import styles from './index.module.less'

export default defineComponent({
  name: 'course-class',
  data() {
    return {
      typeDateTime: 'start',
      currentDate: new Date(),
      minDate: dayjs().toDate(),
      maxDate: new Date(),
      show: false
    }
  },
  mounted() {
    this.maxDate = dayjs(createState.selectCourseList[0].startTime)
      .subtract(1, 'day')
      .toDate()
    createState.live.salesStartDate =
      createState.live.salesStartDate ||
      dayjs(this.minDate).format('YYYY-MM-DD')
    createState.live.salesEndDate =
      createState.live.salesEndDate || dayjs(this.maxDate).format('YYYY-MM-DD')
    // console.log(createState.templateList, '1212')
  },
  methods: {
    tabChange(name: number) {
      ;(this as any).$refs.form.clearValidate('lessonCoverTemplateUrl')
      ;(this as any).$refs.form.clearValidate('lessonCoverUrl')
      createState.tabIndex = name
    },
    selectImg(val: string) {
      createState.live.backgroundPic = ''
      createState.live.backgroundPicTemplate = val
    },
    onFormatter(e: any) {
      e.target.value = verifiyNumberInteger(e.target.value)
    },
    onConfirm(val: any) {
      if (this.typeDateTime === 'start') {
        createState.live.salesStartDate = dayjs(val).format('YYYY-MM-DD')
        if (
          createState.live.salesEndDate &&
          dayjs(createState.live.salesStartDate).isAfter(
            dayjs(createState.live.salesEndDate)
          )
        ) {
          createState.live.salesEndDate = ''
        }
      } else if (this.typeDateTime === 'end') {
        createState.live.salesEndDate = dayjs(val).format('YYYY-MM-DD')
      }
    },
    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-website/courseGroup/addLiveCourse', {
          data: params
        })
        ElMessage.success('创建成功')
        this.$router.back()
      } catch (e: any) {
        // 报错时需要重置日历表的数据
        const message = e.message
        ElMessageBox.confirm(message, '提示', {
          type: 'warning'
        }).then(() => {
          createState.active = 2
          createState.selectCourseList = []
          createState.live.salesStartDate = ''
          createState.live.salesEndDate = ''
          createState.live.mixStudentNum = null
          createState.live.backgroundPic = ''
          createState.live.backgroundPicTemplate = ''
          createState.coursePlanStatus = false

          const currentY =
            document.documentElement.scrollTop || document.body.scrollTop
          scrollAnimation(currentY, 0)
        })
      }
    },
    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-website/courseGroup/updateLiveCourse', {
        data: params
      })
      ElMessage.success('编辑成功')
      this.$router.replace('/userInfo/liveClass')
    }
  },
  render() {
    return (
      <div class={styles.courseContent}>
        <ElForm
          class="px-6 pb-10 pt-7"
          size="large"
          ref="form"
          labelWidth={'140px'}
          labelPosition="left"
          model={createState.live}
        >
          <ElFormItem
            label="开售日期"
            prop="salesStartDate"
            rules={[
              {
                type: 'date',
                required: true,
                message: '请输入开售日期'
              }
            ]}
          >
            <ElDatePicker
              class="!w-full"
              v-model={createState.live.salesStartDate}
              disabledDate={(time: Date) => {
                const now = dayjs().format('YYYY-MM-DD')
                return (
                  time.getTime() < dayjs(now).valueOf() ||
                  time.getTime() > this.maxDate.getTime()
                )
              }}
              // @ts-ignore
              onChange={(val: any) => {
                this.typeDateTime = 'start'
                this.onConfirm(val)
              }}
              placeholder="请输入开售日期"
              type="date"
              disabled={createState.live.courseGroupId ? true : false}
            />
          </ElFormItem>
          <ElFormItem
            label="停售日期"
            prop="salesEndDate"
            rules={[
              {
                type: 'date',
                required: true,
                message: '请输入停售日期',
                trigger: 'change'
              }
            ]}
          >
            <ElDatePicker
              class="!w-full"
              v-model={createState.live.salesEndDate}
              disabledDate={(time: Date) => {
                const now = dayjs().format('YYYY-MM-DD')
                return (
                  time.getTime() <
                    dayjs(createState.live.salesStartDate).valueOf() ||
                  time.getTime() > this.maxDate.getTime()
                )
              }}
              // @ts-ignore
              onChange={(val: any) => {
                this.typeDateTime = 'end'
                this.onConfirm(val)
              }}
              placeholder="请输入停售日期"
              type="date"
              disabled={createState.live.courseGroupId ? true : false}
            />
          </ElFormItem>
          <ElFormItem
            label="最低开课人数"
            prop="mixStudentNum"
            rules={[
              {
                required: true,
                message: '请输入最低开课人数'
              }
            ]}
          >
            <ElInput
              placeholder="请输入最低开课人数"
              v-model={createState.live.mixStudentNum}
              // @ts-ignore
              onKeyup={this.onFormatter}
              maxlength={8}
              v-slots={{
                suffix: () => <span class="text-base text-[#999]">人</span>
              }}
              disabled={createState.live.courseGroupId ? true : false}
            />
          </ElFormItem>
          {/*  <ElFormItem label="课程封面" class="!mb-0" required> */}
          {/* <ElTabs
              v-model={createState.tabIndex}
              class={styles.tabs}
              onTab-change={(name: any) => {
                this.tabChange(name)
              }}
            >
              <ElTabPane label="图片模板" name={1}></ElTabPane>
              <ElTabPane label="自定义模板" name={2}></ElTabPane>
            </ElTabs>

            */}
          <ElFormItem
            label="课程封面"
            prop="backgroundPic"
            rules={[
              {
                required: true,
                message: '请上传课程封面',
                trigger: 'change'
              }
            ]}
          >
            <ColCropper
              modelValue={createState.live.backgroundPic}
              bucket="video-course"
              cropUploadSuccess={(data: any) => {
                createState.live.backgroundPic = data
                createState.live.backgroundPicTemplate = ''
              }}
              options={{
                title: '课程封面',
                fixedNumber: [3.34, 2],
                autoCropWidth: 375,
                autoCropHeight: 212
                // fixedNumber: [3, 2],
                // autoCropWidth: 300,
                // autoCropHeight: 200
              }}
            />
          </ElFormItem>
          {/* </ElFormItem> */}

          {/* {createState.tabIndex === 1 && (
            <ElFormItem
              prop="backgroundPicTemplate"
              rules={[
                {
                  required: true,
                  message: '请上传课程封面'
                }
              ]}
            >
              <ElRadioGroup v-model={createState.live.backgroundPicTemplate}>
                <ElRow>
                  {createState.templateList.map((item: any) => (
                    <ElCol span={7} class="mb-3 cursor-pointer">
                      <div
                        class="w-[152px] relative rounded-xl overflow-hidden border"
                        onClick={() => {
                          this.selectImg(item)
                        }}
                      >
                        <ElImage src={item} class="align-middle" />
                        <ElRadio
                          label={item}
                          class="!absolute bottom-2 right-0 !h-auto z-10"
                        >
                          {''}
                        </ElRadio>
                      </div>
                    </ElCol>
                  ))}
                </ElRow>
              </ElRadioGroup>
            </ElFormItem>
          )} */}

          {/* {createState.tabIndex === 2 && (

          )} */}
        </ElForm>
        <div class="text-center pt-6 pb-7">
          <ElButton
            class="!w-44 !h-[48px] !text-base"
            round
            onClick={() => {
              // console.log(true)
              createState.active = 2
              if (!createState.live.courseGroupId) {
                createState.live.salesStartDate = ''
                createState.live.salesEndDate = ''
                createState.live.backgroundPic = ''
                createState.live.backgroundPicTemplate = ''
                createState.live.mixStudentNum = null
              }
            }}
          >
            上一步
          </ElButton>
          <ElButton
            type="primary"
            class="!w-44 !h-[48px] !text-base"
            round
            onClick={() => {
              // this.show = true
              ;(this as any).$refs.form.validate(_ => {
                console.log(_)
                if (_) {
                  this.show = true
                }
              })
            }}
          >
            下一步
          </ElButton>
        </div>

        {/*  @ts-ignore */}
        <ElDialog
          v-model={this.show}
          title="预览"
          v-slots={{
            footer: () => (
              <span class="dialog-footer !text-center block ">
                <ElButton
                  size="large"
                  round
                  onClick={() => {
                    this.show = false
                  }}
                >
                  返回编辑
                </ElButton>
                {createState.live.courseGroupId ? (
                  <ElButton
                    size="large"
                    round
                    type="primary"
                    onClick={this.onUpdate}
                  >
                    确定修改
                  </ElButton>
                ) : (
                  <ElButton
                    size="large"
                    round
                    type="primary"
                    onClick={this.onSubmit}
                  >
                    创建完成
                  </ElButton>
                )}
              </span>
            )
          }}
        >
          <CoursePreview />
        </ElDialog>
      </div>
    )
  }
})
