<template>
  <div id="chapterEdit">
    <div class="boxWidth">
      <el-form
        label-position="right"
        label-width="120px"
        :model="listData"
        :rules="rules"
        ref="listData"
      >
        <el-form-item label="适用业务层级">
          <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.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-group v-model="sujectArray" class="checkboxSty">
              <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"
              >请选择科目</el-button
            >
          </el-popover>
        </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-button
            size="mini"
            v-if="newSujectApis.length > 1"
            @click="changeType"
            >{{ changeHeight ? "展开" : "关闭" }}</el-button
          >
          <span v-if="newSujectApis.length === 0">未选项目类型</span>
        </el-form-item>
        <el-form-item label="标题前缀" prop="prefixName">
          <el-input v-model="listData.prefixName"></el-input>
        </el-form-item>
        <el-form-item label="章标题" prop="name">
          <el-input v-model="listData.name"></el-input>
        </el-form-item>

        <el-form-item label="节封面">
          <div class="imgBoxins">
            <img :src="$methodsTools.splitImgHost(listData.coverUrl)" alt="" />
            <div
              class="posimg"
              v-if="
                listData.coverUrl === null ||
                listData.coverUrl === '' ||
                listData.coverUrl === undefined
              "
            >
              <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"
              />
              <p>
                注：请上传小于300kb，尺寸为750*440的图片，支持gif、jpg、jpeg、png等类型
              </p>
            </div>
          </div>
          <el-button
            v-if="
              listData.coverUrl !== null &&
              listData.coverUrl !== '' &&
              listData.coverUrl !== undefined
            "
            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>
        <el-form-item label="管理节">
          <div class="dis_plays">
            <div>
              <el-button size="small" @click="openBoxs">添加节</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' }"
          >
            <template v-for="(item, index) in tableSet">
              <el-table-column
                :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></template
            >
            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="100px"
            >
              <template slot-scope="scope">
                <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')">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="添加节" :visible.sync="dialogVisible" width="800px">
      <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="pageSize"
        :currentPage="currentPage"
        @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>
  </div>
</template>

<script>
import pagination from "@/components/pagination";
export default {
  components: { pagination },
  data() {
    return {
      //   弹窗数据
      changeHeight: true,
      bfImg: "oss/images/avatar/20211013/1634097664410_1397766697",
      listData: {
        recordingUrl: "",
        liveUrl: "",
        coverUrl: "oss/images/avatar/20211013/1634097664410_1397766697",
      },
      eduTypeOptions: [], //教育类型数据
      projectTypeOptions: [], //项目类型数据
      courTypeOptions: [], //业务层次数据
      newCourTypeOptions: [], //当前业务层次数据
      sujectOption: [], //科目数据
      newSujectOption: [], //当前科目数据数据
      eduType: "", //当前选中教育类型
      courType: "", //当前选中业务层次
      sujectApis: [], //当前存在的科目
      newSujectApis: [],
      sujectArray: [], //选中的科目
      //表单验证
      rules: {
        prefixName: [
          { required: true, message: "请输入标题前缀", trigger: "blur" },
        ],
        name: [{ 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" },
        { label: "标题前缀", prop: "prefixName", width: "120" },
        { label: "节标题", prop: "name" },
        { label: "节类型", prop: "sectionType", scope: "types" },
        {
          label: "发布状态",
          prop: "publishStatus",
          scope: "Status",
          width: "120",
        },
      ],
      tableData: [],
      dialogVisible: false,
      boxtableData: [],
      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码
      disCheckList: [], //已选转禁用复选列表
      activeLists:[],
    };
  },
  watch: {
    sujectApis: {
      immediate: true,
      handler(newName, oldName) {
        this.changeTypes();
      },
    },
  },
  mounted() {
    this.getDict();
    this.search();
  },
  methods: {
    openBoxs() {
      var self = this;
      this.$api
        .inquireCourseSection({
          status: 1,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
        })
        .then((res) => {
          var aList = [];
          this.tableData.map((item) => {
            aList.push(item.sectionId);
          });
          this.disCheckList = aList;
          this.boxtableData = res.rows;
          this.total = res.total;
          this.dialogVisible = true;
          this.$nextTick(function () {
            self.$refs.multipleTable.clearSelection();
          });
        });
    },
    getInfosList() {
      this.$api
        .inquireCoursechaptersectionlist(this.$route.query.id)
        .then((result) => {
          // this.numberAll = result.total;
          // this.minTimeAll = result.timeTotal;
          this.tableData = result.data;
        });
    },
    getInfos() {
      this.$api
        .inquireCourseSection({
          status: 1,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
        })
        .then((res) => {
          this.boxtableData = res.rows;
          this.total = res.total;
        });
    },
    search() {
      this.$api.obtainCoursechapter(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;
      this.newSujectOption.map((item) => {
        item.newId = this.courType + "-" + item.id;
      });
    },
    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.listData.coverUrl === "" ||
            this.listData.coverUrl === null ||
            this.listData.coverUrl === undefined
          ) {
            this.$message.error("请上传节封面");
            return false;
          }
          this.rulesTableSumbit();
        } else {
          return false;
        }
      });
    },
    async rulesTableSumbit() {
      var sectionIdList = []
      this.tableData.map(item => {
        sectionIdList.push({sectionId:item.sectionId,sort:Number(item.sort)})
      })
      var dataInfos = {
        status: 1,
        chapterId: this.$route.query.id,
        businessList: this.newSujectApis,
        sectionIdList:sectionIdList,
        coverUrl: this.listData.coverUrl,
        name: this.listData.name,
        prefixName: this.listData.prefixName,
        publishStatus: this.listData.publishStatus,
      };
      this.$api.editCoursechapter(dataInfos).then((res) => {
        this.$message.success("修改成功");
        setTimeout(() => {
          this.$router.go(-1);
        }, 500);
      });
    },
    backPage() {
      this.$router.go(-1);
    },
    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 > 2 * 1024 * 1024) {
        self.$message.error("图片不得大于2MB");
        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.pageSize = v;
      this.currentPage = 1;
      this.getInfos();
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.getInfos();
    },
    selectAll(value) {
      this.activeLists = value;
    },
    select(value) {
      this.activeLists = value;
    },
    checkboxT(row, index) {
      if (this.disCheckList.indexOf(row.sectionId) !== -1) {
        return false;
      } else {
        return true;
      }
    },
    getRowKeys(row) {
      return row.sectionId;
    },
    submitForm() {
      if (this.activeLists.length === 0) {
        this.dialogVisible = false;
        return;
      }
      this.tableData = this.tableData.concat(this.activeLists);
      this.dialogVisible = false;
      this.$message.success("添加成功");
          this.activeLists = [];
    },
    delList(item) {
      this.tableData.map((items,indexs) => {
        if(items.sectionId === item.sectionId){
          this.tableData.splice(indexs,1)
          this.$message.success("删除成功");
        }
      })
    },
  },
};
</script>

<style lang="less" scoped>
.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;
}
</style>
