<template>
  <div>
    <el-alert title="教材信息" :closable="false" class="alert" type="info" />
    <el-form
      :model="form"
      :inline="true"
      label-width="120px"
      class="form"
      ref="form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="教材名称"
            prop="name"
            :rules="[
              {
                required: true,
                message: '请输入教材名称',
                trigger: 'blur',
              },
            ]"
          >
            <el-input v-model="form.name" style="width: 260px"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="适用分部"
            prop="organId"
            :rules="[
              {
                required: true,
                message: '请选择适用分部',
                trigger: 'change',
              },
            ]"
          >
            <select-all
              style="width: 260px"
              v-model.trim="form.organId"
              class="organSelect"
              filterable
              placeholder="请选择分部"
              multiple
              clearable
            >
              <el-option
                v-for="(item, index) in selects.branchs"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </select-all>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item
          label="教材封面图"
          prop="coverImg"
          :rules="[
            {
              required: true,
              message: '请上传教材封面图',
              trigger: 'blur',
            },
          ]"
          label-width="120px"
        >
          <!--      v-show="!form.coverImg"  -->
          <upload
            class="uploadImg"
            v-model="form.coverImg"
            :imageWidthM="210"
            :imageHeightM="268"
            ref="uploadImg"
          ></upload>
          <!-- <img v-show="form.coverImg" :src="form.coverImg" alt="" width="105px" height="134px" @click="uploadImg"/> -->
          <p style="color: red">
            请上传210*268像素，大小2M以内，格式为jpg、png、gif图片
          </p>
        </el-form-item>
      </el-row>
      <el-alert
        title="教材曲目分类"
        :closable="false"
        class="alert"
        type="info"
      />

      <div class="treeWrap">
        <el-button type="primary" @click="addCate" class="addCateBtn"
          >添加分类</el-button
        >
        <el-tree
          :data="form.sysMusicScoreCategoriesList"
          node-key="index"
          default-expand-all
          :expand-on-click-node="false"
          draggable
          accordion
          ref="tree"
          :props="treeProps"
          :allow-drop="allowDrop"
        >
          >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span :class="node.level == 1 ? 'title' : ''">{{
              node.label
            }}</span>
            <span>
              <i class="el-icon-edit" @click="() => editItem(data)"></i>
              <i
                class="el-icon-remove-outline"
                @click="() => removeItem(node, data)"
              ></i>
              <i
                class="el-icon-circle-plus-outline"
                v-if="node.level == 1"
                @click="() => appendItem(data)"
              ></i>
            </span>
          </span>
        </el-tree>
      </div>
    </el-form>
  </div>
