<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      学练宝设置
    </h2>
    <div class="m-core">
      <save-form
        :inline="true"
        class="searchForm"
        save-key="memberSet"
        @submit="search"
        @reset="onReSet"
        :model.sync="searchForm"
      >
        <!-- 状态 指导老师 活动方案-->
        <el-form-item prop="name">
          <el-input
            v-model.trim="searchForm.name"
            clearable
            placeholder="学练宝名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="createTimer">
          <el-date-picker
            v-model.trim="searchForm.createTimer"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="更新开始时间"
            end-placeholder="更新结束时间"
            :picker-options="{ firstDayOfWeek: 1 }"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="updateName">
          <el-input
            v-model.trim="searchForm.updateName"
            clearable
            placeholder="更新人"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
          <el-button native-type="reset" type="primary">重置</el-button>
        </el-form-item>
      </save-form>
      <el-button
        type="primary"
        style="margin-bottom: 20px"
        v-permission="'memberRankSetting/add'"
        @click="addLeave"
        >新增</el-button
      >
      <el-table
        :data="tableList"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="学练宝名称"></el-table-column>

        <el-table-column align="center" prop="intro" label="学练宝介绍">
          <template slot-scope="scope">
            <tooltip :content="scope.row.intro" />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="musicCount"
          label="曲目数量"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="updateTime"
          label="更新时间"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="operatorName"
          label="更新人"
        ></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <div>
              <auth auths="memberRankSetting/get">
                <el-button v-if="scope.row.parentId <= 0" type="text" @click="addLeave(scope.row)"
                  >添加子版本</el-button
                >
              </auth>
              <!-- memberRankSetting/add -->
              <auth auths="memberRankSetting/get">
                <el-button type="text" @click="resetMember(scope.row)"
                  >详情</el-button
                >
              </auth>
              <auth
                :auths="['memberRankSetting/get', 'memberRankSetting/update']"
                mulit
              >
                <el-button type="text" @click="resetMember(scope.row, 'update')"
                  >修改</el-button
                >
              </auth>

              <el-button type="text" @click="removeMember(scope.row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- <pagination
        save-key="memberSet"
        :total.sync="rules.total"
        sync
        :page.sync="rules.page"
        :limit.sync="rules.limit"
        :page-sizes="rules.page_size"
        @pagination="getList"
      /> -->
    </div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="branchStatus"
      v-if="branchStatus"
      default-expand-all
      @close="onFormClose('ruleForm')"
      width="800px"
    >
      <el-form :model="form" :inline="true" ref="ruleForm">
        <el-alert
          title="学练宝信息"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        >
        </el-alert>
        <el-form-item
          label="父级"
          prop="parentName"
          v-if="form.parentId"
          :label-width="formLabelWidth"
        >
          <el-input
            :disabled="true"
            v-model.trim="form.parentName"
            style="width: 620px"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="学练宝名称"
          prop="name"
          :label-width="formLabelWidth"
          :rules="[{ required: true, message: '请输入学练宝名称' }]"
        >
          <el-input
            :disabled="addDisabled"
            v-model.trim="form.name"
            autocomplete="off"
            style="width: 620px"
            maxlength="10"
            show-word-limit
            placeholder="请输入学练宝名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="学练宝介绍"
          prop="intro"
          :label-width="formLabelWidth"
          :rules="[{ required: true, message: '请输入学练宝介绍' }]"
        >
          <el-input
            maxlength="200"
            show-word-limit
            :disabled="addDisabled"
            v-model.trim="form.intro"
            autocomplete="off"
            type="textarea"
            :rows="5"
            style="width: 620px"
            placeholder="请输入学练宝介绍"
          ></el-input>
        </el-form-item>

        <el-alert
          title="学练宝权益"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        >
        </el-alert>
        <el-form-item label="搜索：" :label-width="formLabelWidth">
          <el-input
            style="width: 210px"
            v-model.trim="searchRoleValue"
            placeholder="请输入搜索内容"
          ></el-input>
          <el-button
            style="margin-left: 10px"
            type="danger"
            @click="searchRoles"
            >搜索</el-button
          >
          <el-button type="primary" @click="onReSetRole">重置</el-button>
        </el-form-item>
        <br />
        <el-form-item label="学练宝内容" :label-width="formLabelWidth">
          <el-checkbox
            :disabled="addDisabled || this.buyFlag && pageType === 'update'"
            :indeterminate="isMemberIndeterminate"
            @change="onCheckMemberAll"
            v-model.trim="memberCheckAll"
            >全选</el-checkbox
          >
          <div>
            <el-tree
              class="tree"
              :data="treeMemberData"
              show-checkbox
              node-key="id"
              @check="onTreeMemberCheck"
              :filter-node-method="filterNode"
              ref="memberTrees"
              highlight-current
              :default-checked-keys="memberCheckList"
              :props="defaultProps"
            >
              <div slot-scope="{ node, data }">
                {{ node.label }}
              </div>
            </el-tree>
          </div>
        </el-form-item>

        <el-form-item label="学练宝内容2" :label-width="formLabelWidth">
          <!-- <el-checkbox
            :disabled="addDisabled"
            :indeterminate="isMemberIndeterminate"
            @change="onCheckMemberAll"
            v-model.trim="memberCheckAll"
            >全选</el-checkbox
          > -->
          <div style="padding-top: 5px;">
            <el-tree
              class="tree"
              :data="treeClassData"
              show-checkbox
              node-key="id"
              @check="onTreeClassCheck"
              :filter-node-method="filterNode"
              ref="classTrees"
              highlight-current
              :default-checked-keys="classCheckList"
              :props="defaultProps"
            >
              <div slot-scope="{ node, data }">
                {{ node.label }}
              </div>
            </el-tree>
          </div>
        </el-form-item>

        <el-form-item label="学练宝功能" :label-width="formLabelWidth">
          <el-checkbox
            :disabled="addDisabled || this.buyFlag && pageType === 'update'"
            :indeterminate="isIndeterminate"
            @change="onCheckAll"
            v-model.trim="checkAll"
            >全选</el-checkbox
          >
          <div>
            <el-tree
              class="tree"
              :data="treeData"
              show-checkbox
              node-key="id"
              ref="trees"
              @check="onTreeCheck"
              :filter-node-method="filterNode"
              highlight-current
              :default-checked-keys="checkList"
              :props="defaultProps"
            >
              <div slot-scope="{ node, data }">
                {{ node.label }}
              </div>
            </el-tree>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="!addDisabled" @click="branchStatus = false"
          >取 消</el-button
        >
        <el-button @click="onSubmit" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import Upload from "@/components/Upload/index";
