<template>
  <div id="moduleManagementAdd">
    <el-form
      label-position="right"
      label-width="120px"
      :model="listData"
      :rules="rules"
      ref="listData"
    >
      <div class="boxWidth">
        <el-form-item label="适用业务层级" required>
          <el-select
            v-model="eduType"
            placeholder="请选择教育类型"
            @change="changeEduType"
          >
            <el-option
              v-for="(item, index) in eduTypeOptions"
              :key="index"
              :label="item.educationName"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="courType"
            placeholder="请选择业务层次"
            @change="changecourseType"
          >
            <el-option
              v-for="(item, index) in newCourTypeOptions"
              :key="index"
              :label="item.projectName + '-' + item.businessName"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-popover
            ref="popovers"
            placement="bottom"
            trigger="click"
            @show="showHandle"
            @hide="hideHandle"
            :disabled="courType ? false : true"
            ><el-checkbox
              v-model="checkAll"
              @change="handleCheckAllChange"
              :indeterminate="isIndeterminate"
              >全选</el-checkbox
            >
            <el-checkbox-group
              v-model="sujectArray"
              class="checkboxSty"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="(item, index) in newSujectOption"
                :label="item.newId"
                :key="index"
                >{{ item.subjectName }}</el-checkbox
              >
            </el-checkbox-group>
            <div style="display: block; text-align: center; margin-top: 10px">
              <el-button size="mini" type="primary" @click="submitSujectArray"
                >确定</el-button
              >
            </div>
            <el-button
              slot="reference"
              style="margin-left: 12px"
              @click="getMessage"
              >请选择科目</el-button
            >
          </el-popover>
          <span style="margin-left: 10px">注：可多选</span>
        </el-form-item>
        <el-form-item label="">
          <div :class="changeHeight ? 'ach' : 'clh'">
            <div
              v-for="(item, index) in newSujectApis"
              :key="index"
              class="listBoxStys"
            >
              {{
                item.educationName +
                " - " +
                item.projectName +
                " - " +
                item.businessName +
                " - " +
                item.subjectName
              }}
              <i class="el-icon-error closeIcons" @click="closeType(index)"></i>
            </div>
          </div>
          <el-popover
            placement="bottom-start"
            trigger="hover"
            :close-delay="50"
          >
            <ul style="margin: 0; max-width: 600px">
              <li
                class="copyDataLi"
                :class="changeSty(itemT)"
                v-for="(itemT, indexT) in localData"
                :key="indexT"
                @click="unTime(itemT)"
              >
                {{
                  `${itemT.educationName}-${itemT.projectName}-${itemT.businessName}-${itemT.subjectName}`
                }}
              </li>
            </ul>
            <el-button
              v-show="localData.length"
              type="danger"
              slot="reference"
              size="mini"
              style="margin-right: 10px"
              >最近选择</el-button
            >
          </el-popover>
          <el-button
            size="mini"
            v-if="newSujectApis.length > 1"
            @click="changeType"
            >{{ changeHeight ? "展开" : "关闭" }}</el-button
          ><el-button
            size="mini"
            v-if="newSujectApis.length > 0"
            @click="sujectApis = []"
            >清空</el-button
          >
        </el-form-item>
        <el-form-item label="标题前缀" prop="prefixName">
          <el-input v-model="listData.prefixName"></el-input>
          <div style="color: #999">注：便于检索、归类，以及区分一样的标题</div>
        </el-form-item>
        <el-form-item label="模块标题" prop="moduleName">
          <el-input v-model="listData.moduleName"></el-input>
          <div style="color: #999">
            注：请尽量规范易懂，方便在课程目录表呈现给学员
          </div>
        </el-form-item>

        <el-form-item label="模块封面">
          <el-row :gutter="10" style="margin-bottom: 10px">
            <el-col :span="12">
              <div
                style="
                  width: 100%;
                  height: 150px;
                  border: 2px dashed #999;
                  border-radius: 28px;
                  line-height: 150px;
                  text-align: center;
                "
                v-if="!listData.coverUrl"
              >
                <label for="uplose">
                  <i class="el-icon-circle-plus-outline iconStsz"></i
                ></label>
                <input
                  ref="file"
                  type="file"
                  style="display: none"
                  id="uplose"
                  @change="getImgFile"
                />
              </div>
              <el-image
                v-else
                style="width: 100%"
                :src="$methodsTools.splitImgHost(listData.coverUrl)"
                :preview-src-list="[
                  $methodsTools.splitImgHost(listData.coverUrl),
                ]"
              >
              </el-image>
            </el-col>
            <el-col :span="11">
              <span style="color: #999; font-size: 14px"
                >注：请上传小于300kb，尺寸为750*440的图片，支持gif、jpg、jpeg、png等类型</span
              >
            </el-col>
          </el-row>
          <el-button
            v-if="listData.coverUrl"
            type="danger"
            size="mini"
            class="margin-top: 20px;"
            @click="clearImgs"
            >删除</el-button
          >
        </el-form-item>
        <el-form-item label="是否发布" prop="publishStatus">
          <el-radio-group v-model="listData.publishStatus">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <el-form-item label="管理章">
        <div class="dis_plays">
          <div>
            <el-button size="small" @click="openBoxs">调用已有数据</el-button>
            <el-button size="small" type="success" @click="dialogDRFunc"
              >Excel批量新增章</el-button
            >
            <el-button size="small" @click="addChapter">自定义添加章</el-button>
          </div>
          <div style="color: #f56c6c">
            <span style="margin-right: 10px"
              >章总数：{{ tableData.length }}</span
            >
            <!-- <span>总时长：{{ minTimeAll }}分钟</span> -->
          </div>
        </div>
        <el-table
          :data="tableData"
          border
          :header-cell-style="{
            'background-color': '#eee',
            padding: '8px',
            color: '#333',
          }"
          :default-sort="{ prop: 'sort', order: 'ascending' }"
        >
          <el-table-column
            v-for="(item, index) in tableSet"
            :width="item.width"
            :key="index"
            :label="item.label"
            align="center"
            :show-overflow-tooltip="true"
            header-align="center"
            :sortable="item.prop === 'sort'"
            sort-by="sort"
            :prop="item.prop"
          >
            <template slot-scope="scope">
              <span v-if="item.scope === 'types'">{{
                scope.row[item.prop] === 1
                  ? "录播"
                  : scope.row[item.prop] === 2
                  ? "直播"
                  : scope.row[item.prop] === 3
                  ? "回放"
                  : "未知"
              }}</span>
              <span v-else-if="item.scope === 'Status'">
                {{
                  scope.row[item.prop] === 1
                    ? "发布"
                    : scope.row[item.prop] === 0
                    ? "未发布"
                    : "未知"
                }}
              </span>
              <div v-else-if="item.scope === 'inputs'">
                <el-input-number
                  style="width: 50px"
                  size="small"
                  :controls="false"
                  v-model="scope.row[item.prop]"
                  controls-position="right"
                  :min="0"
                ></el-input-number>
              </div>
              <span v-else>{{ scope.row[item.prop] }}</span></template
            >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="180px"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="jumpChapter(scope.row)"
                >章节内容</el-button
              >
              <el-button type="text" @click="delList(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button @click="backPage">取消</el-button>
        <el-button
          type="primary"
          @click="submit('listData')"
          :loading="disabledBtn"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
    <el-dialog
      @closed="closedFunc"
      :visible.sync="dialogVisible"
      width="800px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">添加章</div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Close@2x.png"
            alt=""
            @click="dialogVisible = false"
          />
        </div>
      </div>
      <search-box-new
        ref="searchBox"
        :formData="formData"
        :formList="formList"
        @search="getInfos"
        @init="init"
      />
      <el-table
        ref="multipleTable"
        :data="boxtableData"
        border
        @select-all="selectAll"
        @select="select"
        :row-key="getRowKeys"
        :header-cell-style="{
          'background-color': '#eee',
          padding: '8px',
          color: '#333',
        }"
      >
        <el-table-column
          align="center"
          type="selection"
          width="55"
          header-align="center"
          :selectable="checkboxT"
          :reserve-selection="true"
        >
        </el-table-column>
        <template v-for="(item, index) in tableSet">
          <el-table-column
            v-if="item.scope !== 'inputs'"
            :width="item.width"
            :key="index"
            :label="item.label"
            align="center"
            :show-overflow-tooltip="true"
            header-align="center"
          >
            <template slot-scope="scope">
              <span v-if="item.scope === 'types'">{{
                scope.row[item.prop] === 1
                  ? "录播"
                  : scope.row[item.prop] === 2
                  ? "直播"
                  : scope.row[item.prop] === 3
                  ? "回放"
                  : "未知"
              }}</span>
              <span v-else-if="item.scope === 'Status'">
                {{
                  scope.row[item.prop] === 1
                    ? "发布"
                    : scope.row[item.prop] === 0
                    ? "未发布"
                    : "未知"
                }}
              </span>
              <span v-else>{{ scope.row[item.prop] }}</span></template
            >
          </el-table-column></template
        >
      </el-table>
      <pagination
        :total="total"
        :pageSize="formData.pageSize"
        :currentPage="formData.pageNum"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="activeLists.length === 0"
          @click="submitForm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogDR"
      width="660px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">导入</div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Close@2x.png"
            alt=""
            @click="dialogDR = false"
          />
        </div>
      </div>
      <div>
        <div class="swq">
          <img
            style="width: 182px; height: 168px"
            src="@/assets/images/dr.png"
            alt=""
          />
        </div>
        <div style="padding-left: 100px">
          <p>第一步：下载导入模板</p>
          <p style="padding-left: 50px">
            <i class="el-icon-upload"></i
            ><span class="dowmStys" @click="getDowm">下载模板</span>
          </p>
          <p>第二步：(批量新增)：点击“上传Excel”完成导入</p>
          <label
            for="mobles"
            class="el-button el-button--primary"
            style="margin-left: 50px; padding: 10px 20px"
            >上传Excel</label
          ><input
            style="display: none"
            type="file"
            id="mobles"
            ref="input1"
            @change="importMobleadd"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDR = false">取消</el-button>
        <!-- <el-button type="primary" @click="submitChecksDR">确定</el-button> -->
      </span>
    </el-dialog>
    <el-dialog
      append-to-body
      :visible.sync="dialogERROR"
      width="660px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">提示</div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Close@2x.png"
            alt=""
            @click="dialogERROR = false"
          />
        </div>
      </div>
      <div>
        <h4 style="margin-top: 0px; font-weight: bold; text-align: center">
          导入失败原因
        </h4>
        <el-input
          readonly
          type="textarea"
          :autosize="{ minRows: 6, maxRows: 24 }"
          v-model="errorData"
        >
        </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogERROR = false">确定</el-button>
      </span>
    </el-dialog>
    <addChapter ref="addChapter" @backData="backData" />
  </div>
