<script setup lang="ts">
import AppUpload from '@/components/base/AppUpload.vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createCourse, getCourseDetails, updateCourse } 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) {
  getCourseDetails({ id: id }).then((res: any) => {
    form = res.data
    form.file = [
      {
        name: res.data.name,
        url: res.data.url
      }
    ]
  })
}

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

// form表单
let form: any = $ref({
  file: [],
  name: '',
  source: '2',
  classification: '',
  knowledge_points: '',
  url: '',
  type: '',
  size: ''
})

// 监听文件上传
watch(
  () => form.file,
  value => {
    form.name = value[0]?.name.slice(0, value[0]?.name.lastIndexOf('.')) || ''
  }
)

// 表单验证
const rules = {
  name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  classification: [{ required: true, message: '请选择分类', trigger: 'change' }],
  file: [{ required: true, message: '' }]
}
// 新建编辑表单提交
const ruleFormRef = ref<FormInstance>()

let submitFlag = true
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (!submitFlag) return
  submitFlag = false
  await formEl.validate(valid => {
    if (valid) {
      if (!protocol.value) {
        submitFlag = true
        ElMessage('请勾选用户协议')
        return
      }
      const { url, size } = form.file[0]
      const findString = url.lastIndexOf('.') + 1
      form.url = url
      form.type = url.substring(findString, url.length)
      form.size = size
      const params = Object.assign({}, form)
      delete params.file
      if (isUpdate) {
        params.id = id
        updateResources(params)
      } else {
        createResources(params)
      }
    } else {
      submitFlag = true
      ElMessage('请完善信息')
    }
  })
}

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

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

// 协议
const protocol = ref(false)

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

<template>
  <AppCard :title="isUpdate ? '编辑课件资源' : '新建课件资源'">
    <el-form ref="ruleFormRef" :model="form" :rules="rules" style="width: 70%">
      <el-form-item label="课件文件：" prop="file">
        <div>
          <div class="upload-video">
            <div class="upload-box">
              <AppUpload accept=".doc,.docx,.xls,.xlsx,.pdf,.ppt,.pptx" :limit="1" v-model="form.file"></AppUpload>
              <div class="upload-btn">本地文件</div>
            </div>
          </div>
          <div class="tips">课件支持格式包含：doc docx xls xlsx pdf ppt pptx，大小不超过50M</div>
        </div>
      </el-form-item>
      <el-form-item label="课件名称：" prop="name">
        <el-input maxlength="40" v-model="form.name" />
        <div class="tips">课件名称自动取值于文件名称，可以进行二次修改。</div>
      </el-form-item>
      <el-form-item label="课件分类：" prop="classification">
        <el-tree-select
          :render-after-expand="false"
          style="width: 100%"
          :props="defaultProps"
          v-model="form.classification"
          :data="selectTree"
          placeholder="请选择课件分类"
          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="请输入该课件相关知识点，多个知识点请使用“，”分隔"
          maxlength="100"
          v-model="form.knowledge_points"
          :rows="2"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <div class="protocol-box">
      <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">
.tips {
  font-size: 12px;
  line-height: 100%;
  color: #999999;
  margin-top: 8px;
}
.upload-box {
  // min-width: 400px;
  .el-progress__text {
    transform: translate(20px, -5px);
  }
  position: relative;
  .app-upload-btn {
    position: relative;
    z-index: 99;
    opacity: 0.0001 !important;
  }
}
.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;
    }
  }
  .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;
    }
  }
}
:deep(.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;
  }
}
.upload-video {
  width: 500px;
  display: flex;
  align-items: center;
  .upload-btn {
    position: absolute;
    top: 0;
    left: 0;
    width: 94px;
    line-height: 36px;
    background: rgba(250, 223, 230, 0.39);
    border: 1px solid #aa1941;
    border-radius: 20px;
    font-size: 14px;
    color: #aa1941;
    margin-right: 30px;
    text-align: center;
  }
  .video-info {
    display: flex;
    .name {
      color: #333333;
      font-size: 16px;
      line-height: 100%;
    }
    .view {
      font-size: 16px;
      line-height: 100%;
      color: #399ee8;
      margin-left: 20px;
      cursor: pointer;
    }
  }
}
</style>
