<template>
  <div id="chapterContent">
    <ul class="fatherSty">
      <li class="floatLefts" v-for="(item, index) in headerData" :key="index">
        {{ item.label }}：{{
          item.scope === "more"
            ? pageInfo[item.prop1] + "-" + pageInfo[item.prop2]
            : pageInfo[item.prop]
        }}
      </li>
      <div style="clear: both"></div>
    </ul>
    <div class="mar_b">
      <el-button slot="reference" type="success" @click="openBoxs"
        >添加 模块/章节</el-button
      >
    </div>
    <!-- <el-table
      :data="tableDataInfos"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="标题"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            @click="del(scope.$index, scope.row)"
            v-if="scope.row.isDels"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table> -->
    <el-tree
      ref="tree"
      :data="tableDataInfos"
      lazy
      :load="load"
      :props="layoutTreeProps"
      @node-click="handleNodeClick"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span v-if="data.isDels">
          <el-button type="text" size="mini" @click.stop="del(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <div class="dis-f">
      <el-button @click="backPage">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
    <el-dialog
      title="添加模块/章/节"
      :visible.sync="centerDialogVisible"
      width="28%"
      center
    >
      <el-radio-group v-model="radio" class="dis-f">
        <el-radio :label="1">模板</el-radio>
        <el-radio :label="2">章</el-radio>
        <el-radio :label="3">节</el-radio>
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false" size="small"
          >取 消</el-button
        >
        <el-button type="primary" @click="activeCheckBoxs" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      :title="radio === 1 ? '添加模块' : radio === 2 ? '添加章' : '添加节'"
      :visible.sync="dialogVisible"
      width="800px"
    >
      <el-table
        ref="multipleTable"
        :data="boxtableData"
        border
        @select-all="selectAll"
        @select="select"
        :row-key="getRowKeys"
        :header-cell-style="{
          'background-color': '#eee',
          padding: '8px',
          color: '#333',
        }"
      >
        <el-table-column
          align="center"
          type="selection"
          width="55"
          header-align="center"
          :selectable="checkboxT"
          :reserve-selection="true"
        >
        </el-table-column>
        <template v-for="(item, index) in tableSet">
          <el-table-column
            :width="item.width"
            :key="index"
            :label="item.label"
            align="center"
            :show-overflow-tooltip="true"
            header-align="center"
          >
            <template slot-scope="scope">
              <span v-if="item.scope === 'Status'">
                {{
                  scope.row[item.prop] === 1
                    ? "发布"
                    : scope.row[item.prop] === 0
                    ? "未发布"
                    : "未知"
                }}
              </span>
              <span v-else-if="item.scope === 'teshu'">
                {{ radio === 1 ? scope.row[item.prop] : scope.row[item.prop1] }}
              </span>
              <span v-else>{{ scope.row[item.prop] }}</span></template
            >
          </el-table-column></template
        >
      </el-table>
      <pagination
        :total="total"
        :pageSize="pageSize"
        :currentPage="currentPage"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pagination from "@/components/pagination";
