<script setup lang="ts">
import { PictureFilled, ArrowLeftBold, ArrowRightBold } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import UploadImg from '../components/UploadImg.vue'
import UploadVideo from '../components/UploadVideo.vue'
import { getCoverList, createVideo, getVideoDetails, updateVideo } from '../api'
import { useGetCategoryList } from '@/composables/useGetCategoryList'
import Protocol from '@/components/base/Protocol.vue'

// 路由
const router = useRouter()
const route = useRoute()

const id = route.query.id as string

// is 编辑 新建
const isUpdate = computed(() => {
  return !!route.query.id
})

// 编辑数据回显
if (isUpdate.value) {
  getVideoDetails({ id: id }).then((res: any) => {
    form.data = res.data
  })
}

// 下拉选择tree 视频分类
let { list: selectTree }: any = useGetCategoryList()
const defaultProps = {
  children: 'children',
  label: 'category_name',
  value: 'id'
}

// 视频封面图轮播
const swiperCovers = ref<{ id: string; url: string }[][]>([[]])
// 获取封面
getCoverList().then(res => {
  const filtersData = res.data.list.filter((i: any) => i.type === '1')
  let index = 0
  while (index < filtersData.length) {
    swiperCovers.value.push(filtersData.slice(index, (index += 8)))
  }
  swiperCovers.value.forEach((item: any, index: number) => {
    if (item.length === 0) {
      swiperCovers.value.splice(index, 1)
    }
  })
})
// 获取swiper 自定义左右切换按钮
let swiper = ref()
const swiperChange = (type?: string) => {
  type === 'prev' ? swiper.value.prev() : swiper.value.next()
}
const swiperItemHandle = (url: string) => {
  form.data.cover = url
}

// form表单
let form = reactive({
  data: { name: '', source: '2', classification: '', knowledge_points: '', cover: '', source_id: '' }
})
// 表单验证
const rules = {
  name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  classification: [{ required: true, message: '请选择分类', trigger: 'change' }],
  source_id: [{ required: true, message: '' }]
}
const ruleFormRef = ref<FormInstance>()
let submitFlag = true
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!submitFlag) return
  submitFlag = false
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      if (!protocol.value) {
        submitFlag = true
        ElMessage('请勾选用户协议')
        return
      }
      if (isUpdate.value) {
        updateResources()
      } else {
        createResources()
      }
    } else {
      submitFlag = true
      ElMessage('请完善信息')
    }
  })
}

// 更新
const updateResources = () => {
  const params = Object.assign({ id: id }, form.data)
  updateVideo(params)
    .then((res: any) => {
      if (res.code === 0) {
        ElMessage({ message: '更新成功', type: 'success' })
        setTimeout(() => {
          router.push({
            path: '/resource/video'
          })
        }, 1000)
      } else {
        submitFlag = true
      }
    })
    .catch(() => {
      submitFlag = true
    })
}

// 新建
const createResources = () => {
  createVideo(form.data)
    .then((res: any) => {
      if (res.code === 0) {
        ElMessage({ message: '创建成功', type: 'success' })
        setTimeout(() => {
          router.push({
            path: '/resource/video'
          })
        }, 1000)
      } else {
        submitFlag = true
      }
    })
    .catch(() => {
      submitFlag = true
    })
}

// 协议勾选
const protocol = ref(false)

// 上传视频成功
const uploadVideo = (data: any) => {
  form.data.source_id = data.videoId
  const name = data.name
  form.data.name = name.slice(0, name.lastIndexOf('.'))
}

const isSwiperBtn = ref(0)
const watchSwiper = (index: number) => {
  if (!index) {
    isSwiperBtn.value = 0
  } else {
    swiperCovers.value.length === index + 1 ? (isSwiperBtn.value = 1) : (isSwiperBtn.value = 2)
  }
}

const changeProtocol = (data: any) => {
  protocol.value = data.value
}
</script>

