<template>
  <div v-loading="loading" class="box-border bg-white m-4 p-4 rounded-6px overflow-auto" style="height: calc(100% - 48px - 10px - 1rem);">
    <div class="title mb-10px">{{ title }}</div>
    <div class="zbkcChapterContent">
      <el-scrollbar view-class="h-full">
        <div class="flex space-x-4 h-full">
          <div class="chapterBorder width240">
            <div class="titleDiv">新建课时</div>
            <div class="chapterCon">
              <div class="btnDiv marginX-8px" style="margin-bottom: 10px;" @click="handleAddSource">新建课时</div>
              <div style="height: calc(100% - 42px);">
                <el-scrollbar view-class="h-full">
                  <!-- <div class="flex items-center cursor-pointer chapterItem mb-2 marginX-8px" :class="chapterIndex==index && 'active'" v-for="(item, index) in chapterData" :key="index" @click="initIndex(index)">
                    <div>第{{ dealFigureToChinese(index+1) }}课时：</div>
                    <el-tooltip class="box-item" effect="dark" :hide-after="50" :offset="-5" :content="item.tzk_ksmc" placement="bottom">
                      <div class="flex-1 titleWrap">{{ item.tzk_ksmc }}</div>
                    </el-tooltip>
                    <el-icon @click="handleDeleteSource(chapterData, index, '课时', 'chapter')">
                      <Delete />
                    </el-icon>
                  </div> -->
                  <draggable class="dragSourceDiv" v-model="chapterData" item-key="tzk_id" @end="handleEndChange">
                    <template #item="{element, index}">
                      <div class="flex items-center cursor-pointer chapterItem mb-2 marginX-8px" :class="chapterIndex==index && 'active'" @click="initIndex(index)">
                        <div>第{{ dealFigureToChinese(index+1) }}课时：</div>
                        <el-tooltip class="box-item" effect="dark" :hide-after="50" :offset="-5" :content="element.tzk_ksmc" placement="bottom">
                          <div class="flex-1 titleWrap">{{ element.tzk_ksmc }}</div>
                        </el-tooltip>
                        <el-icon @click="handleDeleteSource(chapterData, index, '课时', 'chapter')">
                          <Delete />
                        </el-icon>
                      </div>
                    </template>
                  </draggable>
                </el-scrollbar>
              </div>
            </div>
          </div>
          <div class="chapterBorder flex-1">
            <div class="titleDiv">编辑框</div>
            <div class="chapterCon">
              <el-scrollbar view-class="h-full">
                <template v-if="ruleForm.tzk_zbjssj=='' || !new Date(ruleForm.tzk_zbjssj).getTime()">
                  <course-start ref="courseStart" :chapterIndex="chapterIndex" :kckssj="kckssj" :ruleForm="ruleForm" :rules="rules" :fileObj="fileObj" @load="(val) => loading=val" @submit="handleSubmit" />
                  <div class="pt-20px pb-10px text-center">
                    <el-button type="primary" plain @click="handleCancel">取消</el-button>
                    <el-button style="margin-left: 50px;" type="primary" @click="handleSubmit(true)">确定</el-button>
                  </div>
                </template>
                <template v-else>
                  <course-end :chapterIndex="chapterIndex" :ruleForm="ruleForm" :fileObj="fileObj" />
                </template>
              </el-scrollbar>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import draggable from "vuedraggable"
import { Delete, Search, CircleCloseFilled } from "@element-plus/icons-vue"
import { dealFigureToChinese, getVideoDurationFormat2 } from "@/utils/common-util";
import CourseStart from "./course/CourseStart.vue";
import CourseEnd from "./course/CourseEnd.vue";

const loading = ref(false);

const router = useRouter();
const parentId = router.currentRoute.value.params.id;
if (parentId) {
  initDetailInfo();
  initChapterData();
}

const title = ref("");
const kckssj = ref("");
async function initDetailInfo() {
  let { code, data } = await request({ url: "/txwx/zbkc/detail", data: { tz_id: parentId } });
  if (code == 1) {
    title.value = data.one_info.tz_kcbt + "编辑课时";
    kckssj.value = data.one_info.tjzx_zbkqsj;
  }
}