export default {
  components: { pagination },
  data() {
    return {
      centerDialogVisible: false,
      radio: "",
      headerData: [
        {
          label: "课程名称",
          prop: "courseName",
        },
        {
          label: "业务层次",
          prop1: "projectName",
          prop2: "businessName",
          scope: "more",
        },
        {
          label: "所属院校",
          prop: "schoolName",
        },
        {
          label: "所属专业",
          prop: "categoryName",
        },
        {
          label: "科目",
          prop: "subjectName",
        },
      ],
      pageInfo: {},
      tableData: [
        // {
        //   courseId: 19,
        //   menuId: 1,
        //   parentId: 0,
        //   status: 1,
        //   type: 1,
        // },
        // {
        //   courseId: 19,
        //   menuId: 16,
        //   parentId: 0,
        //   status: 1,
        //   type: 2,
        // },
        // {
        //   courseId: 19,
        //   menuId: 16,
        //   parentId: 0,
        //   status: 1,
        //   type: 3,
        // },
      ],
      tableDataInfos: [],
      tableSet: [
        { label: "编码", prop: "code" },
        { label: "标题前缀", prop: "prefixName", width: "120" },
        { label: "标题", prop: "moduleName", prop1: "name", scope: "teshu" },
        {
          label: "发布状态",
          prop: "publishStatus",
          scope: "Status",
          width: "120",
        },
      ],
      dialogVisible: false,
      boxtableData: [],
      activeLists: [],
      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码
      theModuleList: [],
      theChapterList: [],
      theSectionList: [],
      layoutTreeProps: {
        label(data, node) {
          return data.name;
        },
        isLeaf(data, node) {
          return data.hasChildren ? false : true;
        },
      },
    };
  },
  mounted() {
    this.getDs();
    this.search();
  },
  methods: {
    search() {
      this.$api.obtainCourseS(this.$route.query.id).then((res) => {
        this.pageInfo = res.data;
      });
      this.$api
        .inquireCoursemenuListS({ courseId: this.$route.query.id })
        .then((res) => {
          this.tableData = res.rows;
          this.changeApis();
        });
    },
    getDs() {
      this.$api.inquireCourseListmodule({ status: 1 }).then((res) => {
        this.theModuleList = res.rows;
      });
      this.$api.inquireCourseListchapter({ status: 1 }).then((res) => {
        this.theChapterList = res.rows;
      });
      this.$api.inquireCourseSection({ status: 1 }).then((res) => {
        this.theSectionList = res.rows;
      });
    },
    openBoxs() {
      this.radio = "";
      this.centerDialogVisible = true;
    },
    activeCheckBoxs() {
      var self = this;
      if (this.radio === 1) {
        this.moduleApi();
      }
      if (this.radio === 2) {
        this.chapterApi();
      }
      if (this.radio === 3) {
        this.sectionApi();
      }
      if (this.radio === "") {
        this.$message.error("请选择添加类型");
        return;
      }
      this.centerDialogVisible = false;
      this.dialogVisible = true;
      this.$nextTick(function () {
        self.$refs.multipleTable.clearSelection();
      });
    },
    getInfos() {
      if (this.radio === 1) {
        this.moduleApi();
      }
      if (this.radio === 2) {
        this.chapterApi();
      }
      if (this.radio === 3) {
        this.sectionApi();
      }
    },
    moduleApi() {
      this.$api
        .inquireCourseListmodule({
          status: 1,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
        })
        .then((res) => {
          this.boxtableData = res.rows;
          this.total = res.total;
        });
    },
    chapterApi() {
      this.$api
        .inquireCourseListchapter({
          status: 1,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
        })
        .then((res) => {
          this.boxtableData = res.rows;
          this.total = res.total;
        });
    },
    sectionApi() {
      this.$api
        .inquireCourseSection({
          status: 1,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
        })
        .then((res) => {
          this.boxtableData = res.rows;
          this.total = res.total;
        });
    },
    // 查询是否存在下级 模块
    quireModule(id) {
      return new Promise((resolve, reject) => {
        this.$api.inquireCourseListmodulechapter(id).then((result) => {
          if (result.data.length === 0) {
            resolve(false);
          } else {
            resolve(true);
          }
        });
      });
    },
    // 查询是否存在下级 章
    quireChapter(id) {
      return new Promise((resolve, reject) => {
        this.$api.inquireCoursechaptersectionlist(id).then((result) => {
          if (result.data.length === 0) {
            resolve(false);
          } else {
            resolve(true);
          }
        });
      });
    },
    changeApis() {
      //inquireCourseListmodulechapter 模块与章关系
      // inquireCoursechaptersectionlist 章与节关系
      var arrays = [];
      this.tableData.map((item, index) => {
        if (item.type === 1) {
          // this.$api.obtainCoursemodule(item.menuId).then(async (res) => {
          var arr = {
            id: "1-" + item.menuId,
            CodeId: item.menuId,
            name: item.menuName,
            hasChildren: true,
            type: 1,
            isDels: true,
          };
          //查询是否存在下级
          arrays.push(arr);
          // });
        }
        if (item.type === 2) {
          // this.$api.obtainCoursechapter(item.menuId).then(async (res) => {
          var arr = {
            id: "2-" + item.menuId,
            CodeId: item.menuId,
            name: item.menuName,
            hasChildren: true,
            type: 2,
            isDels: true,
          };
          arrays.push(arr);
          // });
        }
        if (item.type === 3) {
          // this.$api.obtainCourseSection(item.menuId).then((res) => {
          var arr = {
            id: "3-" + item.menuId,
            CodeId: item.menuId,
            name: item.menuName,
            hasChildren: false,
            type: 3,
            isDels: true,
          };
          arrays.push(arr);
          // });
        }
      });
      this.$nextTick(() => {
        this.tableDataInfos = arrays;
      });
    },
    del(node, item) {
      this.tableDataInfos.map((items, indexs) => {
        if (items.id === item.id) {
          this.tableDataInfos.splice(indexs, 1);
        }
      });
      this.tableDataInfos = JSON.parse(JSON.stringify(this.tableDataInfos))
    },
    getRowKeys(row) {
      if (this.radio === 1) {
        return row.moduleId;
      }
      if (this.radio === 2) {
        return row.chapterId;
      }
      if (this.radio === 3) {
        return row.sectionId;
      }
    },
    checkboxT(row, index) {
      var array = [];
      this.tableDataInfos.map((item) => {
        if (item.type === this.radio) {
          array.push(item.CodeId);
        }
      });
      if (
        array.indexOf(
          this.radio === 1
            ? row.moduleId
            : this.radio === 2
            ? row.chapterId
            : row.sectionId
        ) !== -1
      ) {
        return false;
      } else {
        return true;
      }
    },
    submitForm() {
      if (this.activeLists.length === 0) {
        this.dialogVisible = false;
        return;
      }
      var array = [];
      if (this.radio === 1) {
        this.activeLists.map((item) => {
          array.push({
            id: 1 + "-" + item.moduleId,
            CodeId: item.moduleId,
            name: item.moduleName,
            isDels: true,
            hasChildren: true,
            type: 1,
          });
        });
      } else if (this.radio === 2) {
        this.activeLists.map((item) => {
          array.push({
            id: 2 + "-" + item.chapterId,
            CodeId: item.chapterId,
            name: item.name,
            isDels: true,
            hasChildren: true,
            type: 2,
          });
        });
      } else if (this.radio === 3) {
        this.activeLists.map((item) => {
          array.push({
            id: 3 + "-" + item.sectionId,
            CodeId: item.sectionId,
            name: item.name,
            type: 3,
            isDels: true,
          });
        });
      }
      this.tableDataInfos = this.tableDataInfos.concat(array);
      this.activeLists = [];
      this.dialogVisible = false;
      this.$message.success("添加成功");
    },
    handleNodeClick() {},
    async load(node, resolve) {
      const tree = node.data;
      if (tree.type === 1) {
        var arrays = [];
        await this.$api
          .inquireCourseListmodulechapter(tree.CodeId)
          .then((res) => {
            res.data.map((item, index) => {
              var arr = {
                id: tree.id + "-" + item.chapterId,
                CodeId: item.chapterId,
                name: item.name,
                hasChildren: true,
                type: 2,
              };
              arrays.push(arr);
            });
          });
        resolve(arrays);
      }
      if (tree.type === 2) {
        this.$api.inquireCoursechaptersectionlist(tree.CodeId).then((res) => {
          var arrays = [];
          res.data.map((item, index) => {
            var arr = {
              id: tree.id + "-" + item.sectionId,
              CodeId: item.sectionId,
              name: item.name,
              type: 3,
            };
            arrays.push(arr);
          });
          resolve(arrays);
        });
      }
      return;
      if (tree.type === 1) {
        var arrays = [];
        await this.$api
          .inquireCourseListmodulechapter(tree.CodeId)
          .then((res) => {
            res.data.map((item, index) => {
              var arr = {
                id: tree.id + "-" + item.chapterId,
                CodeId: item.chapterId,
                name: item.name,
                hasChildren: true,
                type: 2,
              };
              arrays.push(arr);
            });
          });
        resolve(arrays);
      }
      if (tree.type === 2) {
        this.$api.inquireCoursechaptersectionlist(tree.CodeId).then((res) => {
          var arrays = [];
          res.data.map((item, index) => {
            var arr = {
              id: tree.id + "-" + item.sectionId,
              CodeId: item.sectionId,
              name: item.name,
              type: 3,
            };
            arrays.push(arr);
          });
          resolve(arrays);
        });
      }
    },
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;
      this.getInfos();
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.getInfos();
    },
    selectAll(value) {
      this.activeLists = value;
    },
    select(value) {
      this.activeLists = value;
    },
    backPage() {
      this.$router.go(-1);
    },
    submit() {
      var array = [];
      this.tableDataInfos.map((item) => {
        array.push({
          courseId: Number(this.$route.query.id),
          menuId: item.CodeId,
          parentId: 0,
          status: 1,
          type: item.type,
        });
      });
      var data = {
        courseId: Number(this.$route.query.id),
        menuList: array,
      };
      this.$api.editCoursemenu(data).then((res) => {
        this.$message.success("编辑成功");
        setTimeout(() => {
          this.$router.go(-1);
        }, 500);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.fatherSty {
  background-color: #eee;
  padding: 10px;
  margin-bottom: 15px;
}
.floatLefts {
  font-size: 14px;
  float: left;
  margin-right: 30px;
}
.mar_b {
  margin-bottom: 12px;
}
.dis-f {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
/deep/.el-tree-node__content {
  height: 35px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}
</style>
