<template>
  <div id="volumeManagementAdd">
    <div class="boxWidth">
      <el-form
        label-position="right"
        label-width="120px"
        :model="listData"
        :rules="rules"
        ref="listData"
      >
        <el-form-item label="适用业务层级" :required="true">
          <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-radio-group v-model="sujectApis" class="dis_flexbox">
              <el-radio
                v-for="(item, index) in newSujectOption"
                :label="item.newId"
                :key="index"
                >{{ item.subjectName }}</el-radio
              >
            </el-radio-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>
        </el-form-item>
        <el-form-item label="">
          <!-- <span v-if="Object.keys(newSujectApis).length == 0"
            >未选项目类型</span
          > -->
          <div
            v-if="Object.keys(newSujectApis).length !== 0"
            style="display: flex"
          >
            <div class="listBoxStys">
              {{
                newSujectApis.educationName +
                " - " +
                newSujectApis.projectName +
                " - " +
                newSujectApis.businessName +
                " - " +
                newSujectApis.subjectName
              }}
              <i class="el-icon-error closeIcons" @click="closeType"></i>
            </div>
          </div>
        </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="moduleName">
          <el-input v-model="listData.moduleName"></el-input>
        </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' }"
          >
            <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="100px"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="delList(scope.row, scope.$index)"
                  >删除</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="submitIns('listData')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      :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(1)"
        @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>
  </div>
</template>