const chapterData = ref([]);
const chapterIndex = ref();
const chapterId = ref("");
const isModify = ref(false);
const ruleForm = ref({});
initForm();
function initForm() {
  ruleForm.value = {
    tzk_ksmc: "",
    tzk_zjr_user_id: "",
    tzk_zjr_user_name: "",
    tzk_xm: "",
    tzk_ssdw: "",
    tzk_ssdw_id: "",
    tzk_img: "",
    tzk_zbkqsj: "",
    tzk_zbjssj: "",
    tzk_dxa_file: "",
    tzk_ksce_file: "",
    tzk_ksce_tq_id: "",
    tzk_files_json: "",
    tz_id: parentId,
    tzk_sort: "",
    tzk_video_file: "",
  }
}
const rules = reactive({
  tzk_ksmc: [{ required: true, message: "请输入课时名称", trigger: "blur" }],
  tzk_img: [{ required: true, message: "请选择课时封面图", trigger: "submit" }],
})
const courseStart = ref();

const fileObj = ref({
  ksdxaData: [],
  kscsData: [],
  qtfjData: []
})

async function initChapterData() {
  loading.value = true;
  let res = await request({ url: "/txwx/zbkc_ks/index", data: { tz_id: parentId, limit: "999" } });
  if (res.code == 1) {
    chapterData.value = res.data.page_data;
    if (chapterData.value.length == 0) {
      loading.value = false;
      handleAddSource();
    } else {
      initIndex(chapterIndex.value || 0);
    }
  }
}

const initIndex = async (index) => {
  if (isModify.value) {
    ElMessageBox.confirm('当前数据未保存，是否离开当前页面？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: "warning",
    })
      .then(() => {
        initChapterDetail(index);
      })
      .catch(() => {

      })
  } else {
    initChapterDetail(index);
  }
}

function init() {
  chapterId.value = "";
  initForm();
  fileObj.value.ksdxaData = [];
  fileObj.value.kscsData = [];
  fileObj.value.qtfjData = [];
  setTimeout(() => {
    isModify.value = false;
  }, 0)
}

const initChapterDetail = async (index) => {
  chapterIndex.value = index;
  if (chapterData.value[index].tzk_id) {
    loading.value = true;
    chapterId.value = chapterData.value[index].tzk_id;
    fileObj.value.ksdxaData = [];
    fileObj.value.kscsData = [];
    fileObj.value.qtfjData = [];
    let { code, data } = await request({ url: "/txwx/zbkc_ks/detail", data: { tzk_id: chapterId.value } });
    if (code == 1) {
      for (let key in ruleForm.value) {
        ruleForm.value[key] = data.one_info[key];
      }

      if (ruleForm.value.tzk_dxa_file) {
        let file1 = ruleForm.value.tzk_dxa_file.split(";");
        if (file1[0] && file1[1] && file1[2]) {
          fileObj.value.ksdxaData = [{
            name: file1[0],
            size: file1[1],
            url: file1[2],
          }]
        }
      }
      if (ruleForm.value.tzk_ksce_file) {
        let file2 = ruleForm.value.tzk_ksce_file.split(";");
        if (file2[0] && file2[1] && file2[2]) {
          fileObj.value.kscsData = [{
            name: file2[0],
            size: file2[1],
            url: file2[2],
          }]
        }
      }
      if (ruleForm.value.tzk_files_json) {
        let file3 = ruleForm.value.tzk_files_json.split(";");
        if (file3[0] && file3[1] && file3[2]) {
          fileObj.value.qtfjData = [{
            name: file3[0],
            size: file3[1],
            url: file3[2],
          }]
        }
      }

      setTimeout(() => {
        isModify.value = false;
      }, 0)
      loading.value = false;
    }
  } else {
    init();
  }
}

const handleAddSource = () => {
  chapterData.value.push({});
  initIndex(chapterData.value.length - 1);
}

const handleDeleteSource = (data, index, name, key) => {
  ElMessageBox.confirm(`确定要删除该${name}吗？`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: "warning",
  })
    .then(async () => {
      if (key == "chapter") {
        let { code } = await request({ url: "/txwx/zbkc_ks/delete", data: { tzk_id: data[index].tzk_id } });
        if (code == 1) {
          ElMessage.success("删除成功！");
          chapterIndex.value = 0;
          init();
          setTimeout(() => {
            initChapterData();
          }, 0)
        }
      }
    })
    .catch(() => { })
}

const handleCancel = () => {
  router.back();
}

