<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      教材列表
    </h2>
    <div class="m-core">
      <save-form
        :inline="true"
        :model="searchForm"
        @submit="search"
        @reset="onReSet"
        ref="searchForm"
      >
        <el-form-item prop="search">
          <el-input
            v-model.trim="searchForm.search"
            clearable
            @keyup.enter.native="search"
            placeholder="教材编号、名称"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item prop="organId">
          <el-select
            class="multiple"
            v-model.trim="searchForm.organId"
            filterable
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item prop="enable">
          <el-select
            v-model.trim="searchForm.enable"
            placeholder="教材状态"
            clearable
          >
            <el-option label="启用" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="primary">搜索</el-button>
          <el-button native-type="reset" type="danger">重置</el-button>
        </el-form-item>
      </save-form>
      <div class="btnList">
        <auth auths="sysMusicScoreCategories/save">
          <el-button type="primary" @click="operationTeachClass('create')">新增教材</el-button>
        </auth>
      </div>
      <div class="tableWrap">
        <el-table
          style="width: 100%"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :data="tableList"
          row-key="id"
          :expand-row-keys="expands"
          :tree-props="{children: 'sysMusicScoreCategoriesList', hasChildren: 'hasChildren'}"
        >
          <!-- <el-table-column
            align="center"
            prop="id"
            label="教材编号"
          ></el-table-column> -->
          <el-table-column
            align="left"
            prop="name"
            label="教材名称"
          >
            <template slot-scope="scope">
              {{ scope.row.name }}({{ scope.row.id }})
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" prop="organNames" label="可见分部">
            <template slot-scope="scope">
              <div>
                <overflow-text :text="scope.row.organNames"></overflow-text>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column
            align="center"
            prop="musicScoreNum"
            label="曲目数量"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="musicScoreNum"
            label="使用音源"
          >
            <template slot-scope="scope">
              {{ scope.row.soundResource | formatSoundReSource }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="updateTime"
            label="最后更新时间"
          ></el-table-column>
          <el-table-column align="center" prop="studentId" label="教材状态">
            <template slot-scope="scope">
              <div>
                {{ scope.row.enable ? "启用" : "停用" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="studentId" label="操作">
            <template slot-scope="scope">
              <div>
                <auth auths="/accompaniment">
                  <el-button type="text" @click="lookMusic(scope.row)"
                    >查看</el-button
                  >
                </auth>
                <auth auths="sysMusicScoreCategories/update">
                  <el-button
                    type="text"
                    @click="operationTeachClass('create', scope.row)"
                    v-if="!scope.row.enable && formatParentId(scope.row.id, tableList).length < 4"
                    >添加</el-button
                  >
                </auth>
                <auth auths="sysMusicScoreCategories/update">
                  <el-button
                    type="text"
                    @click="operationTeachClass('update', scope.row)"
                    v-if="!scope.row.enable"
                    >修改</el-button
                  >
                </auth>
                <auth auths="sysMusicScoreCategories/enable">
                  <el-button
                    type="text"
                    v-if="scope.row.enable"
                    @click="stopTeach(scope.row)"
                    >停用</el-button
                  >
                  <el-button
                    type="text"
                    v-if="!scope.row.enable"
                    @click="stopTeach(scope.row)"
                    >启用</el-button
                  >
                </auth>
                <auth auths="sysMusicScoreCategories/delete">
                  <el-button
                    type="text"
                    v-if="!scope.row.enable"
                    @click="removeTeach(scope.row)"
                    >删除</el-button
                  >
                </auth>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- <pagination
          sync
          :total.sync="rules.total"
          :page.sync="rules.page"
          :limit.sync="rules.limit"
          :page-sizes="rules.page_size"
          @pagination="getList"
        /> -->
      </div>
    </div>

    <el-dialog
      :title="type == 'create' ? '新增教材' : '修改教材'"
      :visible.sync="teachClassVisible"
      width="600px"
      v-if="teachClassVisible"
    >
      <teachClass
        @close="teachClassVisible = false"
        @getList="getList"
        ref="teachClass"
        :type="type"
        v-if="teachClassVisible"
        :activeRow="activeRow"
      />
    </el-dialog>

  </div>
</template>

<script>
import pagination from "@/components/Pagination/index";
import teachClass from "./modals/addRoot";
import { queryTree } from '../accompaniment/api'
import {
  getSysMusicScoreList,
  enableSysMusicScore,
  removeSysMusicScore,
} from "./api";
export default {
  components: { pagination, teachClass },
  data() {
    return {
      searchForm: {
        search: null,
        enable: null,
        organId: null,
      },
      tableList: [],
      organList: [],
      activeRow: null,
      type: 'create',
      teachClassVisible: false,
      expands: []
    };
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // 获取分部
     this.$store.dispatch("setBranchs");
    this.getList();
  },
  filters: {
    formatSoundReSource(val) {
      let template = {
        NOTEPERFORMER: 'NotePerformer音源',
        TANG: '标准音源',
        OFFICIAL: '官方音源'
      }
      return template[val]
    }
  },
  methods: {
    async getList() {
      let {...rest} =  this.searchForm
      try {
        const res = await queryTree({
          // organId:organId.join(','),
         ...rest
        });
        console.log(res)
        this.tableList = res.data;
      } catch (e) {}
    },
    search() {
      this.getList();
    },
    onReSet() {
      this.$refs.searchForm.resetFields();
      this.search();
    },
    operationTeachClass(type, row) {
      this.type = type
      let level = 0
      if(row) {
        console.log(row.id, 'id')
        let tempArr = this.formatParentId(row.id, this.tableList)
        console.log(tempArr.indexOf(row.id))
        level = tempArr.indexOf(row.id)
        console.log(row, row.id, this.formatParentId(row.id, this.tableList), 'tableList')
        row.level = level
      }
      this.activeRow = row || null;
      this.teachClassVisible = true;
    },
    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;
    },
    async stopTeach(row) {
      let str = "";
      if (row.enable) {
        str = `是否停用${row.name}该教材`;
      } else {
        str = `是否启用${row.name}该教材`;
      }
      this.$confirm(str, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await enableSysMusicScore({ categoriesId: row.id });
            if (row.enable) {
              this.$message.success("停用成功");
            } else {
              this.$message.success("启用成功");
            }

            this.getList();
          } catch (e) {
            console.log(e);
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    async removeTeach(row) {
      this.$confirm(`是否删除${row.name}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await removeSysMusicScore({ id: row.id });
            this.$message.success("删除成功");
            this.getList();
          } catch (e) {
            console.log(e);
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    lookMusic(row) {
      this.$router.push({
        name: "accompaniment",
        params: { categoriesId: row.id },
      });
    },
  },
};
</script>
<style lang='scss' scoped>
.btnList {
  margin-bottom: 20px;
}
</style>