</template>

<script>
import * as baseUrls from "@/utils/request.js";
import addChapter from "../addChapter.vue";
import searchBoxNew from "@/components/searchBoxNew";
import pagination from "@/components/pagination";
export default {
  components: { searchBoxNew, pagination, addChapter },
  name: "ModuleManagementAdd",
  data() {
    return {
      disabledBtn: false,
      isIndeterminate: false,
      checkAll: false,
      //   弹窗数据
      changeHeight: true,
      bfImg: "oss/images/avatar/20211013/1634097664410_1397766697",
      listData: {
        publishStatus: 1,
        recordingUrl: "",
        liveUrl: "",
        coverUrl: "oss/images/avatar/20211013/1634097664410_1397766697",
      },
      eduTypeOptions: [], //教育类型数据
      projectTypeOptions: [], //项目类型数据
      courTypeOptions: [], //业务层次数据
      newCourTypeOptions: [], //当前业务层次数据
      sujectOption: [], //科目数据
      newSujectOption: [], //当前科目数据数据
      eduType: "", //当前选中教育类型
      courType: "", //当前选中业务层次
      sujectApis: [], //当前存在的科目
      newSujectApis: [],
      sujectArray: [], //选中的科目
      //表单验证
      rules: {
        prefixName: [
          { required: false, message: "请输入标题前缀", trigger: "blur" },
        ],
        moduleName: [
          { required: true, message: "请输入节标题", trigger: "blur" },
        ],
        // liveDuration: [
        //   { required: true, message: "节时长不能为空" },
        //   { type: "number", message: "节时长必须为数字值" },
        // ],
        publishStatus: [
          { required: true, message: "请选择是否发布", trigger: "change" },
        ],
      },
      numberAll: 0, //节总数
      minTimeAll: 0, //总时长
      tableSet: [
        { label: "排序", prop: "sort", scope: "inputs", width: "100" },
        { label: "章编码", prop: "code", width: "120" },
        { label: "标题前缀", prop: "prefixName", width: "180" },
        { label: "章标题", prop: "name" },
        { label: "节数量", prop: "sectionNum" , width: "120"  },
        {
          label: "发布状态",
          prop: "publishStatus",
          scope: "Status",
          width: "120",
        },
      ],
      tableData: [],
      dialogVisible: false,
      boxtableData: [],
      formList: [
        {
          prop: "educationTypeId",
          placeholder: "教育类型",
          scope: "educationType",
        },
        {
          prop: "businessId",
          placeholder: "业务层次",
          scope: "businessLevel",
          edu: "educationTypeId",
        },
        {
          prop: "subjectId",
          placeholder: "科目",
          scope: "sujectType",
          edu: "educationTypeId",
        },
        // {
        //   prop: "publishStatus",
        //   placeholder: "发布状态",
        //   scope: "select",
        //   options: [
        //     {
        //       label: "已发布",
        //       value: 1,
        //     },
        //     {
        //       label: "未发布",
        //       value: 0,
        //     },
        //   ],
        // },
        {
          prop: "key",
          placeholder: "请输入章标题/章编码/标题前缀",
        },
      ],
      total: 0, //一共多少条
      formData: {
        status: 1,
        pageSize: 10,
        pageNum: 1,
      },
      disCheckList: [], //已选转禁用复选列表
      activeLists: [],
      localData: [],
      errorData: "",
      dialogERROR: false,
      dialogDR: false,
    };
  },
  watch: {
    sujectApis: {
      immediate: true,
      handler(newName, oldName) {
        this.changeTypes();
      },
    },
  },
  mounted() {
    this.localData = this.$methodsTools.getBusinessList();
    this.getDict();
    // this.search();
  },
  activated() {
    if (this.$store.getters.modulePage) {
      this.$api
        .obtainCoursechapter(this.$store.getters.modulePage.id)
        .then((res) => {
          const FIND = this.tableData.findIndex((item) => {
            return item.chapterId == this.$store.getters.modulePage.id;
          });
          if (FIND !== -1) {
            res.data.sort = this.tableData[FIND].sort;
            this.tableData.splice(FIND, 1, res.data);
          }
          this.$store.dispatch("changemodulePage", null);
        });
    }
  },
  methods: {
    
    /**
     * 下载Excel模板
     */
    getDowm() {
      let url =
        baseUrls.BASE_IMG_URL + "/oss/images/file/20220617/1655453121157.xlsx";
      let link = document.createElement("a");
      let fileName = "导入模板" + ".xlsx";
      document.body.appendChild(link);
      link.href = url;
      link.dowmload = fileName;
      link.click();
      link.remove();
    },
    dialogDRFunc() {
      if (!this.newSujectApis.length) {
        this.$message.error("请添加科目");
        return;
      }
      this.dialogDR = true;
    }
    /**
     *
     * @param {Object} e
     * @remards 导入逻辑
     */,
    importMobleadd(e) {
      if (!this.newSujectApis.length) {
        this.$message.error("请添加科目");
        return;
      }
      var self = this;
      var file = e.target.files[0];
      if (file === undefined) {
        e.target.value = ""
        return;
      }
      var type = e.target.value.toLowerCase().split(".").splice(-1);
      if (type[0] != "xlsx"&& type[0] != "xls") {
        self.$message.error("请上传excel文件,且上传格式需为：.xlsx");
        return;
      }
      let formData = new FormData();
      formData.append("businessJson", JSON.stringify(this.newSujectApis));
      formData.append("file", file);
      this.$api
        .CoursemoduleimportData(formData)
        .then(async (res) => {
          if (res.code === 200) {
            if (!res.data.errorLog) {
              await this.awaitGetFestivalList(res.data.importNo, 1)
                .then((result) => {
                  self.dialogDR = false;
                })
                .catch(() => {
                  e.target.value = "";
                });
            } else {
              await this.awaitGetFestivalList(res.data.importNo, 2)
                .then((result) => {
                  let ary = res.data.errorLog.split("\r\n");
                  ary = ary
                    .filter((item) => {
                      return item.length > 0;
                    })
                    .reverse();
                  self.$message({
                    message: `${ary.length}条数据导入失败,请查看失败原因`,
                    customClass: "myMessageClass",
                  });
                  ary = ary.join("\r\n");
                  self.errorData = ary;
                  self.dialogERROR = true;
                })
                .catch(() => {
                  e.target.value = "";
                });
            }
          }
        })
        .finally(() => {
          e.target.value = "";
        });
    },
    /**
     *
     * @param {Strings} ids 查询编码
     * @param {Number} type 1为成功2为失败
     * @remards 失败时也需查询是否有成功的数据导入数据库，如存在 则加列队列同时提示
     */
    awaitGetFestivalList(ids, type) {
      return new Promise((resolve, reject) => {
        this.$api
          .inquireCourseListchapter({ importNo: ids })
          .then((res) => {
            if (type === 2 && res.rows.length) {
              this.$message({
                type: "success",
                message: `成功导入${res.rows.length}条数据,`,
                customClass: "myMessageClass",
              });
            }
            if (res.rows.length) {
              this.activeLists = res.rows;
              if (type === 1) {
                this.submitForm();
              } else {
                this.submitForm(1);
              }
            }
            resolve();
          })
          .catch(() => {
            reject();
          });
      });
    },
    jumpChapter(v) {
      const jump = () => {
        this.$store.dispatch("changemodulePage", {
          name: "moduleManagementAdd",
          id: v.chapterId,
        });
        this.$router.push({
          path: "chapterEdit",
          query: {
            id: v.chapterId,
          },
        });
      };
      const statusPage = this.$store.state.tagsView.visitedViews.some(
        (item) => {
          return item.name == "ChapterEdit";
        }
      );
      if (statusPage) {
        this.$store
          .dispatch("tagsView/delCachedView", {
            name: "ChapterEdit",
          })
          .then((res) => {
            jump();
          });
      } else {
        jump();
      }
    },
    /**
     * 打开添加章组件
     */
    addChapter() {
      if (!this.newSujectApis.length) {
        this.$message.warning("请选择科目");
        return;
      }
      this.$refs.addChapter.openBoxs(this.newSujectApis);
    },
    /**
     * 添加章-返回数据
     */
    backData(v) {
      this.$api.inquireCourseListchapter({ chapterIds: v }).then((res) => {
        this.activeLists = res.rows;
        this.submitForm();
      });
    },
    unTime(val) {
      let a = `${val.businessId}-${val.subjectId}`;
      if (this.sujectApis.includes(a)) {
        this.sujectApis.splice(this.sujectApis.indexOf(a), 1);
      } else {
        this.sujectApis.push(a);
      }
    },
    changeSty(val) {
      var arr = "";
      this.sujectApis.forEach((item) => {
        let arr1 = item.split("-").map(Number);
        if (val.businessId == arr1[0] && val.subjectId == arr1[1]) {
          arr = "activeStyIcons";
        }
      });
      return arr;
    },
    handleCheckedCitiesChange() {
      let nid = this.newSujectOption.map((item) => {
        return item.newId;
      });
      this.checkAll = this.sujectArray.length === nid.length;
      this.isIndeterminate =
        this.sujectArray.length > 0 && this.sujectArray.length < nid.length;
    },
    setFunc(arr) {
      var arrays = [];
      for (let i = 0; i < arr.length; i++) {
        if (!arrays.includes(arr[i])) {
          arrays.push(arr[i]);
        }
      }
      return arrays;
    },
    handleCheckAllChange(val) {
      if (val) {
        let nid = this.newSujectOption.map((item) => {
          return item.newId;
        });
        let arrays = this.sujectArray.concat(nid);
        this.sujectArray = this.setFunc(arrays);
        this.isIndeterminate = false;
      } else {
        let nid = this.newSujectOption.map((item) => {
          return item.newId;
        });
        let newArr = [];
        this.sujectArray.forEach((item) => {
          if (!nid.includes(item)) {
            newArr.push(item);
          }
        });
        this.sujectArray = newArr;
        this.isIndeterminate = false;
      }
    },
    getMessage() {
      if (!this.courType) {
        this.$message.warning("请先选择业务层级");
      }
    },
    openBoxs() {
      var self = this;
      this.$api
        .inquireCourseListchapter({
          status: 1,
          pageNum: 1,
          pageSize: 10,
          publishStatus: 1,
        })
        .then((res) => {
          var aList = [];
          this.tableData.map((item) => {
            aList.push(item.chapterId);
          });
          this.disCheckList = aList;
          this.boxtableData = res.rows;
          this.total = res.total;
          this.dialogVisible = true;
          this.$nextTick(function () {
            self.$refs.multipleTable.clearSelection();
          });
        });
    },
    getInfosList() {
      this.$api
        .inquireCourseListmodulechapter({ chapterId: this.$route.query.id })
        .then((result) => {
          // this.numberAll = result.total;
          // this.minTimeAll = result.timeTotal;
          this.tableData = result.data;
        });
    },
    init() {
      this.getInfos(2);
    },
    getInfos(int) {
      if (int === 1) {
        this.formData.pageNum = 1;
      }
      if (int === 2) {
        this.formData = {
          status: 1,
          pageSize: 10,
          pageNum: 1,
          publishStatus: 1,
        };
      }
      this.$api.inquireCourseListchapter(this.formData).then((res) => {
        this.boxtableData = res.rows;
        this.total = res.total;
      });
    },
    search() {
      this.$api.obtainCoursemodule(this.$route.query.id).then((res) => {
        this.bfImg = res.data.coverUrl;
        this.listData = res.data;
        this.$api
          .obtainCoursechapterbusiness(this.$route.query.id)
          .then((result) => {
            var arrays = [];
            result.data.map((item) => {
              arrays.push(item.businessId + "-" + item.subjectId);
            });
            this.sujectApis = arrays;
            this.getInfosList();
          });
      });
    },
    clearImgs() {
      this.listData.coverUrl = "";
    },
    changeTypes() {
      var self = this;
      var arrays = [];
      this.sujectApis.map((item, index) => {
        this.courTypeOptions.map((items) => {
          if (items.id === item.split("-").map(Number)[0]) {
            var obj = {
              educationTypeId: items.educationId,
              educationName: items.educationName,
              projectId: items.projectId,
              projectName: items.projectName,
              businessId: items.id,
              businessName: items.businessName,
            };
            self.sujectOption.map((i) => {
              if (
                i.id === item.split("-").map(Number)[1] &&
                i.courseArrays.indexOf(items.projectId) !== -1
              ) {
                obj.subjectName = i.subjectName;
                obj.subjectId = i.id;
              }
            });
            arrays.push(obj);
          }
        });
      });
      this.newSujectApis = arrays;
    },
    changeType() {
      this.changeHeight = !this.changeHeight;
    },
    submitSujectArray() {
      var self = this;
      this.sujectApis = this.sujectApis.filter((item, index) => {
        return item.split("-").map(Number)[0] !== Number(self.courType);
      });
      for (let i = 0; i < this.sujectArray.length; i++) {
        this.sujectApis.push(this.sujectArray[i]);
      }
      this.$refs.popovers.doClose();
    },
    showHandle() {
      var array = [];
      for (let i = 0; i < this.sujectApis.length; i++) {
        if (
          this.sujectApis[i].split("-").map(Number)[0] === Number(this.courType)
        ) {
          array.push(this.sujectApis[i]);
        }
      }
      this.sujectArray = array;
      if (!this.newSujectOption.length) {
        this.$message.warning("该业务层次暂无关联科目");
        this.$refs.popovers.doClose();
        return;
      }
      this.newSujectOption.map((item) => {
        item.newId = this.courType + "-" + item.id;
      });
      this.handleCheckedCitiesChange();
    },
    hideHandle() {},
    getDict() {
      this.$api.inquireCourseEducationType({ status: 1 }).then((res) => {
        this.eduTypeOptions = res.rows;
      });
      this.$api.inquireCourseProjectType({ status: 1 }).then((res) => {
        this.projectTypeOptions = res.rows;
      });
      this.$api.inquirebusinessList({ status: 1 }).then((res) => {
        this.courTypeOptions = res.rows;
        this.newCourTypeOptions = res.rows;
      });
      this.$api.inquireCourseSubject({ status: 1 }).then((res) => {
        res.rows.map((item, index) => {
          var array = [];
          item.courseProjectTypes.map((items, indexs) => {
            array.push(items.id);
          });
          item.courseArrays = array;
        });
        this.sujectOption = res.rows;
      });
    },
    changeEduType() {
      if (!(this.courType === undefined || this.courType === "")) {
        this.courType = "";
      }
      var arrays = [];
      this.courTypeOptions.map((item) => {
        if (item.educationId === this.eduType) {
          arrays.push(item);
        }
      });
      this.newCourTypeOptions = arrays;
    },
    changecourseType() {
      this.newCourTypeOptions.map((item, index) => {
        if (item.id === this.courType) {
          this.eduType = item.educationId;
          var array = [];
          this.sujectOption.map((items, indexs) => {
            if (items.courseArrays.indexOf(item.projectId) !== -1) {
              array.push(items);
            }
          });
          this.newSujectOption = array;
        }
      });
      var arrays = [];
      this.courTypeOptions.map((item) => {
        if (item.educationId === this.eduType) {
          arrays.push(item);
        }
      });
      this.newCourTypeOptions = arrays;
      this.$refs.popovers.doClose();
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.newSujectApis.length) {
            this.$message.error("请选择适用业务层级");
            return;
          }
          // if (
          //   this.listData.coverUrl === "" ||
          //   this.listData.coverUrl === null ||
          //   this.listData.coverUrl === undefined
          // ) {
          //   this.$message.error("请上传节封面");
          //   return false;
          // }
          for (let i = 0; i < this.tableData.length; i++) {
            if (!this.tableData[i].sort && this.tableData[i].sort !== 0) {
              this.$message.warning(`管理章第${i + 1}条请输入排序`);
              return;
            }
          }
          let arr = this.tableData.map((items) => {
            return items.sort;
          });
          if (new Set(arr).size != arr.length) {
            this.$message.warning("排序不允许有重复值");
            return;
          }
          this.rulesTableSumbit();
        } else {
          return false;
        }
      });
    },
    async rulesTableSumbit() {
      this.disabledBtn = true;
      var chapterIdList = [];
      this.tableData.map((item) => {
        chapterIdList.push({
          chapterId: item.chapterId,
          sort: Number(item.sort),
        });
      });
      var dataInfos = {
        status: 1,
        businessList: this.newSujectApis,
        chapterIdList: chapterIdList,
        coverUrl: this.listData.coverUrl,
        moduleName: this.listData.moduleName,
        prefixName: this.listData.prefixName,
        publishStatus: this.listData.publishStatus,
      };
      this.$api
        .addCoursemodule(dataInfos)
        .then((res) => {
          this.$methodsTools.cacheBusinessList(this.newSujectApis);
          this.$message.success("新增成功");
          setTimeout(() => {
            this.$store
              .dispatch("tagsView/exitView", this.$route)
              .then((res) => {
                this.$router.push({
                  path: "moduleManagement",
                });
              });
          }, 500);
        })
        .catch(() => {
          this.disabledBtn = false;
        });
    },
    backPage() {
      this.$store.dispatch("tagsView/delView", this.$route).then((res) => {
        this.$router.push({
          path: "moduleManagement",
        });
      });
    },
    closeType(index) {
      this.sujectApis.splice(index, 1);
    },
    getImgFile() {
      var self = this;
      var file = self.$refs.file.files[0];
      if (file === undefined) {
        self.$set(self.listData, "coverUrl", "");
        return;
      }
      if (file.size > 0.3 * 1024 * 1024) {
        self.$message.error("图片不得大于300kb");
        return;
      }
      var type = self.$refs.file.value.toLowerCase().split(".").splice(-1);
      if (
        type[0] != "jpg" &&
        type[0] != "png" &&
        type[0] != "jpeg" &&
        type[0] != "gif"
      ) {
        self.$message.error("上传格式需为：.jpg/.png/.jpeg/gif");
        self.$refs.file.value = "";
        return;
      }
      this.$upload.upload(file, 0).then((res) => {
        self.listData.coverUrl = res;
      });
    },
    handleSizeChange(v) {
      this.formData.pageSize = v;
      this.formData.pageNum = 1;
      this.getInfos();
    },
    handleCurrentChange(v) {
      this.formData.pageNum = v;
      this.getInfos();
    },
    selectAll(value) {
      this.activeLists = value;
    },
    select(value) {
      this.activeLists = value;
    },
    checkboxT(row, index) {
      if (this.disCheckList.indexOf(row.chapterId) !== -1) {
        return false;
      } else {
        return true;
      }
    },
    getRowKeys(row) {
      return row.chapterId;
    },
    /**
     *
     * @param {Number} int 导入失败标识
     * @remards 合并且排列节列表数据
     */
    submitForm(int) {
      if (this.activeLists.length === 0) {
        this.dialogVisible = false;
        return;
      }
      if (this.tableData.length) {
        let maxIndex = 0;
        this.tableData.forEach((item) => {
          if (item.sort > maxIndex) {
            maxIndex = item.sort;
          }
        });
        this.activeLists.forEach((item, index) => {
          item.sort = maxIndex + index + 1;
        });
      } else {
        this.activeLists.forEach((item, index) => {
          item.sort = index + 1;
        });
      }
      this.tableData = this.tableData.concat(this.activeLists);
      this.dialogVisible = false;
      this.activeLists = []
      if (!int) {
        this.$message({
          type: "success",
          message: `添加成功`,
          customClass: "myMessageClass",
        });
      }
    },
    delList(item) {
      this.tableData.map((items, indexs) => {
        if (items.chapterId === item.chapterId) {
          this.tableData.splice(indexs, 1);
          this.$message.success("删除成功");
        }
      });
    },
    closedFunc(){
      this.activeLists = [];
    },
  },
};
</script>