const handleSubmit = async (verify) => {
  if (verify) {
    courseStart.value.submit();
    return
  }
  if (chapterId.value == "") {
    ruleForm.value.tzk_sort = chapterData.value.length;
  }
  let data = {
    txwx_zbkc_ks: ruleForm.value
  }
  let res = {};
  if (chapterId.value == "") {
    res = await request({ url: "/txwx/zbkc_ks/add", data });
  } else {
    data.tzk_id = chapterId.value;
    res = await request({ url: "/txwx/zbkc_ks/edit", data });
  }
  if (res.code == 1) {
    ElMessage.success("保存成功！");
    init();
    setTimeout(() => {
      initChapterData();
    }, 0)
  }
}

const handleEndChange = async () => {
  let arr = chapterData.value.map((item, index) => {
    return `${item.tzk_id}-${index}`
  })
  let obj = {
    sort_string: arr.join(",")
  }
  let { code } = await request({ url: "/txwx/zbkc_ks/batch_sort", data: obj });
  if (code == 1) {
    init();
    setTimeout(() => {
      initChapterData();
    }, 0)
  }
}

watch(
  () => ruleForm.value,
  (newVal, oldVal) => {
    isModify.value = true;
  },
  { deep: true },
)

watch(() => [fileObj.value.ksdxaData, fileObj.value.kscsData, fileObj.value.qtfjData], (newValue) => {
  ruleForm.value.tzk_dxa_file = newValue[0][0] ? Object.values(newValue[0][0]).join(";") : "";
  ruleForm.value.tzk_ksce_file = newValue[1][0] ? Object.values(newValue[1][0]).join(";") : "";
  if (!newValue[1][0]) {
    ruleForm.value.tzk_ksce_tq_id = "";
  }
  ruleForm.value.tzk_files_json = newValue[2][0] ? Object.values(newValue[2][0]).join(";") : "";
})
</script>

<style lang="scss" scoped>
@use "~/styles/scroll.scss";
.zbkcChapterContent {
  height: calc(100% - 34px);
  .chapterBorder {
    border: 1px solid #d7d7d7;
    font-size: 14px;
    &.width240 {
      width: 240px;
    }
    .marginX-8px {
      margin: 0 10px;
    }
    .titleDiv {
      background: #f2f2f2;
      border-bottom: 1px solid #d7d7d7;
      font-size: 14px;
      line-height: 35px;
      padding: 0 15px;
    }
    .chapterCon:deep() {
      padding: 8px 0;
      height: calc(100% - 36px);
      .el-date-editor {
        &.el-input {
          width: 100%;
        }
        .el-input__wrapper {
          width: 100%;
        }
      }
      .tox.tox-tinymce {
        height: 100% !important;
      }
      .filename {
        line-height: 20px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 220px;
      }
      .btnDiv {
        background: var(--el-color-primary);
        color: #fff;
        text-align: center;
        border-radius: 2px;
        line-height: 32px;
        cursor: pointer;
      }
      .titleWrap {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .chapterItem {
        line-height: 32px;
        border-radius: 2px;
        padding: 0 5px;
      }
      .active {
        // background: rgba($color: var(--el-color-primary), $alpha: 0.2);
        background: rgba($color: #00a3ff, $alpha: 0.2);
      }
      .tip {
        color: #8e8e8e;
      }
      .kjBorder {
        width: 144px;
        height: 144px;
        border: 1px dashed #979797;
        position: relative;
        background: linear-gradient(white, white) padding-box,
          repeating-linear-gradient(
            -45deg,
            #ccc 0,
            #ccc 0.25em,
            white 0,
            white 0.75em
          );
        .dragText {
          font-size: 12px;
          color: #606266;
          margin-top: -10px;
        }
        .dragSourceDiv {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          pointer-events: none;
        }
        .kjCon {
          // cursor: pointer;
          width: 120px;
          padding: 15px 0;
          background: rgba(0, 163, 255, 0.1);
          border: 1px solid #00a3ff;
          border-radius: 4px;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          text-align: center;
          font-size: 12px;
          line-height: 20px;
          img {
            width: 16px;
            margin: auto;
          }
          .deleteIcon {
            position: absolute;
            top: 0;
            right: 0;
            transform: translate(50%, -50%);
          }
        }
      }
      .source-list {
        line-height: 34px;
        img {
          width: 16px;
        }
      }
      :deep() {
        .btnUpload {
          .el-upload {
            display: block;
          }
          .el-upload-list__item {
            display: none;
          }
        }
      }
    }
  }
}
</style>