<script>
import searchBoxNew from "@/components/searchBoxNew";
import pagination from "@/components/pagination";
import tableList from "@/components/tableList";
export default {
  components: { searchBoxNew, tableList, pagination },
  name: "VolumeManagementAdd",
  data() {
    return {
      listData: {
        publishStatus: 1,
      }, //   弹窗数据
      eduTypeOptions: [], //教育类型数据
      projectTypeOptions: [], //项目类型数据
      courTypeOptions: [], //业务层次数据
      newCourTypeOptions: [], //当前业务层次数据
      sujectOption: [], //科目数据
      newSujectOption: [], //当前科目数据数据
      eduType: "", //当前选中教育类型
      courType: "", //当前选中业务层次

      newSujectApis: {},
      sujectApis: "", //当前存在的科目 例如'19-2'
      //表单验证
      rules: {
        moduleName: [
          { required: true, message: "请输入模块卷标题", trigger: "blur" },
        ],
        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", width: "320" },
        {
          label: "发布状态",
          prop: "publishStatus",
          scope: "Status",
          width: "120",
        },
      ],
      tableData: [],
      dialogVisible: false,
      boxtableData: [],
      total: 0, //一共多少条
      formList: [
        {
          prop: "key",
          placeholder: "请输入章卷标题/章卷编码/标题前缀",
        },
      ],
      formData: {
        publishStatus: 1,
        status: 1,
        pageSize: 10,
        pageNum: 1,
      },
      disCheckList: [], //已选转禁用复选列表
      activeLists: [],
    };
  },
  watch: {
    newSujectApis() {
      this.tableData = [];
    },
  },
  mounted() {
    this.getDict();
  },
  methods: {
    openBoxs() {
      if (!this.newSujectApis.subjectId) {
        this.$message.warning("请先选择科目");
        return;
      }
      var self = this;
      var data = JSON.parse(JSON.stringify(this.formData));
      data.businessId = this.newSujectApis.businessId;
      data.subjectId = this.newSujectApis.subjectId;
      this.$api.inquirebankchapterList(data).then((res) => {
        var aList = [];
        this.tableData.map((item) => {
          aList.push(item.chapterExamId);
        });
        this.disCheckList = aList;
        this.boxtableData = res.rows;
        this.total = res.total;
        this.dialogVisible = true;
        this.$nextTick(function () {
          self.$refs.multipleTable.clearSelection();
        });
      });
    },
    getInfos(int) {
      if (int === 1) {
        this.formData.pageNum = 1;
      }
      if (int === 2) {
        this.formData = {
          status: 1,
          pageSize: 10,
          pageNum: 1,
          publishStatus: 1,
        };
      }
      var data = JSON.parse(JSON.stringify(this.formData));
      data.businessId = this.newSujectApis.businessId;
      data.subjectId = this.newSujectApis.subjectId;
      this.$api.inquirebankchapterList(data).then((res) => {
        this.boxtableData = res.rows;
        this.total = res.total;
      });
    },
    init() {
      this.getInfos(2);
    },
    changeTypes() {
      var self = this;
      if (!this.sujectApis) {
        self.newSujectApis = {};
        return;
      }
      this.courTypeOptions.map((items) => {
        if (items.id === this.sujectApis.split("-").map(Number)[0]) {
          var obj = {
            type: 4,
            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 === self.sujectApis.split("-").map(Number)[1] &&
              i.courseArrays.indexOf(items.projectId) !== -1
            ) {
              obj.subjectName = i.subjectName;
              obj.subjectId = i.id;
            }
          });
          self.newSujectApis = obj;
        }
      });
    },
    getMessage() {
      if (!this.courType) {
        this.$message.warning("请先选择业务层级");
      }
    },
    submitSujectArray() {
      this.changeTypes();
      this.$refs.popovers.doClose();
    },
    showHandle() {
      this.sujectApis = "";
      this.newSujectOption.map((item) => {
        item.newId = this.courType + "-" + item.id;
        if (item.newId === this.sujectApis) {
          console.log("成功");
        }
      });
      this.sujectApis =
        this.newSujectApis.businessId + "-" + this.newSujectApis.subjectId;
    },
    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();
      this.tableData = [];
    },
    submitIns(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (JSON.stringify(this.newSujectApis) === "{}") {
            this.$message.error("请选择适用业务层级");
            return;
          }
          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() {
      var chapterList = [];
      this.tableData.map((item) => {
        chapterList.push({
          chapterExamId: item.chapterExamId,
          sort: Number(item.sort),
        });
      });
      var data1 = {
        // examId: this.listData.examId,
        moduleName: this.listData.moduleName,
        chapterList: chapterList,
        publishStatus: this.listData.publishStatus,
        prefixName: this.listData.prefixName,
        businessList: [this.newSujectApis],
        status: 1,
      };
      this.$api.addBankModule(data1).then((res) => {
        this.$message.success("新增成功");
        setTimeout(() => {
          this.$store.dispatch("tagsView/exitView", this.$route).then((res) => {
            this.$router.push({
              path: "volumeManagement",
            });
          });
        }, 500);
      });
    },
    backPage() {
      this.$store.dispatch("tagsView/delView", this.$route).then((res) => {
        this.$router.push({
          path: "volumeManagement",
        });
      });
    },
    closeType() {
      this.sujectApis = "";
      this.changeTypes();
    },
    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.chapterExamId) !== -1) {
        return false;
      } else {
        return true;
      }
    },
    getRowKeys(row) {
      return row.chapterExamId;
    },
    submitForm() {
      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.$message.success("添加成功");
      this.activeLists = [];
    },
    delList(item, index) {
      this.tableData.splice(index, 1);
      this.$message.success("删除成功");
    },
  },
};
</script>

<style lang="less" scoped>
.dis_flexbox {
  display: flex;
  flex-direction: column;
}
.boxWidth {
  width: 700px;
}
.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;
}
.BusBoxs {
  min-height: 100px;
  border: 1px solid #a4a4a4;
  margin-bottom: 10px;
  border-radius: 8px;
  max-height: 280px;
  padding: 10px;
  overflow-y: auto;
  .fot_Le {
    border-radius: 12px;
    border: 1px solid yellowgreen;
    padding: 0px 10px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    float: left;
    margin-right: 6px;
    margin-bottom: 6px;
    .icon_clear {
      margin-left: 2px;
      font-size: 15px;
      color: #f56c6c;
      cursor: pointer;
    }
  }
}
.marg_play {
  display: flex;
  margin-bottom: 15px;
  .spans {
    text-align: right;
    width: 80px;
  }
}
/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: center;
    }
  }
}
.centerStys {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 18px;
}
.dis_fos {
  align-items: flex-end;
  display: flex;
  justify-content: space-between;
}
.margin_bs {
  margin-bottom: 6px;
}
.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>
