import ColUpload from '@/components/col-upload'
import ColUploadVideo from '@/components/col-upload-video'
import request from '@/helpers/request'
import { scrollAnimation } from '@/util/scroll'
import {
  ElButton,
  ElCol,
  ElDialog,
  ElForm,
  ElFormItem,
  ElIcon,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElRow,
  ElTooltip
} from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { defineComponent } from 'vue'
import CoursePreview from '../course-preview'
import { createState } from '../createState'
import styles from './index.module.less'
import iconDown from '../images/icon_down.png'
import iconUp from '../images/icon_up.png'
import iconDelete from '../images/icon_delete.png'
import ColVideo from '@/components/col-video'
import SelectMusicAlbum from '../select-music-album'
import VideoTcplayer from '@/components/video-tcplayer'

export default defineComponent({
  name: 'course-content',
  data() {
    return {
      show: false,
      form: {
        lessonList: [
          {
            key: 1,
            videoTitle: '',
            videoContent: '',
            videoUrl: '',
            relationList: [] as any,
            coverUrl: ''
          }
        ] as any
      },
      musicStatus: false,
      selectItem: {} as any // 选中的课程
    }
  },
  methods: {
    handleUpload(urls: any) {
      console.log(urls)
      // 上传视频连接s
      const urlList = urls || []
      urlList.forEach((item: any) => {
        createState.lessonList.push({
          videoTitle: '',
          videoContent: '',
          videoUrl: item,
          relationList: [] as any,
          coverUrl: ''
        })
      })
    },
    handleSubmit() {
      ;(this as any).$refs.form.validate(async (valid: any) => {
        if (valid) {
          if (createState.lessonList.length <= 0) {
            ElMessage.error('请上传课程视频')
            return
          }
          // 提交数据
          console.log('提交数据')
          this.show = true
        } else {
          this.$nextTick(() => {
            const isError = document.getElementsByClassName('is-error')
            isError[0].scrollIntoView({
              block: 'center',
              behavior: 'smooth'
            })
          })
          return false
        }
      })
    },
    async createSubmit() {
      try {
        const videoDetail = createState.lessonGroup
        const params = {
          lessonList: createState.lessonList,
          lessonGroup: {
            ...videoDetail,
            lessonPrice:
              videoDetail.payType === 'VIP' ? 0 : videoDetail.lessonPrice,
            lessonCoverUrl:
              videoDetail.lessonCoverTemplateUrl || videoDetail.lessonCoverUrl
          }
        }
        if (createState.groupId) {
          await request.post('/api-website/videoLessonGroup/update', {
            data: params
          })
          ElMessage.success('修改成功')
        } else {
          await request.post('/api-website/videoLessonGroup/add', {
            data: params
          })
          ElMessage.success('创建成功')
        }
        sessionStorage.setItem('videoActiveName', 'DOING')
        this.$router.back()
      } catch {
        //
      }
    },
    swapItems(arr: any, index1: number, index2: number) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
      return arr
    },
    getName(item: any) {
      const relation =
        item.relationList.length > 0 ? item.relationList[0] : null
      return relation
        ? (relation.relationMusicAlbum === 'ALBUM' ? '专辑：' : '曲目：') +
            relation.musicAlbumName
        : ''
    }
  },
  render() {
    return (
      <div class={styles.courseContent}>
        <ElForm
          class="px-6 pb-10 pt-7 min-h-[280px]"
          size="large"
          labelWidth={'140px'}
          labelPosition="left"
          ref="form"
          model={createState}
        >
          <ElFormItem label="课程视频" required>
            <div>
              <ColUploadVideo
                multiple
                limit={3}
                bucket="video-course"
                multipleModel={(urls: any) => {
                  this.handleUpload(urls)
                }}
              />
            </div>
            {/* <ElInput placeholder="请输入课程名称" /> */}
          </ElFormItem>
          {createState.lessonList.map((item: any, index: number) => (
            <div
              class="p-4 mb-10 border-b border-solid border-[#E7E6E6] relative"
              key={item.key}
            >
              <div class="absolute right-4 top-4 z-10 flex">
                {index !== 0 && (
                  <ElTooltip
                    class="box-item"
                    effect="dark"
                    content="上移"
                    placement="top"
                  >
                    <div
                      onClick={() => {
                        this.swapItems(createState.lessonList, index, index - 1)
                      }}
                    >
                      <ElIcon size={29}>
                        <img src={iconUp} />
                      </ElIcon>
                    </div>
                  </ElTooltip>
                )}
                {createState.lessonList.length - 1 !== index && (
                  <ElTooltip
                    class="box-item"
                    effect="dark"
                    content="下移"
                    placement="top"
                  >
                    <div
                      onClick={() => {
                        this.swapItems(createState.lessonList, index, index + 1)
                      }}
                    >
                      <ElIcon size={29} class="ml-3">
                        <img src={iconDown} title="向下移动" />
                      </ElIcon>
                    </div>
                  </ElTooltip>
                )}
                {createState.lessonList.length > 1 && (
                  <ElTooltip
                    class="box-item"
                    effect="dark"
                    content="删除"
                    placement="top"
                  >
                    <div
                      onClick={() => {
                        ElMessageBox.confirm('确定删除该条数据吗？', '提示', {
                          type: 'warning'
                        }).then(() => {
                          createState.lessonList.splice(index, 1)
                        })
                      }}
                    >
                      <ElIcon size={29} class="ml-3">
                        <img src={iconDelete} />
                      </ElIcon>
                    </div>
                  </ElTooltip>
                )}
              </div>
              <h2 class="text-xl font-semibold pb-5">{`第 ${index + 1} 课`}</h2>

              <ElFormItem
                label="课程标题"
                prop={`lessonList.${index}.videoTitle`}
                rules={[
                  {
                    required: true,
                    message: '请输入课程标题'
                  }
                ]}
              >
                <ElInput
                  placeholder="请输入课程标题"
                  maxlength={50}
                  v-model={item.videoTitle}
                />
              </ElFormItem>

              <ElFormItem
                label="课程介绍"
                prop={`lessonList.${index}.videoContent`}
                rules={[
                  {
                    required: true,
                    message: '请输入课程介绍'
                  }
                ]}
              >
                <ElInput
                  placeholder="请输入课程介绍"
                  v-model={item.videoContent}
                  type="textarea"
                  // @ts-ignore
                  maxlength={200}
                  rows={4}
                  showWordLimit
                />
              </ElFormItem>
              <ElRow>
                <ElCol span={12}>
                  <ElFormItem label="课程视频" required>
                    <ColVideo
                      styleValue={{ with: '150px', height: '85px' }}
                      controls={false}
                      preview
                      src={item.videoUrl}
                      volume={false}
                    />
                    {/* <VideoTcplayer
                      styleValue={{ with: '150px', height: '85px' }}
                      src={item.videoUrl}
                    /> */}
                    <p></p>
                  </ElFormItem>
                </ElCol>
                <ElCol span={11}>
                  <ElFormItem
                    label="视频封面"
                    prop={`lessonList.${index}.coverUrl`}
                    rules={[{ required: true, message: '请上传视频封面' }]}
                  >
                    <ColUpload
                      v-model:modelValue={item.coverUrl}
                      bucket="video-course"
                    />
                  </ElFormItem>
                </ElCol>
              </ElRow>
              <ElFormItem
                label="关联曲目或专辑"
                prop={`lessonList.${index}.relationList`}
                onClick={() => {
                  this.selectItem = item
                  this.musicStatus = true
                }}
              >
                <div class={styles.relationList}></div>
                <ElInput
                  placeholder="请选择关联曲目或专辑"
                  // v-model={item.videoContent}
                  modelValue={
                    item.relationList.length > 0 ? this.getName(item) : ''
                  }
                  readonly
                  suffixIcon={ArrowDown}
                />
              </ElFormItem>
            </div>
          ))}
        </ElForm>
        <div class="text-center pt-6 pb-7">
          <ElButton
            round
            class="!w-44 !h-[48px] !text-base"
            onClick={() => {
              createState.active = 0
              const currentY =
                document.documentElement.scrollTop || document.body.scrollTop
              scrollAnimation(currentY, 0)
            }}
          >
            上一步
          </ElButton>
          <ElButton
            round
            type="primary"
            class="!w-44 !h-[48px] !text-base"
            onClick={this.handleSubmit}
          >
            下一步
          </ElButton>
        </div>
        {/*  @ts-ignore */}
        <ElDialog
          v-model={this.show}
          width={375}
          title="预览"
          v-slots={{
            footer: () => (
              <span class="dialog-footer !text-center block ">
                <ElButton
                  size="large"
                  round
                  onClick={() => {
                    this.show = false
                  }}
                >
                  返回编辑
                </ElButton>
                <ElButton
                  size="large"
                  round
                  type="primary"
                  onClick={this.createSubmit}
                >
                  {createState.groupId ? '确认修改' : '创建完成'}
                </ElButton>
              </span>
            )
          }}
        >
          <CoursePreview />
        </ElDialog>

        <ElDialog v-model={this.musicStatus} title="选择曲目或专辑" width={750}>
          <SelectMusicAlbum
            subjectIds={createState.lessonGroup.lessonSubject}
            onSelect={(item: any) => {
              this.musicStatus = false

              if (this.selectItem.relationList.length > 0) {
                this.selectItem.relationList[0].musicAlbumId = item.id
                this.selectItem.relationList[0].musicAlbumName =
                  item.selectType === 'ALBUM'
                    ? item.albumName
                    : item.musicSheetName
                this.selectItem.relationList[0].relationMusicAlbum =
                  item.selectType
              } else {
                this.selectItem.relationList = [
                  {
                    musicAlbumId: item.id,
                    musicAlbumName:
                      item.selectType === 'ALBUM'
                        ? item.albumName
                        : item.musicSheetName,
                    relationMusicAlbum: item.selectType,
                    useRelationType: 'RECOMMEND'
                  }
                ]
              }
            }}
          />
        </ElDialog>
      </div>
    )
  }
})