</template>
<script>
import Upload from "@/components/Upload/index";
import {
  addsysMusicScore,
  getSysMusicScoreDetail,
  resetsysMusicScore,
} from "../api";
export default {
  props: ["activeRow"],
  components: {
    Upload,
  },
  data() {
    return {
      form: {
        organId: [],
        name: null,
        coverImg: "",
        sysMusicScoreCategoriesList: [],
        delCategoriesIds: [],
      },
      index: 0,
      treeProps: {
        children: "sysMusicScoreCategoriesList",
        label: "name",
      },
    };
  },
  async mounted() {
    await this.$store.dispatch("setBranchs");
    if (this.activeRow?.id) {
      try {
        const res = await getSysMusicScoreDetail({ id: this.activeRow.id });
        this.form.name = res.data.name;
        this.form.organId = res.data.organId.split(",").map((item) => {
          return Number(item);
        });
        this.form.coverImg = res.data.coverImg;
        this.form.sysMusicScoreCategoriesList = this.recursionDate(
          res.data.sysMusicScoreCategoriesList
        )||[];
      } catch (e) {}
    }
  },
  methods: {
    // 递归遍历数组
    recursionDate(arr) {
      // 这里来了
      if (arr.length > 0) {
        let newArr = [];
        for (let i = 0; i < arr.length; i++) {
          let obj = {
            ...arr[i],
            index: arr[i].id,
          };

          if (
            arr[i].sysMusicScoreCategoriesList &&
            arr[i].sysMusicScoreCategoriesList.length > 0
          ) {
            obj.sysMusicScoreCategoriesList = this.recursionDate(
              arr[i].sysMusicScoreCategoriesList
            );
          }

          newArr.push(obj);
        }

        return newArr;
      }
    },
    appendItem(data) {
      this.$prompt("请输入教材名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{1,30}$/,
        inputErrorMessage: "请输入1到15个汉字或字符",
      })
        .then(({ value }) => {
          this.index += 1;
          // this.form.data.push({ index: `xxx${this.index}`, label: value });
          const newChild = {
            index: `xxx${this.index}`,
            name: value,
            sysMusicScoreCategoriesList: [],
          };
          if (!data.sysMusicScoreCategoriesList) {
            this.$set(data, "sysMusicScoreCategoriesList", []);
          }
          data.sysMusicScoreCategoriesList.push(newChild);
        })
        .catch(() => {});
    },
    removeItem(node, data) {
      const parent = node.parent;
      const children = parent.data.sysMusicScoreCategoriesList || parent.data;

      const index = children.findIndex((d) => {
        this.form.delCategoriesIds.push(data.id);
        return d.id === data.id;
      });
      children.splice(index, 1);
      this.form.delCategoriesIds = [...new Set(this.form.delCategoriesIds)];
    },
    editItem(data) {
      this.$prompt("请输入修改的教材曲目名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputValue: data.name,
        inputPattern: /^.{1,30}$/,
        inputErrorMessage: "请输入1到15个汉字或字符",
      })
        .then(({ value }) => {
          data.name = value;
          // this.form.data.push({ index: `xxx${this.index}`, label: value });
        })
        .catch(() => {});
    },
    addCate() {
      this.$prompt("请输入教材曲目名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{1,30}$/,
        inputErrorMessage: "请输入1到15个汉字或字符",
      })
        .then(({ value }) => {
          this.index += 1;
          this.form.sysMusicScoreCategoriesList.push({
            index: `xxx${this.index}`,
            name: value,
          });
        })
        .catch(() => {});
      // this.form.data.push({})
    },
    addSubmit() {
      this.$refs.form.validate(async (flag) => {
        if (flag) {
          let { organId, delCategoriesIds, ...rest } = this.form;
          let obj = {
            ...rest,
            organId: organId.join(","),
            delCategoriesIds: delCategoriesIds.join(","),
          };
          try {
            if (this.activeRow?.id) {
              obj.id = this.activeRow.id;
              const resut = await resetsysMusicScore(obj);
              this.$message.success("修改成功");
              this.$emit("getList");
              this.$emit("close");
            } else {
              const resut = await addsysMusicScore(obj);
              this.$message.success("添加成功");
              this.$emit("getList");
              this.$emit("close");
            }
          } catch (e) {
            console.log(e);
          }
        }
      });
    },
    uploadImg() {
      this.$refs.uploadImg.$refs.upload.submit();
    },
    allowDrop(draggingNode, dropNode, type) {
      let flag = true
      // console.log(type, dropNode, draggingNode);
      if (draggingNode.childNodes.length > 0 && type == "inner") {
        flag = false;
      } else {
        if (dropNode.level != 1&& type == "inner") {
         flag = false;
        }
      }
      return flag
    },
  },
  computed: {},
};
</script>
<style lang="scss" scoped>
.alert {
  margin-bottom: 20px;
}
.form {
  /deep/.el-form-item {
    margin-right: 0 !important;
  }
}
.addCateBtn {
  margin-bottom: 20px;
}

.custom-tree-node {
  .title {
    font-size: 16px;
  }
  font-size: 14px;
  i {
    // font-size: 20px;
    margin-left: 5px;
  }
}
.uploadImg {
  /deep/.avatar {
    width: 105px;
    height: 134px;
  }
}
</style>
