<template>
  <el-card style="min-height: calc(100vh - 100px)">
    <backPage @click="goBack"></backPage>
    <div class="row">
      <div class="left">
        <el-button type="primary" @click="addPage" style="width: 114px"
          >增加页数</el-button
        >
        <el-tree
          ref="treeRef"
          default-expand-all
          style="max-width: 600px"
          :data="treeData"
          :props="defaultProps"
          :default-checked-keys="[0]"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span
              class="nametitle"
                :class="{ active: data.id == showTab && node.level == 2 }"
                 :title="node.label">{{ node.label }}</span
              >
              <span style="display: inline-block; margin-left: 10px">
                <a @click="delData(data)" v-if="node.level == 2"
                  ><el-icon color="red"><Delete /></el-icon
                ></a>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
      <div class="right">
        <div
          class="content"
          v-for="(item, index) in pageData"
          :key="item.case_item_id"
        >
          <div class="unit" v-show="showTab == index">
            <el-row :gutter="20" style="margin-top: 30px" v-if="showTab !== 0">
              <el-col :span="8">
                <el-button type="primary" @click="addModel">增加模块</el-button>
              </el-col>
            </el-row>
            <el-divider v-if="showTab !== 0" />

            <div class="unit" v-for="(cell, key) in item.case_item_model" :key="key">
              <el-row :gutter="20">
                <el-col :span="23">
                  <el-form-item :label="'模块' +(key+1)"> </el-form-item>
                </el-col>
                <el-col :span="1">
                  <el-icon
                   v-if="item.case_item_model.length>1"
                    color="red"
                    size="20px"
                    style="cursor: pointer"

                    @click="delModel(key)"
                    ><Delete
                  /></el-icon>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="模块标题：" prop="question_answer">
                    <el-input
                      v-model="cell.model_name"
                      style="width: 350px"
                      placeholder="请输入模块标题"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="模块内容：" prop="baidueditor">
                    <ueditor
                      v-if="showTab == index"
                      v-model="cell.content"
                      :id="index + 'baidueditor' + key"
                    ></ueditor>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-divider />
            </div>
            <!-- <div class="unit" v-else>
              <ueditor
              v-show="showTab == index"
              v-model="item.content"
              :id="'baidueditor' + index"
              ></ueditor>
            </div> -->
            <!-- <el-row :gutter="20" style="margin-top: 30px" v-if="showTab !== 0">
              <el-col :span="8">
               
              </el-col>
            </el-row> -->
            <!-- <el-row :gutter="20" style="margin-top: 30px" v-if="showTab !== 0">
              <el-col :span="12">
                
              </el-col>
            </el-row> -->
            <el-row :gutter="20" style="margin-top: 30px" v-if="showTab !== 0">
              <el-col :span="8">
                <el-button type="primary" :disabled="item.case_item_question && (item.case_item_question)[0] && (item.case_item_question)[0].created_at"  @click="addQuestion"
                  >增加题目</el-button
                >
              </el-col>
            </el-row>
            <el-divider v-if="showTab !== 0" />
            <div v-if="showTab !== 0">
              <question
                :modalForm="cell"
                v-for="(cell, key) in item.case_item_question"
                :key="cell.name"
                :qIndex="key"
                @handleAddSelect="handleAddSelect"
                @handleDelQusetion="handleDelQusetion"
                @handleDelSelect="handleDelSelect"
                @handleChangeType="handleChangeType"
              ></question>
            </div>
            <div class="rowSave">
              <el-button type="primary"   @click="handleSave(item.case_item_id)">
                保存
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import userApi from "../api/user";
import { ElMessage, ElMessageBox } from "element-plus";
const case_id = ref("");
const treeData = ref([]);
const pageData = ref([]);
const caseDetail = reactive({
  case_author: "",
  case_id: "",
  case_name: "",
  case_status: null,
});
const isAdd = ref(false);
const emits = defineEmits(["goBack"]);