<template>
  <AppCard :title="isUpdate ? '编辑视频资源' : '新建视频资源'">
    <el-form ref="ruleFormRef" :model="form.data" :rules="rules" style="width: 70%">
      <el-form-item label="视频文件：" prop="source_id" v-if="!isUpdate">
        <UploadVideo @upload="uploadVideo" :createFlag="1"></UploadVideo>
      </el-form-item>
      <el-form-item label="视频名称：" prop="name">
        <el-input v-model="form.data.name" maxlength="40" />
        <div class="tips">视频名称自动取值于文件名称，可以进行二次修改。</div>
      </el-form-item>
      <el-form-item label="视频分类：" prop="classification">
        <el-tree-select
          :render-after-expand="false"
          :props="defaultProps"
          style="width: 100%"
          v-model="form.data.classification"
          :data="selectTree"
          node-key="id"
          :default-expanded-keys="selectTree.length ? [selectTree[0]?.id] : []" />
      </el-form-item>
      <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;知识点：">
        <el-input
          placeholder="请输入该视频相关知识点，多个知识点请使用“，”分隔"
          v-model="form.data.knowledge_points"
          :rows="2"
          type="textarea"
          maxlength="100" />
      </el-form-item>
      <el-form-item label="&nbsp;&nbsp;视频封面：">
        <div class="video-cover">
          <div class="img-box">
            <el-icon :size="50" color="#ccc" v-if="form.data.cover == ''">
              <PictureFilled></PictureFilled>
            </el-icon>
            <div v-else class="cover-img" :style="`background-image:url(${form.data.cover})`"></div>
          </div>
          <div class="video-cover_right">
            <UploadImg accept=".jpg,.jpeg,.gif,.png" v-model="form.data.cover"></UploadImg>
            <div class="list">
              <div class="item">
                <img src="/center_resource/upload-video-icon.png" class="icon" />
                <div class="text">该图片作为视频的封面图，用于视频封面显示</div>
              </div>
              <div class="item">
                <img src="/center_resource/upload-video-icon.png" class="icon" />
                <div class="text">支持jpg/jpeg/gif/png格式</div>
              </div>
              <div class="item">
                <img src="/center_resource/upload-video-icon.png" class="icon" />
                <div class="text">支持小于4M，最好宽240*高175*及以上尺寸</div>
              </div>
              <div class="item">
                <img src="/center_resource/upload-video-icon.png" class="icon" />
                <div class="text">可以自己上传图片，也可以从下面这些图片中选择使用</div>
              </div>
            </div>
          </div>
        </div>
        <div class="swiper-box">
          <div class="block text-center" v-if="swiperCovers.length">
            <el-carousel
              @change="watchSwiper"
              height="202px"
              :autoplay="false"
              arrow="never"
              trigger="click"
              ref="swiper">
              <el-carousel-item v-for="(item, index) in swiperCovers" :key="index" class="cover-list">
                <div
                  @click="swiperItemHandle(cItem.url)"
                  :key="cItem.id"
                  v-for="cItem in item"
                  :style="`background-image:url(${cItem.url})`"
                  class="cover-list_item"></div>
              </el-carousel-item>
            </el-carousel>
          </div>
          <el-icon v-if="isSwiperBtn != 0" class="arrow left" @click="swiperChange('prev')"><ArrowLeftBold /></el-icon>
          <el-icon v-if="isSwiperBtn != 1" class="arrow right" @click="swiperChange('next')"
            ><ArrowRightBold
          /></el-icon>
        </div>
      </el-form-item>
    </el-form>
    <div class="protocol-box">
      <Protocol :select="protocol" @change="changeProtocol"></Protocol>
    </div>
    <div class="btn-box">
      <div class="confirm" @click="submitForm(ruleFormRef)">保存</div>
      <div class="cancel" @click="router.go(-1)">取消</div>
    </div>
  </AppCard>
</template>
<style lang="scss" scoped>
.tips {
  font-size: 12px;
  line-height: 100%;
  color: #999999;
  margin-top: 8px;
}
.tool-btn-box {
  display: flex;
  justify-content: right;
  .btn-item {
    width: 127px;
    line-height: 36px;
    background: #aa1941;
    border-radius: 20px;
    margin-right: 10px;
    font-size: 14px;
    color: #ffffff;
    text-align: center;
  }
}
.demo-progress {
  width: 350px;
}
.video-cover {
  display: flex;
  .img-box {
    width: 208px;
    height: 130px;
    border-radius: 4px;
    background: #f7f7f7;
    font-size: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    // img {
    //   width: 100%;
    //   // height: 100%;
    //   display: block;
    // }
    .cover-img {
      width: 208px;
      height: 130px;
      background-size: cover;
    }
  }
  .video-cover_right {
    margin-left: 20px;
    .list {
      .item {
        display: flex;
        align-items: center;
        margin-top: 12px;
        img {
          width: 9px;
          display: block;
          margin-right: 5px;
        }
        .text {
          font-size: 12px;
          color: #999999;
          line-height: 100%;
        }
      }
    }
  }
}
.swiper-box {
  min-width: 660px;
  margin-top: 20px;
  padding: 0 40px;
  position: relative;
  .arrow {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    font-size: 30px;
    color: #d5d5d5;
    cursor: pointer;
    &.left {
      left: 0;
    }
    &.right {
      right: 10px;
    }
  }
  .cover-list {
    display: flex;
    flex-wrap: wrap;
    .cover-list_item {
      display: block;
      width: 155px;
      height: 96px;
      margin: 0 10px 10px 0;
      border-radius: 4px;
      cursor: pointer;
      background-size: cover;
    }
  }
}
.el-carousel__indicators--horizontal {
  display: none;
}
.protocol-box {
  font-size: 14px;
  line-height: 24px;
  padding-left: 90px;
  padding-top: 20px;
  color: #666666;
}
.btn-box {
  display: flex;
  margin-top: 20px;
  margin-left: 90px;
  .confirm {
    width: 94px;
    background: #aa1941;
    border-radius: 20px;
    text-align: center;
    line-height: 36px;
    color: #fff;
    margin-right: 26px;
    cursor: pointer;
  }
  .cancel {
    width: 94px;
    line-height: 36px;
    border: 1px solid #aa1941;
    border-radius: 20px;
    text-align: center;
    color: #aa1941;
    cursor: pointer;
  }
}
</style>
