<template>
  <div>
    <el-form class="mx-30px" ref="ruleFormRef" :rules="rules" label-position="right" label-width="120px" :model="ruleForm">
      <div class="grid grid-cols-2 gap-x-10">
        <el-form-item label="课时名称:" prop="tzk_ksmc">
          <el-input v-model="ruleForm.tzk_ksmc" size="small" placeholder="标题">
            <template #prefix>第{{ dealFigureToChinese(chapterIndex+1) }}课时：</template>
          </el-input>
        </el-form-item>
        <el-form-item label="姓名:" prop="tzk_xm">
          <remote-user-select size="small" class="w-full" v-model="ruleForm.tzk_zjr_user_id" v-model:model-name="ruleForm.tzk_zjr_user_name" v-model:model-real-name="ruleForm.tzk_xm" :d="{user_role_id:'75'}"></remote-user-select>
        </el-form-item>
        <el-form-item label="主讲人账号:" prop="tzk_zjr_user_name">
          <el-input v-model="ruleForm.tzk_zjr_user_name" size="small"></el-input>
        </el-form-item>
        <el-form-item label="所属单位:" prop="tzk_ssdw_id">
          <remote-select class="w-full" size="small" v-model="ruleForm.tzk_ssdw_id" v-model:model-name="ruleForm.tzk_ssdw" url="/school/main/index" :fields="['id', 'sm_name']"></remote-select>
        </el-form-item>
      </div>
      <el-form-item label="课时封面图片:" prop="tzk_img">
        <file-upload-progress v-model:part="ruleForm.tzk_img" :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.tzk_img" size="small" placeholder="可直在输入框填写图片地址"></el-input> -->
      </el-form-item>
      <div class="grid grid-cols-2 gap-x-10">
        <el-form-item label="直播开启时间:" prop="tzk_zbkqsj">
          <date-time-picker type="datetime" value-format="YYYY-MM-DD HH:mm:ss" v-model="ruleForm.tzk_zbkqsj" :start="kckssj"></date-time-picker>
        </el-form-item>
      </div>
      <div class="flex space-x-4">
        <div>
          <div>课时导学案</div>
          <div class="kjBorder">
            <div class="h-full w-full flex items-center justify-center" v-if="fileObj.ksdxaData.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, 'ksdxa')">
                  <template #default>
                    <el-button type="primary" size="large">添加</el-button>
                  </template>
                </file-upload-progress>
              </div>
            </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="fileObj.ksdxaData[0].name" placement="bottom">
                <div class="flex-1 px-1 titleWrap">{{ fileObj.ksdxaData[0].name }}</div>
              </el-tooltip>
              <div>（{{ fileObj.ksdxaData[0].size }}）</div>
              <el-icon color="#00a3ff" class="cursor-pointer deleteIcon" @click="fileObj.ksdxaData=[]">
                <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="fileObj.kscsData.length==0">
              <div class="text-center">
                <import-homework accept=".docx" @compile="(val) => handleSuccess(val, 'kscs')" @load="(val) => loading=val">
                  <template #default1>
                    <el-button type="primary" size="large">添加试题</el-button>
                  </template>
                </import-homework>
              </div>
            </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="fileObj.kscsData[0].name" placement="bottom">
                <div class="flex-1 px-1 titleWrap">{{ fileObj.kscsData[0].name }}</div>
              </el-tooltip>
              <div>（{{ fileObj.kscsData[0].size }}）</div>
              <el-icon color="#00a3ff" class="cursor-pointer deleteIcon" @click="fileObj.kscsData=[]">
                <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="fileObj.qtfjData.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, 'qtfj')">
                  <template #default>
                    <el-button type="primary" size="large">添加</el-button>
                  </template>
                </file-upload-progress>
              </div>
            </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="fileObj.qtfjData[0].name" placement="bottom">
                <div class="flex-1 px-1 titleWrap">{{ fileObj.qtfjData[0].name }}</div>
              </el-tooltip>
              <div>（{{ fileObj.qtfjData[0].size }}）</div>
              <el-icon color="#00a3ff" class="cursor-pointer deleteIcon" @click="fileObj.qtfjData=[]">
                <CircleCloseFilled />
              </el-icon>
            </div>
          </div>
        </div>
      </div>
    </el-form>

    <el-dialog width="80%" v-model="dialogVisible" destroy-on-close :close-on-click-modal="false" @close="handleClose">
      <!-- <file-preview class="h-600px" :url="currentUrl"></file-preview> -->
      <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 { Delete, Search, CircleCloseFilled } from "@element-plus/icons-vue"
import { dealFigureToChinese, getVideoDurationFormat2 } from "@/utils/common-util";

const loading = ref(false);

const props = defineProps({
  chapterIndex: Number,
  kckssj: String,
  ruleForm: Object,
  rules: Object,
  fileObj: Object
})

const emits = defineEmits(['update:ruleForm', 'update:fileObj', 'load', 'submit'])

const ruleFormRef = ref();

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 "ksdxa":
      if (file.response) {
        props.ruleForm.tzk_dxa_file = Object.values(obj).join(";");
      }
      props.fileObj.ksdxaData.push(obj);
      break
    case "kscs":
      if (file.response) {
        obj.url = file.response.data.fileinfo.path;
        currentZyData.value = obj;


        homeworkJson.value = file.response.data;
        dialogVisible.value = true;
      }
      break
    case "qtfj":
      if (file.response) {
        props.ruleForm.tzk_files_json = Object.values(obj).join(";");
      }
      props.fileObj.qtfjData.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) {
    props.ruleForm.tzk_ksce_tq_id = data.tq_ids;
    props.ruleForm.tzk_ksce_file = Object.values(currentZyData.value).join(";");
    props.fileObj.kscsData.push(currentZyData.value);
    handleClose();
  }
}

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

watch(
  () => loading.value,
  () => {
    emits("load", loading.value);
  }
);


const submit = () => {
  let formEl = ruleFormRef.value;
  if (!formEl) return;

  formEl.validate(async (valid, fields) => {
    if (valid) {
      emits("submit", false);
    } else {
      console.log("error submit!", fields);
    }
  });
}

defineExpose({ submit })
</script>

<style>
</style>