const treeRef = ref(null);
const showTab = ref(0);
const defaultProps = {
  children: "children",
  label: "label",
};
const goBack = () => {
  emits("goBack");
};
const page = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
const getDetail = async (id,tab=0) => {
  const { code, data } = await userApi.getCaseDetail(id);
  if (code == 200) {
    pageData.value = data.case_item ? data.case_item : [];
    caseDetail.case_author = data.caseDetail;
    caseDetail.case_id = data.case_id;
    caseDetail.case_name = data.case_name;
    caseDetail.project_id = data.project_id;
    caseDetail.case_status = data.case_status;
     showTab.value = tab || 0;
    if (pageData.value.length == 0) {
      isAdd.value = false;
    }
    //currentPageData.data = pageData.value[0];
    let temp = pageData.value.map((item, index) => {
      return {
        id: index,
        level: 1,
        label: "第" + page[index] + "页",
        // children: [
        //   {
        //     parentId: index,
        //     index: 0,
        //     id: index + 1 + "-" + 0,
        //     level: 2,
        //     label: "内容",
        //   },
        //   {
        //     id: index + 1 + "-" + 1,
        //     parentId: index,
        //     level: 2,
        //     index: 1,
        //     label: "问题",
        //   },
        // ],
      };
    });
    treeData.value = [
      {
        id: -1,
        level: 0,
        index: 0,
        label: data.case_name,
        children: temp,
      },
    ];
    if (pageData.value.length == 0) {
       addPage();
    }
  }
};

