<template>
  <div>
    <el-alert title="教材信息" :closable="false" class="alert" type="info" />
    <el-form :model="form" label-width="120px" class="form" ref="form">
      <el-form-item
        label="教材名称"
        prop="name"
        :rules="[
          {
            required: true,
            message: '请输入教材名称',
            trigger: 'blur',
          },
        ]"
      >
        <el-input
          v-model="form.name"
          placeholder="请输入教材名称"
          style="width: 100%"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="音源设置"
        prop="soundResource"
        v-if="level <= 1 && level == 1 && type != 'create'"
        :rules="[
          {
            required: true,
            message: '请选择音源设置',
            trigger: 'change',
          },
        ]"
      >
        <el-select
          filterable
          placeholder="请选择音源设置"
          clearable
          v-model="form.soundResource"
          style="width: 100% !important"
        >
          <el-option label="NotePerformer音源" value="NOTEPERFORMER"></el-option>
          <el-option label="标准音源" value="TANG"></el-option>
          <el-option label="官方音源" value="OFFICIAL"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="教材封面图"
        prop="coverImg"
        :rules="[
          {
            required: level > 1 ? false : true,
            message: '请上传教材封面图',
            trigger: 'blur',
          },
        ]"
        label-width="120px"
      >
        <!-- <upload
          :class="[imageWidthM == 350 ? 'uploadImg' : 'uploadSmallImg']"
          v-model="form.coverImg"
          :imageWidthM="imageWidthM"
          :imageHeightM="imageHeightM"
          ref="uploadImg"
        ></upload> -->
        <image-cropper
          :options="cropperOptions"
          bucket_name="cloud-coach"
          :imgSize="2"
          :imageUrl="form.coverImg"
          showSize
          @crop-upload-success="cropSuccess"
        />
        <p style="color: red">大小2M以内，格式为jpg、png、gif图片</p>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$listeners.close()">取 消</el-button>
      <el-button type="primary" @click="addSubmit">确 定</el-button>
    </span>
  </div>
</template>
<script>
import Upload from "@/components/Upload/index";
import ImageCropper from "@/components/ImageCropper";
import { addsysMusicScore, getSysMusicScoreDetail, resetsysMusicScore } from "../api";
export default {
  props: ["type", "activeRow"],
  components: {
    Upload,
    ImageCropper,
  },
  data() {
    return {
      imageWidthM: 350,
      imageHeightM: 140,
      form: {
        organId: [],
        name: null,
        coverImg: "",
        soundResource: null,
        sysMusicScoreCategoriesList: [],
        // delCategoriesIds: [],
      },
      index: 0,
      treeProps: {
        children: "sysMusicScoreCategoriesList",
        label: "name",
      },
      level: 0, // 当前添加或修改第几层
      cropperOptions: {
        autoCrop: true, //是否默认生成截图框
        autoCropWidth: 350, //默认生成截图框宽度
        autoCropHeight: 140, //默认生成截图框高度
        fixedBox: true, //是否固定截图框大小 不允许改变
        previewsCircle: false, //预览图是否是圆形
        full: true, // 是否输出原图比例的截图
        enlarge: 2,
        title: "教材封面图", //模态框上显示的标题
      },
    };
  },
  async mounted() {
    await this.$store.dispatch("setBranchs");
    if (this.activeRow?.id) {
      // 判断是否是根元素处理
      if (this.activeRow?.parentId != 0 || this.type == "create") {
        // this.imageWidthM = 210
        // this.imageHeightM = 268
        this.cropperOptions.autoCropWidth = 210;
        this.cropperOptions.autoCropHeight = 268;
      }
      console.log(this.activeRow, "level");
      this.level = this.activeRow?.level || 0;
      try {
        const res = await getSysMusicScoreDetail({ id: this.activeRow.id });
        if (this.type == "create") {
          // 添加一级分类或子级
          this.form.organId = res.data.organId.split(",").map((item) => {
            return Number(item);
          });
        } else if (this.type == "update") {
          // 修改分类
          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.soundResource = res.data.soundResource;
        }
      } catch (e) {}
    }
  },
  methods: {
    formatParentId(id, list, ids = []) {
      for (const item of list) {
        if (item.sysMusicScoreCategoriesList) {
          const cIds = this.formatParentId(id, item.sysMusicScoreCategoriesList, [
            ...ids,
            item.id,
          ]);
          if (cIds.includes(id)) {
            return cIds;
          }
        }
        if (item.id === id) {
          return [...ids, id];
        }
      }
      return ids;
    },
    addSubmit() {
      this.$refs.form.validate(async (flag) => {
        if (flag) {
          let { organId, ...rest } = this.form;
          let parentId = 0;
          if (this.type == "create") {
            parentId = this.activeRow?.id || 0;
          } else if (this.type == "update") {
            parentId = this.activeRow?.parentId || 0;
          }
          let obj = {
            ...rest,
            parentId,
            organId: organId.join(","),
          };
          try {
            if (this.type == "update") {
              obj.id = this.activeRow?.id;
              await resetsysMusicScore(obj);
              this.$message.success("修改成功");
              this.$emit("getList");
              this.$emit("close");
            } else {
              await addsysMusicScore(obj);
              this.$message.success("添加成功");
              this.$emit("getList");
              this.$emit("close");
            }
          } catch (e) {
            console.log(e);
          }
        }
      });
    },
    uploadImg() {
      this.$refs.uploadImg.$refs.upload.submit();
    },
    //上传操作结束
    cropClose() {
      console.log("上传操作结束");
    },
    //上传图片成功
    cropSuccess(data) {
      // this.imgUrl = data.data.avatar
      this.form.coverImg = data.data.url;
      console.log(this.form.coverImg);
    },
  },
  computed: {},
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  display: block;
  text-align: right;
}
.alert {
  margin-bottom: 20px;
}
.form {
  ::v-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 {
  ::v-deep .avatar {
    width: 350px;
    height: 140px;
  }
}
.uploadSmallImg {
  ::v-deep .avatar {
    width: 105px;
    height: 134px;
  }
}
</style>
