<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="mszyChapterContent">
      <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.tmz_zjmc" placement="bottom">
                      <div class="flex-1 titleWrap">{{ item.tmz_zjmc }}</div>
                    </el-tooltip>
                    <el-icon @click="handleDeleteSource(chapterData, index, '章节', 'chapter')">
                      <Delete />
                    </el-icon>
                  </div> -->
                  <draggable class="dragSourceDiv" v-model="chapterData" item-key="tmz_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.tmz_zjmc" placement="bottom">
                          <div class="flex-1 titleWrap">{{ element.tmz_zjmc }}</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">
                <el-form class="mx-30px h-full" ref="ruleFormRef" :rules="rules" label-position="right" label-width="120px" :model="ruleForm">
                  <el-form-item label="章节名称:" prop="tmz_zjmc">
                    <el-input v-model="ruleForm.tmz_zjmc" size="small" placeholder="标题">
                      <template #prefix>第{{ dealFigureToChinese(chapterIndex+1) }}章：</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="责任教师姓名:" prop="tmz_zrjs_mc">
                    <remote-user-select size="small" class="w-full" v-model="ruleForm.tmz_zrjs_user_id" v-model:model-name="ruleForm.tmz_zrjs_user_name" v-model:model-real-name="ruleForm.tmz_zrjs_mc" :d="{user_role_id:'75'}"></remote-user-select>
                  </el-form-item>
                  <el-form-item label="责任教师账号:" prop="tmz_zrjs_user_name">
                    <el-input v-model="ruleForm.tmz_zrjs_user_name" size="small"></el-input>
                  </el-form-item>
                  <el-form-item label="章节封面图:" prop="tmz_img_url">
                    <file-upload-progress v-model:part="ruleForm.tmz_img_url" :limit="1" accept=".jpg,.jpeg,.png" :size-limit="500 * 1024">
                      <template #default>
                        <el-button type="primary" size="large">点击上传</el-button>
                      </template>
                      <template #tip>
                        <div class="mt-2 text-xs">只能上传jpg/png/jpeg文件，且不超过500kb，建议尺寸600x337</div>
                      </template>
                    </file-upload-progress>
                    <el-input v-model="ruleForm.tmz_img_url" size="small" placeholder="可直在输入框填写图片地址"></el-input>
                  </el-form-item>
                  <el-form-item label="章节视频:" prop="tmz_video_url">
                    <file-upload-progress v-model:full="ruleForm.tmz_video_url" :limit="1" accept=".ppt,.pptx,.pdf,.mp4" :size-limit="500 * 1024 * 1024" @compile="(val) => handleSuccess(val, 'video')">
                      <template #default>
                        <el-button type="primary" size="large">点击上传</el-button>
                      </template>
                      <template #tip>
                        <div class="mt-2 text-xs">支持格式：mp4（500M以内）</div>
                      </template>
                    </file-upload-progress>
                    <el-input v-model="ruleForm.tmz_video_url" size="small" placeholder="可直在输入框填写视频地址"></el-input>
                  </el-form-item>
                  <el-form-item label="周期:" prop="tmz_zq">
                    <el-select v-model="ruleForm.tmz_zq" size="small">
                      <el-option v-for="(item, index) in termData" :key="index" :label="item.n" :value="item.v" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="">
                    <div class="flex space-x-4 justify-center">
                      <div>
                        <div>章节课件</div>
                        <div class="kjBorder">
                          <div class="h-full w-full flex items-center justify-center" v-if="zjkjData.length==0">
                            <div class="text-center">
                              <file-upload-progress :limit="1" accept=".ppt,.pptx,.pdf,.xls,.xlsx,.doc,.docx" class="btnUpload" @compile="(val) => handleSuccess(val, 'zjkj')">
                                <template #default>
                                  <el-button type="primary" size="large">添加课件</el-button>
                                </template>
                              </file-upload-progress>
                              <div class="dragText">可拖拽最右边课件到此处</div>
                            </div>
                            <draggable class="dragSourceDiv" v-model="zjkjData" item-key="name" :group='{name: "source", put: true}'>
                              <template #item="{element}">
                                {{ element.name }}
                              </template>
                            </draggable>
                          </div>
                          <div class="kjCon" v-else>
                            <img src="/images/file.png" alt="" />
                            <el-tooltip class="box-item" effect="dark" :hide-after="50" :offset="-5" :content="zjkjData[0].name" placement="bottom">
                              <div class="flex-1 px-1 titleWrap">{{ zjkjData[0].name }}</div>
                            </el-tooltip>
                            <div>（{{ zjkjData[0].size }}）</div>
                            <el-icon color="#00a3ff" class="cursor-pointer deleteIcon" @click="zjkjData=[]">
                              <CircleCloseFilled />
                            </el-icon>
                          </div>
                        </div>
                      </div>
                      <div>
                        <div>章节试题答案解析</div>
                        <div class="kjBorder">
                          <div class="h-full w-full flex items-center justify-center" v-if="zjstdajxData.length==0">
                            <div class="text-center">
                              <file-upload-progress limit="1" accept=".ppt,.pptx,.pdf,.xls,.xlsx,.doc,.docx" class="btnUpload" @compile="(val) => handleSuccess(val, 'zjstdajx')">
                                <template #default>
                                  <el-button type="primary" size="large">添加试题</el-button>
                                </template>
                              </file-upload-progress>
                              <div class="dragText">可拖拽最右边课件到此处</div>
                            </div>
                            <draggable class="dragSourceDiv" v-model="zjstdajxData" item-key="name" :group='{name: "source", put: true}'>
                              <template #item="{element}">
                                {{ element.name }}
                              </template>
                            </draggable>
                          </div>
                          <div class="kjCon" v-else>
                            <img src="/images/file.png" alt="" />
                            <el-tooltip class="box-item" effect="dark" :hide-after="50" :offset="-5" :content="zjstdajxData[0].name" placement="bottom">
                              <div class="flex-1 px-1 titleWrap">{{ zjstdajxData[0].name }}</div>
                            </el-tooltip>
                            <div>（{{ zjstdajxData[0].size }}）</div>
                            <el-icon color="#00a3ff" class="cursor-pointer deleteIcon" @click="zjstdajxData=[]">
                              <CircleCloseFilled />
                            </el-icon>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </el-form>
              </el-scrollbar>
            </div>
          </div>
          <div class="width240">
            <div class="chapterBorder width240" style="height: calc(100% - 200px - 1rem);">
              <div class="titleDiv">资源管理</div>
              <div class="chapterCon">
                <div class="searchDiv flex space-x-2 marginX-8px">
                  <el-input v-model="keyword" placeholder="请输入搜索的关键词" size="small" :suffix-icon="Search" />
                  <el-button type="primary" @click="handleSearchSource">搜索</el-button>
                </div>
                <div class="my-5px" style="height: calc(100% - 74px);">
                  <el-scrollbar view-class="h-full">
                    <div class="marginX-8px h-full">
                      <div class="h-full flex items-center justify-center" v-if="sourceData.length==0">此分类下没有资源</div>
                      <draggable class="h-full" v-else v-model="sourceData" item-key="name" :group='{name: "source", put: false, pull:"clone"}'>
                        <template #item="{element, index}">
                          <div class="source-list flex items-center">
                            <img src="/images/file.png" alt="" />
                            <el-tooltip class="box-item" effect="dark" :hide-after="50" :offset="-5" :content="`${element.name}（${element.size}）`" placement="bottom">
                              <div class="flex-1 px-1 titleWrap">{{ element.name }}（{{ element.size }}）</div>
                            </el-tooltip>
                            <!-- <el-icon color="#00a3ff" class="cursor-pointer" @click="handleDeleteSource(sourceData, index, '资源', 'source')">
                              <CircleCloseFilled />
                            </el-icon> -->
                          </div>
                        </template>
                      </draggable>
                    </div>
                  </el-scrollbar>
                </div>
                <file-upload-progress accept=".ppt,.pptx,.pdf,.xls,.xlsx,.doc,.docx" class="btnUpload" @compile="(val) => handleSuccess(val, 'source')">
                  <template #default>
                    <div class="btnDiv marginX-8px">上传资源</div>
                  </template>
                </file-upload-progress>
              </div>
            </div>
            <div class="chapterBorder width240 mt-4" style="height: 200px;">
              <div class="titleDiv">课程章节完结测试</div>
              <div class="chapterCon">
                <div style="height: 40px;">
                  <template v-if="testData.length==0">
                    <import-homework class="btnUpload" accept=".docx" @compile="(val) => handleSuccess(val, 'test')" @load="(val) => loading=val">
                      <template #default1>
                        <!-- <el-button class="btnDiv" type="primary" size="large">新增课程测试</el-button> -->
                        <div class="btnDiv marginX-8px">新增课程测试</div>
                      </template>
                    </import-homework>
                  </template>
                  <!-- <file-upload-progress accept=".ppt,.pptx,.pdf,.xls,.xlsx,.doc,.docx" v-if="testData.length==0" class="btnUpload" @compile="(val) => handleSuccess(val, 'test')">
                    <template #default>
                      <div class="btnDiv marginX-8px">新增课程测试</div>
                    </template>
                  </file-upload-progress> -->
                  <template v-else>
                    <div class="source-list flex items-center marginX-8px" v-for="(element, index) in testData" :key="index">
                      <img src="/images/file.png" alt="" />
                      <el-tooltip class="box-item" effect="dark" :hide-after="50" :offset="-5" :content="`${element.name}（${element.size}）`" placement="bottom">
                        <div class="flex-1 px-1 titleWrap">{{ element.name }}（{{ element.size }}）</div>
                      </el-tooltip>
                      <el-icon color="#00a3ff" class="cursor-pointer" @click="testData=[]">
                        <CircleCloseFilled />
                      </el-icon>
                    </div>
                  </template>
                </div>
                <div class="tip marginX-8px">弹出时间：观看视频结束后弹出</div>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="mt-20px mb-10px text-center">
      <el-button type="primary" plain @click="handleCancel">取消</el-button>
      <el-button style="margin-left: 50px;" type="primary" @click="handleSubmit(ruleFormRef)">确定</el-button>
    </div>

    <el-dialog width="80%" v-model="dialogVisible" destroy-on-close :close-on-click-modal="false" @close="handleClose">
      <TinymceVue v-if="dialogVisible" class="w-full h-600px" v-model="homeworkJson.content"></TinymceVue>
      <div class="text-center mt-15px">
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

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

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