import ImageCropper from "@/components/ImageCropper";
import Tooltip from "@/components/Tooltip/index";
import {
  addMemberRank,
  getmemberRankList,
  getmemberRankDetail,
  resetMemberRank,
  api_memberRankCategoryTree,
  api_memberRankDel
} from "./api";
import { getTimeFormat } from "@/utils";
import { getMemberPrivilegesItem } from "@/views/dictionaryManager/api";
export default {
  components: { pagination, Upload, ImageCropper, Tooltip },
  name: "memberSet",
  data() {
    return {
      formLabelWidth: "120px",
      searchForm: {
        name: null,
        updateName: null,
        createTimer: []
      },
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      tableList: [],
      title: "新增会员等级",
      branchStatus: false,
      form: {
        name: null,
        intro: null,
        memberCategoryIdList: [],
        memberCourseTypeList: [],
        memberPrivilegesItemIdList: []
      },
      buyFlag: false, // 是否购买
      addDisabled: false,
      checkAll: false,
      isIndeterminate: false,
      memberCheckAll: false,
      isMemberIndeterminate: false,
      treeData: [],
      treeMemberData: [],
      treeClassData: [],
      defaultProps: {
        children: "children",
        label: "label",
        disabled: this.addDisabled
      },
      result: {
        roleName: null,
        roleDesc: null
      },
      classList: [],
      classCount: 0,
      memberRankList: [],
      memberRankCount: 0,
      searchRoleValue: "",
      silderList: [],
      slideCount: 0,
      pageType: "",
      allChildIds: [],
      allMemberChildIds: [],
      allClassChildIds: [],
      checkList: [],
      memberCheckList: [],
      classCheckList: [],
      searchName: ""
    };
  },
  async mounted() {
    this.getList();
  },
  methods: {
    onFormClose(ruleForm) {
      this.form = {
        name: "",
        icon: "",
        into: ""
      };
      this.$refs.trees.setCheckedNodes([]);
      this.onTreeCheck();
      this.$refs[ruleForm].resetFields();
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
      this.searchForm = {
        name: null,
        updateName: null,
        createTimer: []
      };
      this.search();
    },
    async getList() {
      try {
        // this.tableList = []
        let { createTimer, ...reset } = this.searchForm;
        const res = await getmemberRankList({
          ...reset,
          ...getTimeFormat(
            createTimer,
            ["updateStartTime", "updateEndTime"],
            "YYYY-MM-DD"
          )
          // rows: this.rules.limit,
          // page: this.rules.page,
        });
        this.tableList = res.data;
        // this.rules.total = res.data.total;
      } catch {}
    },
    async addLeave(row) {
      this.checkList = [];
      this.memberCheckList = [];
      this.classCheckList = [];
      this.isIndeterminate = false;
      this.checkAll = false;
      this.isMemberIndeterminate = false;
      this.memberCheckAll = false;

      this.title = "新增";
      // 添加新增
      this.form.name = null;
      this.form.intro = null;
      if (row) {
        this.form.parentId = row.id;
        this.form.parentName = row.name
      } else {
        this.form.parentId = 0
      }
      
      this.addDisabled = false;
      this.pageType = "create";
      await this.getMemberRankList(this.form.parentId || null);
      this.memberRankCount = 0;
      this.treeMemberData = await this.setMemberTableData(
        this.memberRankList,
        this.addDisabled
      );
      this.classCount = 0;
      this.treeClassData = await this.setMemberTableData(
        this.classList,
        this.addDisabled,
        "class"
      );
      await this.getNewTree(this.form.parentId || null);
      this.slideCount = 0;
      this.treeData = await this.setTableData(
        this.silderList,
        this.addDisabled
      );
      this.branchStatus = true;
    },
    onSubmit() {
      this.$refs.ruleForm.validate(async flag => {
        if (flag) {
          const tempIds = this.$refs.trees.getCheckedKeys();
          const halfIds = this.$refs.trees.getHalfCheckedKeys();
          const allIds = [...tempIds, ...halfIds];

          const memberTempIds = this.$refs.memberTrees.getCheckedKeys();
          const memberHalfIds = this.$refs.memberTrees.getHalfCheckedKeys();
          const memberAllIds = [...memberTempIds, ...memberHalfIds];

          const classTempIds = this.$refs.classTrees.getCheckedKeys();
          const classHalfIds = this.$refs.classTrees.getHalfCheckedKeys();
          const classAllIds = [...classTempIds, ...classHalfIds];
          if (this.pageType == "update") {
            try {
              await resetMemberRank({
                ...this.form,
                memberPrivilegesItemIdList: allIds,
                memberCategoryIdList: memberAllIds,
                memberCourseTypeList: classAllIds
              });
              this.$message.success("修改成功");
              this.branchStatus = false;
              this.getList();
            } catch {}
          } else if (this.pageType == "create") {
            try {
              await addMemberRank({
                ...this.form,
                memberPrivilegesItemIdList: allIds,
                memberCategoryIdList: memberAllIds,
                memberCourseTypeList: classAllIds
              });
              this.$message.success("新建成功");
              this.branchStatus = false;
              this.getList();
            } catch {}
          } else {
            this.branchStatus = false;
          }
        }
      });
    },
    onCheckMemberAll(val) {
      if (val) {
        // 先去掉半选
        this.isMemberIndeterminate = false;
        this.$refs.memberTrees.setCheckedNodes(this.treeMemberData);
      } else {
        this.$refs.memberTrees.setCheckedNodes([]);
      }
    },
    onCheckAll(val) {
      if (val) {
        // 先去掉半选
        this.isIndeterminate = false;
        this.$refs.trees.setCheckedNodes(this.treeData);
      } else {
        this.$refs.trees.setCheckedNodes([]);
      }
    },
    onTreeMemberCheck() {
      let checkTree = this.$refs.memberTrees.getCheckedKeys();
      this.memberCheckAll = checkTree.length >= this.memberRankCount;
      this.isMemberIndeterminate =
        checkTree.length > 0 && checkTree.length < this.memberRankCount;
    },
    onTreeClassCheck() {},
    onTreeCheck() {
      let checkTree = this.$refs.trees.getCheckedKeys();
      this.checkAll = checkTree.length >= this.slideCount;
      this.isIndeterminate =
        checkTree.length > 0 && checkTree.length < this.slideCount;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    searchRoles() {
      this.$refs.memberTrees.filter(this.searchRoleValue);
      this.$refs.classTrees.filter(this.searchRoleValue);
      this.$refs.trees.filter(this.searchRoleValue);
    },
    onReSetRole() {
      this.searchRoleValue = "";
      this.$refs.memberTrees.filter(this.searchRoleValue);
      this.$refs.classTrees.filter(this.searchRoleValue);
      this.$refs.trees.filter(this.searchRoleValue);
    },
    setTableData(result, disabled) {
      let list = [];
      list = result.map(res => {
        let tempList = {};
        tempList = {
          id: res.id,
          name: res.name,
          label: res.name,
          disabled: disabled ? disabled : false
        };
        this.slideCount++;
        if (res.memberPrivilegesItems && res.memberPrivilegesItems.length > 0) {
          tempList.children = this.setTableData(
            res.memberPrivilegesItems,
            disabled
          );
        }
        return tempList;
      });
      return list;
    },
    setMemberTableData(result, disabled, type = "music") {
      let list = [];
      list = result.map(res => {
        let tempList = {};
        tempList = {
          id: res.id,
          name: res.name,
          label: res.name,
          disabled: disabled ? disabled : false
        };
        if (type === "music") {
          this.memberRankCount++;
        } else {
          this.classCount++;
        }
        if (
          res.sysMusicScoreCategoriesList &&
          res.sysMusicScoreCategoriesList.length > 0
        ) {
          tempList.children = this.setMemberTableData(
            res.sysMusicScoreCategoriesList,
            disabled
          );
        }
        return tempList;
      });
      return list;
    },
    removeMember(row) {
      this.$confirm("是否删除该学练宝设置?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await api_memberRankDel({ id: row.id });
          this.$message.success("删除成功");
          this.getList()
        })
        .catch(() => {});
    },
    async resetMember(row, type) {
      this.branchStatus = true;
      await this.resetTree(row);
      let tempStatus = false
      if (type) {
        this.title = "修改";
        this.pageType = "update";
        this.addDisabled = false;
        tempStatus = this.buyFlag
      } else {
        this.addDisabled = true;
        tempStatus = true;
        this.title = "查看";
        this.pageType = "";
      }
      this.slideCount = 0;
      this.treeData = await this.setTableData(
        this.silderList,
        tempStatus
      );

      this.memberRankCount = 0;
      this.treeMemberData = await this.setMemberTableData(
        this.memberRankList,
        tempStatus
      );

      this.classCount = 0;
      this.treeClassData = await this.setMemberTableData(
        this.classList,
        tempStatus,
        "class"
      );
    },
    //递归获取到所有的为子级的ID
    getParent(checkIds, data, type = "tree") {
      let removeIds = JSON.parse(JSON.stringify(checkIds));
      this.getAllChildIds(data, type);
      let tempAllChildIds = [];
      if (type === "tree") {
        tempAllChildIds = this.allChildIds;
      } else if (type === "member") {
        tempAllChildIds = this.allMemberChildIds;
      } else if (type === "class") {
        tempAllChildIds = this.allClassChildIds;
      }
      
      for (let i = checkIds.length; i > 0; i--) {
        if (!tempAllChildIds.includes(Number(checkIds[i - 1]))) {
          removeIds.splice(i - 1, 1);
        }
      }
      return removeIds;
    },
    getAllChildIds(data, type) {
      // 获取所有最子集编号
      data.forEach(item => {
        let temp = [];
        if (item.children && item.children.length > 0) {
          temp = this.getAllChildIds(item.children, type);
        } else {
          if (type === "member") {
            this.allMemberChildIds.push(item.id);
          } else if (type === "class") {
            this.allClassChildIds.push(item.id);
          } else if (type === "tree") {
            this.allChildIds.push(item.id);
          }
        }
      });
    },
    async resetTree(row) {
      try {
        await this.getNewTree(row.parentId || null);
        await this.getMemberRankList(row.parentId || null);
        this.treeMemberData = await this.setMemberTableData(
          this.memberRankList
        );
        this.treeClassData = await this.setMemberTableData(
          this.classList,
          false,
          "class"
        );
        this.treeData = await this.setTableData(this.silderList);
        const { data } = await getmemberRankDetail({
          memberRankSettingId: row.id
        });
        this.buyFlag = data.buyFlag || false
        this.form = { ...data };
        console.log(row.parentId, 'parentId')
        if(row.parentId) {
          this.form.parentId = row.parentId;
          this.form.parentName = row.parentName
        }
        
        this.checkAll =
          data.memberPrivilegesItemIdList?.length >= this.slideCount && data.memberPrivilegesItemIdList?.length > 0 || false;
        // 反写树的值
        this.isIndeterminate =
          data.memberPrivilegesItemIdList?.length > 0 &&
          data.memberPrivilegesItemIdList?.length < this.slideCount;

        this.checkList = data.memberPrivilegesItemIdList;
        let tSplice = this.getParent(
          data.memberPrivilegesItemIdList || [],
          this.treeData
        );
        this.checkList = tSplice;
        this.$nextTick(() => {
          this.$refs.trees.setCheckedKeys(this.checkList);
        });

        this.memberCheckAll = data.memberCategoryIdList?.length >= this.memberRankCount && data.memberCategoryIdList?.length > 0 || false;
        this.isMemberIndeterminate = data.memberCategoryIdList?.length > 0 && data.memberCategoryIdList?.length < this.memberRankCount;
        this.memberCheckList = data.memberCategoryIdList;
        const mSplice = this.getParent(data.memberCategoryIdList || [], this.treeMemberData, 'member')
        this.memberCheckList = mSplice;
        this.$nextTick(() => {
          this.$refs.memberTrees.setCheckedKeys(this.memberCheckList);
        });

        // this.classCheckAll =
        //   data.memberCourseTypeList?.length >= this.memberRankCount || false;
        // this.isClassIndeterminate =
        //   data.memberCourseTypeList?.length > 0 &&
        //   data.memberCourseTypeList?.length < this.memberRankCount;

        this.classCheckList = data.memberCourseTypeList;
        const cSplice = this.getParent(
          data.memberCourseTypeList || [],
          this.treeClassData,
          "class"
        );
        this.classCheckList = cSplice;
        this.$nextTick(() => {
          this.$refs.classTrees.setCheckedKeys(this.classCheckList);
        });
      } catch (e) {
        console.log(e);
      }
    },
    async getNewTree(parentId) {
      try {
        const resTree = await getMemberPrivilegesItem({ parentMemberId: parentId });
        this.silderList = resTree.data;
        this.slideCount = 0;
      } catch {}
    },
    async getMemberRankList(parentId) {
      try {
        const { data } = await api_memberRankCategoryTree({ parentMemberId: parentId });
        this.memberRankList = data.musicScoreCategories || [];
        this.memberRankCount = 0;

        this.classList = data.lessonCategories || [];
        this.classCount = 0;
      } catch {}
    }
  }
};
</script>
<style lang="scss" scoped>
.tree {
  min-width: 630px;
}
</style>
