<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="70px"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="属性名称">
              <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"
                @focus="e => getCourses(e.target.value)"
              >
                <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="searchFrom"
                ><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>
        <div
          style="width: 100%; border-bottom: 1px solid #ddd; margin: 10px 0;"
        ></div>
        <el-row>
          <el-form-item class="pull-left">
            <span>批量操作：</span>
            <el-button
              size="small"
              type="success"
              @click="openCoursePropertys"
              :disabled="noBatchSelected"
              ><i class="el-icon-check"></i> 启用</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="closeCoursePropertys"
              :disabled="noBatchSelected"
              ><i class="el-icon-close"></i> 禁用</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>
      <div style="width: 100%;margin-bottom: 10px;"></div>
      <!-- 页面列表 -->
      <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 v-if="scope.row.enable">
              <el-tooltip
                class="item"
                effect="dark"
                content="启用"
                placement="left"
              >
                <i class="el-icon-success" style="color:green;"></i>
              </el-tooltip>
            </span>
            <span v-else>
              <el-tooltip
                class="item"
                effect="dark"
                content="禁用"
                placement="left"
              >
                <i class="el-icon-error" style="color:red;"></i>
              </el-tooltip>
            </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)"
                plain
                ><i class="el-icon-zoom-in"></i> 详情
              </el-button>
              <el-button
                v-if="!scope.row.enable"
                size="mini"
                type="primary"
                plain
                @click="openCourseProperty(scope.row)"
              >
                <i class="el-icon-check" aria-hidden="true"></i>启用
              </el-button>
              <el-button
                v-if="scope.row.enable"
                size="mini"
                type="danger"
                @click="closeCourseProperty(scope.row)"
              >
                <i class="el-icon-close" aria-hidden="true"></i>禁用
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page pull-right">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 300]"
          @size-change="handleSizeChange"
          layout="total, sizes, 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="请选择课程"
              @focus="e => getCourses(e.target.value)"
            >
              <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')"
            ><i class="el-icon-refresh"></i> 重 置</el-button
          >
          <el-button @click="back('coursePropertyForm')" type="primary"
            ><i class="el-icon-arrow-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: {
    //查询所有课程属性
    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 = "";
    },
    //重置
    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) {
      console.log(`当前页: ${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) {
          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;
        }
      });
    },
    //查询所有课程
    getCourses(query) {
      query = query.trim();
      this.courseLoading = true;
      this.$http
        .get(CORE_API + "/course/query?name=" + query + "&enable=true")
        .then(response => {
          this.courseList = response.data;
          this.courseLoading = 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(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;
    },
    noBatchSelected() {
      return this.selectedList.length === 0;
    }
  },
  watch: {
    $route: "initValue"
  },
  created() {
    this.initValue();
  }
};
</script>
<style scoped src="../styles/Common.css"></style>
