<template>
  <section class="content">
    <div v-show="isClear == 1">
      <LinkTitlesCustom :currentPaths="['基础信息', '课程属性预设']" />
    </div>
    <!-- 正文信息 -->
    <div class="box-body">
      <el-form
        :inline="true"
        :model="formSearch"
        label-position="right"
        label-width="90px"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="属性名称" class="pull-left">
              <el-input
                class="search_width"
                placeholder="请输入属性名称"
                v-model="formSearch.name"
                size="small"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="课程名称">
              <el-select
                class="search_width"
                v-model="formSearch.courseId"
                filterable
                :remote-method="getCourses"
                remote
                clearable
                placeholder="请选择"
                size="small"
              >
                <el-option
                  v-for="item in courseInfoSelect"
                  :label="item.courseInfo"
                  :value="item.courseId"
                  :key="item.courseId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="search_down">
              <el-button size="small" type="primary" @click="searchCourProperty"
                ><i class="el-icon-search"></i> 查询</el-button
              >
              <el-button size="small" type="primary" @click="addCourseProperty"
                ><i class="el-icon-plus"></i> 新增</el-button
              >
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item class="pull-left">
            <el-button size="small" type="primary" @click="openCoursePropertys"
              ><i class="el-icon-circle-check"></i> 批量启用</el-button
            >
            <el-button size="small" type="danger" @click="closeCoursePropertys"
              ><i class="el-icon-circle-close"></i> 批量禁用</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>

      <!-- 页面列表 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        element-loading-text="拼命加载中"
        border
        style="width:100%;"
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" width="35"></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>{{ getEnable(scope.row.enable) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-button
                size="mini"
                type="primary"
                @click="editCourseProperty(scope.row)"
                ><i class="el-icon-zoom-in"></i> 详情
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="openCourseProperty(scope.row)"
                ><i class="el-icon-circle-check"></i> 启用
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="closeCourseProperty(scope.row)"
                ><i class="el-icon-circle-close"></i> 禁用
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page pull-right">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="新增课程属性名称"
      :visible.sync="coursePropertyDialog"
      width="500px"
    >
      <el-form
        :model="coursePropertyForm"
        ref="coursePropertyForm"
        :rules="rules"
        label-position="right"
        label-width="90px"
        inline-message
      >
        <el-row>
          <el-form-item label="属性名称" label-width="120px" prop="name">
            <el-input
              class="dialog_input_width"
              v-model="coursePropertyForm.name"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="课程名称" label-width="120px" prop="courseId">
            <el-select
              class="dialog_input_width"
              v-model="coursePropertyForm.courseId"
              filterable
              :remote-method="getCourses"
              remote
              clearable
              placeholder="请选择课程"
            >
              <el-option
                v-for="item in courseInfoSelect"
                :label="item.courseInfo"
                :value="item.courseId"
                :key="item.courseId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row class="margin_top_10 margin_left_120">
          <el-button type="primary" @click="submit('coursePropertyForm')"
            >保 存</el-button
          >
          <el-button @click="resetForm('coursePropertyForm')">重 置</el-button>
          <el-button @click="back('coursePropertyForm')" type="success"
            ><i class="el-icon-caret-left"></i> 返 回</el-button
          >
        </el-row>
      </el-form>
    </el-dialog>
  </section>
</template>

<script>
import { CORE_API, QUESTION_API } from "@/constants/constants";
import LinkTitlesCustom from "@/components/LinkTitlesCustom.vue";
export default {
  components: { LinkTitlesCustom },
  data() {
    return {
      formSearch: {
        name: "",
        courseId: ""
      },
      courseList: [],
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      coursePropertyForm: {
        name: "",
        courseId: "",
        courseCode: ""
      },
      coursePropertyDialog: false,
      selectedList: [],
      rules: {
        name: [{ required: true, message: "请输入属性名称", trigger: "blur" }],
        courseId: [
          { required: true, message: "请选择课程名称", trigger: "change" }
        ]
      }
    };
  },

  methods: {
    //查询所有课程属性
    searchCourProperty() {
      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.loading = false;
      });
    },
    //新增
    addCourseProperty() {
      this.coursePropertyDialog = true;
      this.coursePropertyForm.name = "";
      this.coursePropertyForm.courseId = "";
    },
    //重置
    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() {
      var selectedList = this.selectedList;
      if (selectedList.length === 0) {
        this.$notify({
          type: "error",
          message: "请选择要开启的课程属性"
        });
      } else {
        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() {
      var selectedList = this.selectedList;
      if (selectedList.length === 0) {
        this.$notify({
          type: "error",
          message: "请选择要禁用的课程属性"
        });
      } else {
        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) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.searchCourProperty();
    },
    //确定
    submit(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          for (let course of this.courseList) {
            if (course.id == this.coursePropertyForm.courseId) {
              this.coursePropertyForm.courseCode = course.code;
            }
          }
          this.$http
            .post(
              QUESTION_API + "/courseProperty/save",
              this.coursePropertyForm
            )
            .then(() => {
              this.$notify({
                message: "新增成功",
                type: "success"
              });
              this.coursePropertyDialog = false;
              this.searchCourProperty();
            })
            .catch(() => {
              this.$notify({
                type: "error",
                message: "课程属性名称重复,请重新命名"
              });
            });
        } else {
          return false;
        }
      });
    },
    getEnable(value) {
      if (value === true) {
        return "开启";
      } else {
        return "禁用";
      }
    },
    //查询所有课程
    getCourses(query) {
      query = query.trim();
      if (query) {
        if (!(query.indexOf("(") > -1 && query.indexOf(")") > -1)) {
          this.courseLoading = true;
          this.$http
            .get(CORE_API + "/course/query?name=" + query + "&enable=true")
            .then(response => {
              this.courseList = response.data;
              this.courseLoading = false;
            });
        }
      } else {
        this.courseList = [];
      }
    },
    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.searchCourProperty();
    },
    //查询单个课程
    getOneCourse(courseId) {
      if (courseId) {
        this.$http.get(CORE_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;
    }
  },
  computed: {
    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;
    }
  },
  watch: {
    $route: "initValue"
  },
  created() {
    this.initValue();
  }
};
</script>
<style scoped src="../styles/Common.css"></style>