<template>
  <section class="property-info">
    <!-- 正文信息 -->
    <div class="part-box">
      <h2 class="part-box-title">{{ courseProperty.name }}</h2>
      <!-- <el-form
        class="part-filter-form"
        :inline="true"
        :model="courseProperty"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="课程名称">
          <el-select
            v-model="courseProperty.courseId"
            filterable
            :remote-method="getCourses"
            remote
            clearable
            :disabled="true"
          >
            <el-option
              v-for="item in courseInfoSelect"
              :key="item.courseId"
              :label="item.courseInfo"
              :value="item.courseId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form> -->

      <div class="part-box-action">
        <div class="icon-btn-group">
          <svg-btn name="xinzeng">新增同级</svg-btn>
          <svg-btn name="xinzeng">新增子级</svg-btn>
          <svg-btn name="bianji">编辑</svg-btn>
          <svg-btn name="shanchu">删除</svg-btn>
          <svg-btn name="shangjiantou">上移</svg-btn>
          <svg-btn name="xiajiantou">下移</svg-btn>
        </div>
        <!-- <div>
          <el-button
            type="primary"
            icon="icon icon-plus-white"
            @click="insertParent"
            >新增一级</el-button
          >

          <el-button
            type="primary"
            icon="icon icon-plus-white"
            :disabled="showSonButtton"
            @click="insertSon"
            >新增二级</el-button
          >
          <el-button
            type="primary"
            plain
            icon="icon icon-edit"
            :disabled="showButton"
            @click="updateProperty"
            >编辑</el-button
          >
          <el-button
            type="danger"
            plain
            icon="icon icon-delete"
            :disabled="!multipleSelection.length"
            @click="deleteProperty"
            >删除</el-button
          >
          <el-button
            type="primary"
            plain
            icon="icon icon-import"
            :disabled="showMoveButtton"
            @click="moveUp"
            >上移</el-button
          >
          <el-button
            type="primary"
            plain
            icon="icon icon-export"
            :disabled="showMoveButtton"
            @click="moveDown"
            >下移</el-button
          >
        </div> -->
        <div>
          <el-button type="danger" plain icon="icon icon-back" @click="back"
            >返回</el-button
          >
        </div>
      </div>
    </div>

    <div class="part-box property-box">
      <el-tree
        ref="PropertyTree"
        class="property-tree"
        :data="treeData"
        node-key="id"
        :props="defaultProps"
        :default-expanded-keys="ids"
        highlight-current
        show-checkbox
        :check-strictly="true"
        @node-click="handleNodeClick"
        @check="checkChange"
        ><span
          slot-scope="{ data }"
          :class="{ 'node-level-one': !data.parentId }"
        >
          <span>{{ data.name }}({{ data.code }})</span>
        </span></el-tree
      >
    </div>

    <el-dialog
      :title="title"
      :visible.sync="propertyDialog"
      :modal="true"
      width="620px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      custom-class="side-dialog"
      @close="closeModel"
    >
      <el-form
        ref="propertyForm"
        :model="propertyForm"
        :rules="rules"
        inline-message
        class="form-tight"
        label-width="100px"
      >
        <el-row>
          <el-form-item label="编号" prop="code">
            <el-input
              v-model="propertyForm.code"
              auto-complete="off"
              class="dialog-input-width"
              disabled
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row v-if="isFirstLev()">
          <el-form-item label="一级名称" prop="name">
            <el-input
              v-model="propertyForm.name"
              auto-complete="off"
              class="dialog-input-width"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row v-if="isSecondLev()">
          <el-form-item label="二级名称" prop="name">
            <el-input
              v-model="propertyForm.name"
              auto-complete="off"
              class="dialog-input-width"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="名称备注">
            <el-input
              v-model="propertyForm.remark"
              auto-complete="off"
              :maxlength="100"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button type="danger" plain @click="closeModel">取消</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { QUESTION_API } from "@/constants/constants";
import { mapState } from "vuex";