const handleNodeClick = (data) => {
  if (data.level == 1) {
    showTab.value = data.id;
    //currentPageData.data = pageData.value[data.id];
    //console.log(currentPageData.data)
  }

  console.log(data);
};
const handleAddSelect = (data) => {
  pageData.value[showTab.value].case_item_question[
    data
  ].case_item_question_option.push({
    option_id: new Date().getTime(),
  });
};
const addModel = () => {
  pageData.value[showTab.value].case_item_model.push({
    content: "",
    model_name: "",
    case_item_model_id:''
  });
};
const delModel = (index) => {
  pageData.value[showTab.value].case_item_model.splice(index, 1);
};
const handleChangeType = (data) => {
  console.log(pageData.value[showTab.value].case_item_question[data.qIndex]);
  pageData.value[showTab.value].case_item_question[data.qIndex].question_type =
    data.typeVal;
  if (data.typeVal == 1 || data.typeVal == 2) {
    pageData.value[showTab.value].case_item_question[
      data.qIndex
    ].case_item_question_option =[{
      option_id: new Date().getTime(),
      option_value:'',
    }];
    let arr =
      pageData.value[showTab.value].case_item_question[data.qIndex]
        .case_item_question_option;
    if (!arr) {
      pageData.value[showTab.value].case_item_question[
        data.qIndex
      ].case_item_question_option = [];
      handleAddSelect(data.qIndex);
    }
  } else {
    pageData.value[showTab.value].case_item_question[
      data.qIndex
    ].case_item_question_option = null;
    if (data.typeVal == 4) {
      pageData.value[showTab.value].case_item_question[
        data.qIndex
      ].case_item_question_option = [
        {
          option_id: 1,
          option_value: "正确",
        },
        {
          option_id: 2,
          option_value: "错误",
        },
      ];
    }
  }
};
const handleDelSelect = (data) => {
  console.log(pageData.value[showTab.value].case_item_question[data.qIndex].case_item_question_option);
  if(pageData.value[showTab.value].case_item_question[data.qIndex].case_item_question_option){
    pageData.value[showTab.value].case_item_question[data.qIndex].case_item_question_option.splice(data.delIndex, 1);
  }
 
};
const addQuestion = () => {
  if (!pageData.value[showTab.value].case_item_question) {
    pageData.value[showTab.value].case_item_question = [];
  }
  pageData.value[showTab.value].case_item_question.push({
    question_id:'',
    is_right_next: 2,
  });
};
const handleDelQusetion = (data) => {
  pageData.value[showTab.value].case_item_question.splice(data.qIndex, 1);
};
const delData = (data) => {
  
  ElMessageBox.confirm("确定要删除这一页吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let case_item_id = pageData.value[showTab.value].case_item_id;
      if(!case_item_id){
        ElMessage.success("删除成功");
        getDetail(case_id.value);
      }else{
        const { code, data } = await userApi.delCaseItem(case_item_id);
       if (code == 200) {
        ElMessage.success("删除成功");
        getDetail(case_id.value);
       }
      }
     
    })
    .catch((error) => {
      console.log(error);
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
const handleSave = (id) => {
  if (id) {
    handleEdit(id);
  } else {
    handleAdd();
  }
};
const handleEdit = async (id) => {
  let potsData = {
    //content: pageData.value[showTab.value].content,
    is_right_next: pageData.value[showTab.value].is_right_next,
    error_tips: pageData.value[showTab.value].error_tips,
    page: showTab.value + 1,
    case_item_question: pageData.value[showTab.value].case_item_question,
    case_item_model: pageData.value[showTab.value].case_item_model
  };
  const { code, data } = await userApi.updateCaseItem(id, {
    ...caseDetail,
    ...potsData,
  });
  if (code == 200) {
    ElMessage.success("保存成功");
    getDetail(case_id.value,showTab.value);
  } else {
    ElMessage.error(data.message);
  }
};
const handleAdd = async () => {
  let potsData = {
    //content: pageData.value[showTab.value].content,
    is_right_next: pageData.value[showTab.value].is_right_next,
    error_tips: pageData.value[showTab.value].error_tips,
    page: showTab.value + 1,
    case_item_model: pageData.value[showTab.value].case_item_model,
    case_item_question: pageData.value[showTab.value].case_item_question,
  };
  const { code, data } = await userApi.addCaseItem({
    ...caseDetail,
    ...potsData,
  });
  if (code == 200) {
    ElMessage.success("保存成功");
    getDetail(case_id.value,showTab.value);
  } else {
    ElMessage.error(data.message);
  }
};
const addPage = () => {
  const l = treeData.value[0].children.length;
  console.log(treeData.value[0].children);
  treeData.value[0].children.push({
    id: l,
    level: 1,
    label: "第" + page[l] + "页",
    // children: [
    //   {
    //     id: l + 1 + "-" + 0,
    //     parentId: l,
    //     index: 0,
    //     level: 2,
    //     label: "内容",
    //   },
    //   {
    //     id: l + 1 + "-" + 1,
    //     parentId: l,
    //     level: 2,
    //     id: 1,
    //     label: "问题",
    //   },
    //],
  });
  pageData.value.push({
    //content: "",
    case_item_model:[{model_id:'',model_name:"",content:''}],
    case_item_id: "",
    case_id: case_id.value,
    page: page[l],
    case_item_question: [],
  });
  nextTick(() => {
    // if (treeRef.value) {
    // treeRef.value.setCurrentNode([
    //   {
    //     id: l,
    //     level: 1,
    //     label: "第" + page[l] + "页",
    //   },
    // ]);
    //treeRef.value.setCheckedKeys([l], false);

    //}

    handleNodeClick({
      id: l,
      level: 1,
      label: "第" + page[l] + "页",
    });
  });

  console.log(pageData.value);
};
const init = (id) => {
  case_id.value = id;
  getDetail(id);
};
defineExpose({ init });
</script>

<style lang='scss' scoped>
.custom-tree-node .active {
  color: rgb(147 197 253 / 1);
}
.nametitle{
  max-width: 100px;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
 text-overflow: ellipsis;

}
.rowSave {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
.row {
  display: flex;
  .left {
    display: flex;
    flex-direction: column;
  }
  .right {
    margin-left: 100px;
  }
}
</style>