const title = ref("");
const keyword = ref("");
const sourceData = ref([]);
const wholeSourceData = ref([]);
async function initDetailInfo() {
  let { code, data } = await request({ url: "/txwx/mszy_kc/detail", data: { tmk_id: parentId } });
  if (code == 1) {
    title.value = data.one_info.tmk_kcm + "编辑章节";
    wholeSourceData.value = data.one_info.all_kc_files;
    sourceData.value = [...wholeSourceData.value];
  }
}

const handleSearchSource = () => {
  sourceData.value = wholeSourceData.value.filter(item => item.name.indexOf(keyword.value) != -1);
}

const termData = ref([
  { v: "1", n: "春季" },
  { v: "2", n: "暑期" },
  { v: "3", n: "秋季" },
  { v: "4", n: "寒假" }
])

const chapterData = ref([]);
const chapterIndex = ref();
const chapterId = ref("");
const isModify = ref(false);
const ruleForm = ref({});
initForm();
function initForm() {
  ruleForm.value = {
    tmz_zjmc: "",
    tmz_zrjs_user_id: "",
    tmz_zrjs_user_name: "",
    tmz_zrjs_mc: "",
    tmz_img_url: "",
    tmz_video_url: "",
    tmz_zq: "",
    tmz_zjkj_file: "",
    tmz_zjsjdajx_file: "",
    tmz_kczjwjcs_file: "",
    tmk_id: parentId,
    tmz_sort: ""
  }
}
const ruleFormRef = ref();
const rules = reactive({
  tmz_zjmc: [{ required: true, message: "请输入章节名称", trigger: "blur" }],
  tmz_img_url: [{ required: true, message: "请选择章节封面图", trigger: "submit" }],
})