<style lang="less" scoped>
.swq {
  text-align: center;
  border-bottom: 1px solid #eee;
}
.dowmStys {
  color: blue;
  cursor: pointer;
}
.boxWidth {
  width: 800px;
}
.numInputs {
  width: 150px;
}
.checkboxSty {
  max-height: 210px;
  overflow: auto;
  display: flex;
  flex-direction: column;
}
.listBoxStys {
  flex-shrink: 0;
  padding: 0px 10px;
  border-radius: 8px;
  border: 1px solid #eee;
  margin-right: 10px;
  margin-bottom: 6px;
}
.closeIcons {
  color: red;
  cursor: pointer;
  margin-left: 6px;
}
.ach {
  display: flex;
  align-items: center;
  overflow: hidden;
}
.clh {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.imgBoxins {
  width: 375px;
  height: 220px;
  text-align: center;
  img {
    height: 100%;
  }
}
.iconStsz {
  font-size: 40px;
  color: #67c23a;
  cursor: pointer;
}
.dis_plays {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.comInputsty {
  width: 50px;
  height: 24px;
  text-align: center;
  border: none;
}
/deep/.el-button {
  border-radius: 8px;
}
/deep/.el-dialog {
  border-radius: 8px;
  .el-dialog__header {
    padding: 0;
    .hearders {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 18px 0px 20px;
      border-bottom: 1px solid #e2e2e2;
      .leftTitle {
        font-size: 14px;
        font-weight: bold;
        color: #2f4378;
      }
      .rightBoxs {
        display: flex;
        align-items: center;
        img {
          width: 14px;
          height: 14px;
          margin-left: 13px;
          cursor: pointer;
        }
      }
    }
  }
  .el-dialog__footer {
    padding: 0;
    .dialog-footer {
      padding: 0px 40px;
      height: 70px;
      border-top: 1px solid #e2e2e2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
.imgBox {
  width: 100%;
  // height: 210px;
  border: 1px solid #e2e2e2;
  border-radius: 8px;
  padding: 8px 8px 3px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .imgLabel {
    flex: 1;
    width: 100%;
    border: 1px dotted #e2e2e2;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    border-radius: 8px;
    .msPhoto {
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 100%;
      max-height: 270px;
      img {
        max-width: 100%;
        max-height: 270px;
      }
    }
    .imgbbx {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      i {
        font-weight: bold;
        margin: 14px 0;
        font-size: 24px;
      }
    }
  }
  p {
    margin: 5px 0px;
  }
}
</style>
