<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="课程名称">
          <el-select
            v-model="formSearch.courseId"
            :remote-method="getCourses"
            :loading="courseLoading4Search"
            remote
            filterable
            clearable
            placeholder="请选择"
            @clear="getCourses('')"
          >
            <el-option
              v-for="item in courseInfoSelect"
              :key="item.courseId"
              :label="item.courseInfo"
              :value="item.courseId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="searchFrom">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <div>
          <el-button
            type="success"
            plain
            icon="icon icon-play"
            :disabled="noBatchSelected"
            @click="openCoursePropertys"
            >启用</el-button
          >
          <el-button
            type="danger"
            plain
            icon="icon icon-delete"
            :disabled="noBatchSelected"
            @click="closeCoursePropertys"
            >禁用</el-button
          >
          <el-button
            type="primary"
            plain
            icon="icon icon-import"
            @click="impCourseProperty"
            >导入
          </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="160">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-button
                size="mini"
                type="primary"
                plain
                @click="editCourseProperty(scope.row)"
                >详情
              </el-button>
              <el-button
                v-if="!scope.row.enable"
                size="mini"
                type="primary"
                plain
                @click="openCourseProperty(scope.row)"
              >
                启用
              </el-button>
              <el-button
                v-if="scope.row.enable"
                size="mini"
                type="danger"
                plain
                @click="closeCourseProperty(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="false"
      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>
    <!-- 导入弹窗 -->
    <el-dialog
      title="导入课程"
      width="520px"
      :visible.sync="impDialog"
      :modal="false"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form>
        <el-form-item style="margin-left: 20px">
          <el-upload
            ref="upload"
            class="form_left"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :action="uploadAction"
            :headers="uploadHeaders"
            :data="uploadData"
            :before-upload="beforeUpload"
            :on-progress="uploadProgress"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :file-list="fileList"
            :auto-upload="false"
            :multiple="false"
          >
            <el-button
              slot="trigger"
              size="small"
              type="primary"
              icon="icon icon-search-white"
            >
              选择文件
            </el-button>
            <el-button
              size="small"
              type="primary"
              icon="icon icon-save-white"
              @click="submitUpload"
            >
              确认上传
            </el-button>
            <el-button
              size="small"
              type="primary"
              icon="icon icon-delete-white"
              @click="removeFile"
            >
              清空文件
            </el-button>
            <el-button
              size="small"
              type="primary"
              icon="icon icon-export-white"
              @click="exportFile"
            >
              下载模板
            </el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-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";
export default {
  data() {
    return {
      courseAddSearch: false,
      courseLoading4Search: false,
      formSearch: {
        name: "",
        courseId: "",
      },

      impDialog: false,
      uploadAction: QUESTION_API + "/courseProperty/import",
      uploadHeaders: {},
      uploadData: {},
      errMessages: [],
      errDialog: false,
      fileLoading: false,
      fileList: [],

      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" },
        ],
      },
    };
  },
  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: {
    //导入
    impCourseProperty() {
      this.impDialog = true;
      this.initUpload();
    },
    initUpload() {
      this.fileList = [];
    },
    beforeUpload(file) {
      console.log(file);
    },
    uploadProgress() {
      console.log("uploadProgress");
    },
    uploadSuccess(response) {
      if (!response.hasError) {
        this.$notify({
          message: "上传成功",
          type: "success",
        });
        this.fileLoading = false;
        this.impDialog = false;
        this.searchCourProperty();
      } else {
        this.fileLoading = false;
        this.impDialog = false;
        this.errMessages = response.failRecords;
        this.errDialog = true;
      }
    },
    uploadError(response) {
      var json = JSON.parse(response.message);
      if (response.status == 500) {
        this.$notify({
          message: json.desc,
          type: "error",
        });
      }
      this.fileLoading = false;
    },
    //确定上传
    submitUpload() {
      if (!this.checkUpload()) {
        return false;
      }
      this.$refs.upload.submit();
      this.fileLoading = true;
    },
    checkUpload() {
      var fileList = this.$refs.upload.uploadFiles;
      if (fileList.length == 0) {
        this.$notify({
          message: "上传文件不能为空",
          type: "error",
        });
        return false;
      }
      if (fileList.length > 1) {
        this.$notify({
          message: "每次只能上传一个文件",
          type: "error",
        });
        return false;
      }
      for (let file of fileList) {
        if (!file.name.endsWith(".xlsx")) {
          this.$notify({
            message: "上传文件必须为xlsx格式",
            type: "error",
          });
          this.initUpload();
          return false;
        }
      }
      return true;
    },
    //清空文件
    removeFile() {
      // this.fileList = [];
      this.$refs.upload.clearFiles();
    },
    //下载模板
    exportFile() {
      window.location.href =
        QUESTION_API +
        "/courseProperty/importTemplate?$key=" +
        this.user.key +
        "&$token=" +
        this.user.token;
    },
    //查询所有课程属性
    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,
      });
    },
    //开启
    openCourseProperty(row) {
      this.$confirm("确认开启?", "提示", {
        type: "success",
      }).then(() => {
        this.loading = true;
        this.$http
          .put(QUESTION_API + "/courseProperty/open/" + row.id)
          .then(() => {
            this.$notify({
              message: "开启成功",
              type: "success",
            });
            this.searchCourProperty();
          })
          .catch(() => {
            this.$notify({
              type: "error",
              message: "开启失败",
            });
          });
      });
    },
    //批量启用
    openCoursePropertys() {
      this.$confirm("是否确认开启？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      }).then(() => {
        this.loading = true;
        var url = QUESTION_API + "/courseProperty/opens/" + this.selectedIds;
        this.$http
          .put(url)
          .then(() => {
            this.$notify({
              type: "success",
              message: "开启成功！",
            });
            this.searchCourProperty();
            this.selectedList = [];
          })
          .catch(() => {
            this.$notify({
              type: "error",
              message: "开启失败！",
            });
            this.selectedList = [];
          });
      });
      this.loading = false;
    },
    //关闭
    closeCourseProperty(row) {
      this.$confirm("确认禁用?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$http
          .put(QUESTION_API + "/courseProperty/close/" + row.id)
          .then(() => {
            this.$notify({
              message: "禁用成功",
              type: "success",
            });
            this.searchCourProperty();
          })
          .catch(() => {
            this.$notify({
              type: "error",
              message: "禁用失败",
            });
          });
      });
    },
    //批量关闭
    closeCoursePropertys() {
      this.$confirm("是否确认禁用？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      }).then(() => {
        this.loading = true;
        var url = QUESTION_API + "/courseProperty/closes/" + this.selectedIds;
        this.$http
          .put(url)
          .then(() => {
            this.$notify({
              type: "success",
              message: "禁用成功！",
            });
            this.searchCourProperty();
            this.selectedList = [];
          })
          .catch(() => {
            this.$notify({
              type: "error",
              message: "禁用失败！",
            });
            this.selectedList = [];
          });
      });
      this.loading = false;
    },
    //分页
    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>