export default {
  data() {
    return {
      courseProperty: {
        name: "",
        courseId: "",
      },
      courseList: [],
      ids: [],
      loading: false,
      propertyDialog: false,
      propertyForm: {
        id: "",
        code: "",
        name: "",
        parentId: "",
        number: "",
        coursePropertyId: "",
        remark: "",
      },
      curProperty: {
        id: "",
        code: "",
        name: "",
        parentId: "",
        number: "",
        coursePropertyId: "",
        remark: "",
      },
      multipleSelection: [],
      showButton: true,
      showSonButtton: true,
      showMoveButtton: true,
      treeData: [],
      defaultProps: {
        children: "propertyList",
      },
      title: "新增属性",
      rules: {
        code: [
          {
            required: true,
            message: "请输入编码",
            trigger: "blur",
          },
          {
            max: 100,
            message: "编码最多100个字符",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
          {
            max: 100,
            message: "名称最多100个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState({ user: (state) => state.user }),
    courseInfoSelect() {
      var courseList = [];
      for (var i = 0; i < this.courseList.length; i++) {
        var courseInfo = {
          courseInfo:
            this.courseList[i].name + "(" + this.courseList[i].code + ")",
          courseId: this.courseList[i].id,
        };
        courseList.push(courseInfo);
      }
      return courseList;
    },
    IS_ASSIGN_TEACHER() {
      // 命题老师
      return this.user.roleList.some(
        (item) => item.roleCode === "ASSIGN_TEACHER"
      );
    },
  },
  created() {
    // this.coursePropertyId = this.$route.params.id;
    this.courseProperty.courseId = this.$route.params.id;
    this.searchProperty();
  },
  mounted() {
    setTimeout(() => {
      this.$store.commit("UPDATE_CURRENT_PATHS", [
        "课程管理",
        "知识点",
        "属性结构",
      ]);
    }, 200);
  },
  methods: {
    disAllBtn() {
      this.showButton = true;
      this.showSonButtton = true;
      this.showMoveButtton = true;
    },
    isFirstLev() {
      if (this.propertyForm.parentId == "0") {
        return true;
      } else {
        return false;
      }
    },
    isSecondLev() {
      if (this.propertyForm.parentId && this.propertyForm.parentId != "0") {
        return true;
      } else {
        return false;
      }
    },
    closeModel() {
      this.propertyDialog = false;
      this.$refs.propertyForm.resetFields();
    },
    //树形节点选中
    handleNodeClick(object) {
      this.showButton = false;
      //判断选中节点，如果是父节点，可以新增二级
      if (object.parentId == "0") {
        this.showSonButtton = false;
      } else {
        this.showSonButtton = true;
      }
      this.showMoveButtton = false;
      this.curProperty = Object.assign({}, object);
    },
    checkChange(data, { checkedKeys }) {
      const checked = checkedKeys.includes(data.id);

      if (!data.propertyList || !data.propertyList.length) {
        this.multipleSelection = this.$refs.PropertyTree.getCheckedKeys();
        if (checked) return;

        this.multipleSelection = this.multipleSelection.filter(
          (id) => id !== data.parentId
        );
        this.$refs.PropertyTree.setCheckedKeys(this.multipleSelection);
        return;
      }

      let propsIds = [];
      const getPropIds = (propertyList) => {
        if (!propertyList || !propertyList.length) return;
        propertyList.forEach((item) => {
          propsIds.push(item.id);
          if (item.propertyList) getPropIds(item.propertyList);
        });
      };

      if (data.propertyList && data.propertyList.length) {
        getPropIds(data.propertyList);
        if (checked) {
          let checkedKeys = this.$refs.PropertyTree.getCheckedKeys();
          checkedKeys.push(...propsIds);
          const idSet = new Set(checkedKeys);
          this.multipleSelection = Array.from(idSet);
          this.$refs.PropertyTree.setCheckedKeys(this.multipleSelection);
        } else {
          let checkedKeys = this.$refs.PropertyTree.getCheckedKeys();
          this.multipleSelection = checkedKeys.filter(
            (item) => !propsIds.includes(item)
          );
          this.$refs.PropertyTree.setCheckedKeys(this.multipleSelection);
        }
      } else {
        this.multipleSelection = this.$refs.PropertyTree.getCheckedKeys();
      }
    },
    //查询所有课程
    getCourses(query) {
      this.courseList = [];
      if (query) {
        this.courseLoading = true;
        this.$http.get(QUESTION_API + "/course/" + query).then((response) => {
          var courseBean = response.data;
          this.courseList.push(courseBean);
          this.courseProperty.name = courseBean.name;
        });
      } else {
        this.courseList = [];
      }
    },
    //查询
    searchProperty() {
      this.loading = true;
      // var coursePropertyStorge = sessionStorage.getItem("courseProperty");
      // if (typeof coursePropertyStorge == "string") {
      // this.courseProperty = JSON.parse(coursePropertyStorge);
      this.getCourses(this.courseProperty.courseId);
      // }
      // this.$http
      //   .get(QUESTION_API + "/property/all/" + this.coursePropertyId)
      //   .then((response) => {
      //     this.treeData = response.data;
      //     for (var i = 0; i < this.treeData.length; i++) {
      //       var property = this.treeData[i];
      //       this.ids.push(property.id);
      //     }
      //     this.loading = false;
      //   });
      this.$http
        .post(
          QUESTION_API +
            "/property/all/by/course?courseId=" +
            this.$route.params.id
        )
        .then((response) => {
          this.coursePropertyId = response.data.coursePropertyId;
          this.treeData = response.data.propertys;
          for (var i = 0; i < this.treeData.length; i++) {
            var property = this.treeData[i];
            this.ids.push(property.id);
          }
          this.loading = false;
        });
    },
    getPropertyCode(parentId) {
      this.$http
        .post(QUESTION_API + "/property/get_code", {
          rootOrgId: this.user.rootOrgId,
          coursePropertyId: this.coursePropertyId,
          parentId,
        })
        .then((response) => {
          this.propertyForm.code = response.data;
        });
    },
    //新增一级
    insertParent() {
      this.disAllBtn();
      this.title = "新增属性";
      this.propertyForm = {
        id: "",
        code: "",
        name: "",
        parentId: "0",
        number: "",
        coursePropertyId: this.coursePropertyId,
        remark: "",
      };
      this.propertyDialog = true;
      this.getPropertyCode(0);
    },
    //新增二级
    insertSon() {
      this.disAllBtn();
      this.title = "新增属性";
      //父对象id赋值
      this.propertyForm = {
        id: "",
        code: "",
        name: "",
        parentId: this.curProperty.id,
        number: "",
        coursePropertyId: this.coursePropertyId,
        remark: "",
      };
      this.propertyDialog = true;
      this.getPropertyCode(this.curProperty.id);
    },
    //修改
    updateProperty() {
      this.disAllBtn();
      this.title = "修改属性";
      this.propertyForm = Object.assign({}, this.curProperty);
      this.propertyDialog = true;
    },
    //保存
    async submit() {
      const res = await this.$refs.propertyForm.validate();
      if (res === false) {
        return;
      }
      this.$http
        .post(QUESTION_API + "/property/save", this.propertyForm)
        .then(() => {
          this.$notify({
            message: this.propertyForm.id ? "修改成功" : "新增成功",
            type: "success",
          });
          this.propertyDialog = false;
          this.searchProperty();
        })
        .catch((error) => {
          this.$notify({
            type: "error",
            message: error.response.data.desc,
          });
        });
      this.showButton = true;
      this.showSonButtton = true;
    },
    //删除
    async deleteProperty() {
      this.disAllBtn();

      const confirm = await this.$confirm("确认删除属性吗?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") return;

      this.loading = true;
      const res = await this.$http
        .delete(
          QUESTION_API +
            "/property/delete/" +
            this.multipleSelection.join() +
            "/" +
            this.coursePropertyId
        )
        .catch(() => {});
      this.loading = false;
      if (!res) return;

      this.$notify({
        message: "删除成功",
        type: "success",
      });

      this.multipleSelection = [];
      this.searchProperty();
      this.showButton = true;
      this.showSonButtton = true;
    },
    //返回
    back() {
      // this.$router.push({
      //   path: "/questions/course_property/1",
      // });
      this.$router.back();
    },
    //上移
    moveUp() {
      this.disAllBtn();
      this.$http
        .put(QUESTION_API + "/property/moveUp", this.curProperty)
        .then(() => {
          this.searchProperty();
          this.showMoveButtton = true;
        })
        .catch((error) => {
          this.$notify({
            type: "error",
            message: error.response.data.desc,
          });
          this.showMoveButtton = true;
        });
    },
    //下移
    moveDown() {
      this.disAllBtn();
      this.$http
        .put(QUESTION_API + "/property/moveDown", this.curProperty)
        .then(() => {
          this.searchProperty();
          this.showMoveButtton = true;
        })
        .catch((error) => {
          this.$notify({
            type: "error",
            message: error.response.data.desc,
          });
          this.showMoveButtton = true;
        });
    },
  },
};
</script>