const zjkjData = ref([]);
const zjstdajxData = ref([]);
const testData = ref([]);

async function initChapterData() {
  loading.value = true;
  let res = await request({ url: "/txwx/mszy_zj/index", data: { tmk_id: parentId, limit: "999", sort: "asc" } });
  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();
  zjkjData.value = [];
  zjstdajxData.value = [];
  testData.value = [];
  setTimeout(() => {
    isModify.value = false;
  }, 0)
}

const initChapterDetail = async (index) => {
  chapterIndex.value = index;
  if (chapterData.value[index].tmz_id) {
    loading.value = true;
    chapterId.value = chapterData.value[index].tmz_id;
    zjkjData.value = [];
    zjstdajxData.value = [];
    testData.value = [];
    let { code, data } = await request({ url: "/txwx/mszy_zj/detail", data: { tmz_id: chapterId.value } });
    if (code == 1) {
      for (let key in ruleForm.value) {
        ruleForm.value[key] = data.one_info[key];
      }
      ruleForm.value.tmz_zq = data.one_info.tmz_zq_option_k;

      let file1 = ruleForm.value.tmz_zjkj_file.split(";");
      if (file1[0] && file1[1] && file1[2]) {
        zjkjData.value = [{
          name: file1[0],
          size: file1[1],
          url: file1[2],
        }]
      }

      let file2 = ruleForm.value.tmz_zjsjdajx_file.split(";");
      if (file2[0] && file2[1] && file2[2]) {
        zjstdajxData.value = [{
          name: file2[0],
          size: file2[1],
          url: file2[2],
        }]
      }

      let file3 = ruleForm.value.tmz_kczjwjcs_file.split(";");
      if (file3[0] && file3[1] && file3[2]) {
        testData.value = [{
          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 homeworkJson = ref({
  content: "",
  fileinfo: "",
  md5: ""
});
const currentZyData = ref({});

const handleSuccess = async (fileList, key) => {
  let file = fileList[fileList.length - 1];
  if (!file) return
  let obj = {
    name: file.name,
    size: file.size / 1024 / 1024 > 1 ? `${(file.size / 1024 / 1024).toFixed(2)}MB` : `${(file.size / 1024).toFixed(2)}KB`,
    url: file.response?.data.url
  }
  switch (key) {
    case "video":
      ruleForm.value.tmz_video_time = file.playTime ? getVideoDurationFormat2(file.playTime) : "";
      break;
    case "source":
      let data = {
        tmk_id: parentId,
        txwx_mszy_kc: {
          tmk_ty_files: Object.values(obj).join(";")
        }
      }
      let { code } = await request({ url: "/txwx/mszy_kc/edit", data });
      if (code == 1) {
        initDetailInfo();
      }
      break
    case "zjkj":
      if (file.response) {
        ruleForm.value.tmz_zjkj_file = Object.values(obj).join(";");
      }
      zjkjData.value.push(obj);
      break
    case "zjstdajx":
      if (file.response) {
        ruleForm.value.tmz_zjsjdajx_file = Object.values(obj).join(";");
      }
      zjstdajxData.value.push(obj);
      break
    case "test":
      if (file.response) {
        // ruleForm.value.tmz_kczjwjcs_file = Object.values(obj).join(";");
        obj.url = file.response.data.fileinfo.path;
        currentZyData.value = obj;


        homeworkJson.value = file.response.data;
        dialogVisible.value = true;
      }
      // testData.value.push(obj);
      break
  }
}

const dialogVisible = ref(false);
const handleConfirm = async () => {
  let obj = {
    md5: homeworkJson.value.md5,
    content: homeworkJson.value.content
  }
  let { code, data } = await request({ url: "/openapi/phpword.php", data: obj });
  if (code == 1) {
    ruleForm.value.tmz_kczjwjcs_tq_id = data.tq_ids;
    ruleForm.value.tmz_kczjwjcs_file = Object.values(currentZyData.value).join(";");
    testData.value.push(currentZyData.value);
    handleClose();
  }
}

const handleClose = () => {
  dialogVisible.value = false;
  homeworkJson.value = {
    content: "",
    fileinfo: "",
    md5: "",
  }
  currentZyData.value = {};
}

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

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

const handleSubmit = async (formEl) => {
  if (!formEl) return;

  formEl.validate(async (valid, fields) => {
    if (valid) {
      if (chapterId.value == "") {
        ruleForm.value.tmz_sort = chapterData.value.length;
      }
      let data = {
        txwx_mszy_zj: ruleForm.value
      }
      let res = {};
      if (chapterId.value == "") {
        res = await request({ url: "/txwx/mszy_zj/add", data });
      } else {
        data.tmz_id = chapterId.value;
        res = await request({ url: "/txwx/mszy_zj/edit", data });
      }
      if (res.code == 1) {
        ElMessage.success("保存成功！");
        init();
        setTimeout(() => {
          initChapterData();
          initDetailInfo();
        }, 0)
      }
    } else {
      console.log("error submit!", fields);
    }
  });
}


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



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


watch(() => [zjkjData.value, zjstdajxData.value], (newValue) => {
  if (newValue[0][0]) {
    ruleForm.value.tmz_zjkj_file = Object.values(newValue[0][0]).join(";");
  }
  if (newValue[1][0]) {
    ruleForm.value.tmz_zjsjdajx_file = Object.values(newValue[1][0]).join(";");
  }
})
</script>

<style lang="scss" scoped>
@use "~/styles/scroll.scss";
.mszyChapterContent {
  height: calc(100% - 24px - 32px - 40px);
  .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 {
      padding: 8px 0;
      height: calc(100% - 36px);
      .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 {
          width: 120px;
          // height: 90px;
          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;
          }
        }
      }
    }
  }
}
:deep() {
  .tox.tox-tinymce {
    height: 100% !important;
  }
}
</style>