<template>
  <section class="content">
    <!-- 正文信息 -->
    <div class="part-box">
      <h2 class="part-box-title">课程属性</h2>
      <el-form class="part-filter-form" :inline="true" :model="formSearch">
        <el-form-item label="属性名称">
          <el-input
            v-model="formSearch.name"
            placeholder="请输入属性名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="课程名称">
          <course-select v-model="formSearch.courseId"> </course-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchFrom">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <div>
          <el-button
            type="danger"
            plain
            icon="icon icon-delete"
            :disabled="noBatchSelected"
            @click="toBatchDeleteCourseProperty"
            >删除</el-button
          >
          <el-button
            type="primary"
            plain
            icon="icon icon-import"
            @click="impCourseProperty"
            >导入
          </el-button>
          <el-button
            type="primary"
            plain
            icon="icon icon-export"
            :disabled="noBatchSelected"
            @click="exportCourseProperty(selectedList)"
            >导出
          </el-button>
        </div>
        <el-button
          type="primary"
          icon="icon icon-plus-white"
          @click="addCourseProperty"
          >新增</el-button
        >
      </div>
    </div>

    <div class="part-box">
      <!-- 页面列表 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        element-loading-text="拼命加载中"
        @selection-change="selectionChange"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column label="课程名称">
          <template slot-scope="scope">
            <span>{{ scope.row.courseName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="属性名称">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.enable">
              <el-tooltip
                class="item"
                effect="dark"
                content="启用"
                placement="left"
              >
                <i class="icon icon-right"></i>
              </el-tooltip>
            </span>
            <span v-else>
              <el-tooltip
                class="item"
                effect="dark"
                content="禁用"
                placement="left"
              >
                <i class="icon icon-error"></i>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-button
                size="mini"
                type="primary"
                plain
                @click="exportCourseProperty([scope.row.id])"
                >导出
              </el-button>
              <el-button
                size="mini"
                type="primary"
                plain
                @click="editCourseProperty(scope.row)"
                >详情
              </el-button>
              <el-button
                size="mini"
                type="danger"
                plain
                @click="toDeleteCourseProperty(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 300]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="新增课程属性名称"
      :visible.sync="coursePropertyDialog"
      width="520px"
      :modal="true"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form
        ref="coursePropertyForm"
        :model="coursePropertyForm"
        :rules="rules"
        label-position="right"
        label-width="90px"
        inline-message
        class="form-tight"
      >
        <el-form-item label="属性名称" prop="name">
          <el-input
            v-model="coursePropertyForm.name"
            class="dialog-input-width"
            maxlength="100"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseId">
          <el-select
            v-model="coursePropertyForm.courseId"
            :remote-method="getCoursesForAdd"
            :loading="courseAddSearch"
            remote
            filterable
            clearable
            class="dialog-input-width"
            placeholder="请选择课程"
            @clear="getCoursesForAdd('')"
          >
            <el-option
              v-for="item in courseAddList"
              :key="item.id"
              :label="item.name + '(' + item.code + ')'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submit('coursePropertyForm')"
          >保存</el-button
        >
        <el-button type="danger" plain @click="resetForm('coursePropertyForm')"
          >重置</el-button
        >
        <el-button type="danger" plain @click="back('coursePropertyForm')"
          >返回</el-button
        >
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <import-file-dialog
      ref="ImportCourseDialog"
      dialog-title="导入课程"
      :template-url="courseTemplateUrl"
      :upload-url="uploadCourseUrl"
      @uploaded="uploadSuccess"
    ></import-file-dialog>

    <!-- 导入错误信息列表 -->
    <el-dialog title="错误提示" :visible.sync="errDialog" append-to-body>
      <div
        v-for="errMessage in errMessages"
        :key="errMessage.lineNum"
        class="text-danger"
      >
        第{{ errMessage.lineNum }}行：{{ errMessage.msg }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="errDialog = false">确定</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
import { QUESTION_API } from "@/constants/constants";
import { mapState } from "vuex";
import { downloadByApi } from "@/plugins/download";
import ImportFileDialog from "@/components/ImportFileDialog.vue";

export default {
  components: { ImportFileDialog },
  data() {
    return {
      courseAddSearch: false,
      courseLoading4Search: false,
      formSearch: {
        name: "",
        courseId: "",
      },

      uploadCourseUrl: `${QUESTION_API}/courseProperty/import`,
      courseTemplateUrl: `${QUESTION_API}/courseProperty/importTemplate`,
      errMessages: [],
      errDialog: false,

      courseList: [],
      courseAddList: [],
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      coursePropertyForm: {
        name: "",
        courseId: "",
      },
      coursePropertyDialog: false,
      selectedList: [],
      rules: {
        name: [{ required: true, message: "请输入属性名称", trigger: "blur" }],
        courseId: [
          { required: true, message: "请选择课程名称", trigger: "change" },
        ],
      },
      downloading: false,
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.user,
    }),
    selectedIds() {
      var selectedIdsStr = "";
      for (let id of this.selectedList) {
        if (!selectedIdsStr) {
          selectedIdsStr += id;
        } else {
          selectedIdsStr += "," + id;
        }
      }
      return selectedIdsStr;
    },
    courseInfoSelect() {
      var courseList = [];
      for (var i = 0; i < this.courseList.length; i++) {
        var courseInfo = {
          courseInfo:
            this.courseList[i].name + "(" + this.courseList[i].code + ")",
          courseId: this.courseList[i].id,
        };
        courseList.push(courseInfo);
      }
      return courseList;
    },
    noBatchSelected() {
      return this.selectedList.length === 0;
    },
  },
  watch: {
    $route: "initValue",
  },
  created() {
    this.initValue();
    this.uploadHeaders = {
      key: this.user.key,
      token: this.user.token,
    };
    this.getCourses("");
    this.getCoursesForAdd("");
  },

  methods: {
    // 导出
    async exportCourseProperty(coursePropertyIds) {
      if (!coursePropertyIds.length) {
        this.$message.error("请选择要导出的属性");
        return;
      }
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        return this.$httpWithMsg.get(
          `${QUESTION_API}/courseProperty/detail/export`,
          {
            params: { coursePropertyIds: coursePropertyIds.join() },
            responseType: "blob",
          }
        );
      }).catch((e) => {
        this.$message.error(e || "导出失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("导出成功！");
    },
    //导入
    impCourseProperty() {
      this.$refs.ImportCourseDialog.open();
    },
    uploadSuccess(response) {
      const { hasError, failRecords } = response.data;
      if (!hasError) {
        this.$notify({
          message: "上传成功",
          type: "success",
        });
        this.searchCourProperty();
      } else {
        this.errMessages = failRecords;
        this.errDialog = true;
      }
    },
    //查询所有课程属性
    searchFrom() {
      this.currentPage = 1;
      this.searchCourProperty();
    },
    searchCourProperty() {
      var pageNo = Number(this.currentPage);
      this.loading = true;
      var url =
        QUESTION_API +
        "/courseProperty/all/" +
        this.currentPage +
        "/" +
        this.pageSize;
      this.$http.get(url, { params: this.formSearch }).then((response) => {
        this.tableData = response.data.content;
        this.total = response.data.totalElements;
        this.currentPage = pageNo;
        this.loading = false;
      });
    },
    //新增
    addCourseProperty() {
      this.coursePropertyDialog = true;
      this.coursePropertyForm.name = "";
      this.coursePropertyForm.courseId = "";
      this.getCoursesForAdd("");
    },
    //重置
    resetForm(formData) {
      this.coursePropertyForm.name = "";
      this.coursePropertyForm.courseId = "";
      this.$refs[formData].clearValidate();
    },
    //返回
    back(formData) {
      this.resetForm(formData);
      this.coursePropertyDialog = false;
    },
    //修改
    editCourseProperty(row) {
      sessionStorage.setItem("course_property_name", this.formSearch.name);
      sessionStorage.setItem(
        "course_property_courseId",
        this.formSearch.courseId
      );
      sessionStorage.setItem("course_property_currentPage", this.currentPage);
      sessionStorage.setItem("courseProperty", JSON.stringify(row));
      this.$router.push({
        path: "/questions/property_info/" + row.id,
      });
    },
    // 删除
    async deleteCourseProperty(ids) {
      if (this.loading) return;
      this.loading = true;

      const res = await this.$httpWithMsg
        .post(
          QUESTION_API + "/courseProperty/delete",
          {},
          { params: { coursePropertyIdList: ids } }
        )
        .catch(() => {});
      this.loading = false;
      if (!res) return;
      this.$message.success("操作成功！");
      this.searchCourProperty();
    },
    async toDeleteCourseProperty(row) {
      const confirm = await this.$confirm("确认删除?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") return;

      await this.deleteCourseProperty(row.id);
    },
    //批量关闭
    async toBatchDeleteCourseProperty() {
      if (!this.selectedIds.length) {
        this.$message.error("请选择要删除数据");
        return;
      }
      const confirm = await this.$confirm("确认删除?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") return;

      await this.deleteCourseProperty(this.selectedIds);
    },
    //分页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchCourProperty();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.searchCourProperty();
    },
    //确定
    submit(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          this.$http
            .post(
              QUESTION_API + "/courseProperty/save",
              this.coursePropertyForm
            )
            .then(() => {
              this.$notify({
                message: "新增成功",
                type: "success",
              });
              this.coursePropertyDialog = false;
              this.searchCourProperty();
            })
            .catch((error) => {
              this.$notify({
                type: "error",
                message: error.response.data.desc,
              });
            });
        } else {
          return false;
        }
      });
    },
    //查询所有课程
    getCourses(query) {
      this.courseLoading4Search = true;
      this.$httpWithMsg
        .get(QUESTION_API + "/course/query?name=" + query)
        .then((response) => {
          this.courseList = response.data;
          this.courseLoading4Search = false;
        });
    },
    getCoursesForAdd(query) {
      this.courseAddSearch = true;
      this.$httpWithMsg
        .get(QUESTION_API + "/course/query?name=" + query + "&enable=true")
        .then((response) => {
          this.courseAddList = response.data;
          this.courseAddSearch = false;
        });
    },
    removeItem() {
      sessionStorage.removeItem("course_property_name");
      sessionStorage.removeItem("course_property_courseId");
      sessionStorage.removeItem("course_property_currentPage");
    },
    //页面回填值
    initValue() {
      this.isClear = this.$route.params.isClear;
      if (this.isClear == 0 || !this.isClear) {
        this.removeItem();
        this.formSearch = {
          name: "",
          courseId: "",
        };
      } else {
        this.formSearch.name =
          sessionStorage.getItem("course_property_name") == "null"
            ? ""
            : sessionStorage.getItem("course_property_name");
        this.formSearch.courseId =
          sessionStorage.getItem("course_property_courseId") == ""
            ? ""
            : parseInt(sessionStorage.getItem("course_property_courseId"));
        this.currentPage =
          sessionStorage.getItem("course_property_currentPage") == null
            ? 1
            : parseInt(sessionStorage.getItem("course_property_currentPage"));
      }
      this.getOneCourse(this.formSearch.courseId);
      this.handleCurrentChange(this.currentPage);
    },
    //查询单个课程
    getOneCourse(courseId) {
      if (courseId) {
        this.$http
          .get(QUESTION_API + "/course/" + courseId)
          .then((response) => {
            this.courseList.push(response.data);
          });
      } else {
        this.courseList = [];
      }
    },
    //全选
    selectionChange(val) {
      this.selectedList = [];
      var selectedList = this.selectedList;
      val.forEach((element) => {
        selectedList.push(element.id);
      });
      this.selectedList = selectedList;
    },
  },
};
</script>
