<template>
  <div class="app-container">
    <!-- 学年/学期 -->
    <!-- 这里的@selecrYear是接收timeSelect提交的事件 -->
    <time-select
      style="margin-top: 20px"
      ref="timeSelect"
      @selectYear="getList()"
      @selectSemester="getList()"
      :flag="true"
    ></time-select>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="实验室名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入实验室名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实验室位置">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入实验室位置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实验条件">
        <el-input
          v-model="queryParams.requirement"
          placeholder="请输入实验条件"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :disabled="labList.length == 0"
          >导出所有</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="labList">
      <el-table-column
        label="实验室名称"
        align="center"
        prop="labName"
        show-overflow-tooltip
      />
      <el-table-column label="实验室位置" align="center" prop="location" />
      <el-table-column label="容纳人数" align="center" prop="capacity" />
      <el-table-column
        label="实验条件"
        align="center"
        prop="requirement"
        show-overflow-tooltip
      />
      <el-table-column label="管理员名称" align="center" prop="userName">
        <template slot-scope="scope">
          <el-popover placement="top-start" trigger="hover">
            <p>电话号码： {{ scope.row.phoneNumber }}</p>
            <p>电子邮箱： {{ scope.row.email }}</p>
            <p v-if="scope.row.office != null">
              办 公 室： {{ scope.row.office }}
            </p>
            <div slot="reference" class="name-wrapper">
              {{ scope.row.userName }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        label="所属学院"
        align="center"
        prop="deptName"
        show-overflow-tooltip
      />
      <el-table-column
        label="实验室备注"
        align="center"
        prop="remarks"
        show-overflow-tooltip
      />
      <!-- <el-table-column label="实验室备注" align="center" prop="remark" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleApply(scope.row)"
            >申请</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改实验室信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="courseOpen"
      append-to-body
      @close="handleClose"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :inline="true"
        class="demo-form-inline"
        label-width="100px"
      >
        <el-form-item label="课程名称" prop="courseId">
          <el-select
            style="width: 206.4px"
            v-model="form.courseId"
            placeholder="请选择"
            @change="handleCourse()"
          >
            <el-option
              v-for="item in courseList"
              :key="item.courseId"
              :label="item.courseName"
              :value="item.courseId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验室名称" prop="labName">
          <el-input v-model="form.labName" :disabled="true" />
        </el-form-item>
        <el-form-item label="实验室位置" prop="location">
          <el-input :disabled="true" v-model="form.location" />
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input :disabled="true" v-model="form.userName" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input :disabled="true" v-model="form.phoneNumber" />
        </el-form-item>
        <el-form-item label="使用班级">
          <el-input :disabled="true" v-model="form.className" />
        </el-form-item>

        <el-form-item label="班级人数" prop="number">
          <el-input :disabled="true" v-model="form.number" width="50px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="courseSubmitClick"
          v-if="isAllowApply == 1"
          >填写申请时间段</el-button
        >
        <el-button type="primary" @click="courseSubmitClick" v-else disabled
          >填写申请时间段</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="title"
      :visible.sync="timetableOpen"
      append-to-body
      width="85%"
    >
      <tb-course
        ref="tbCourse"
        table-label="选择相应的位置确认时间段"
        label="选择相应的位置确认时间段"
        @closeDialog="timetableOpen = false"
      ></tb-course>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { bookLabList, bookLabExport } from "@/api/labbooking/lab";

import { mapGetters } from "vuex";
import tbCourse from "../../components/tbCourseDialog";
import { getMyCourse } from "@/api/labbooking/course";
import timeSelect from "../../components/timeSelect";

export default {
  name: "Lab",
  components: { tbCourse, timeSelect },
  computed: {
    ...mapGetters(["nickName", "phoneNumber"]),
  },
  data() {
    var validateNumber = (rule, value, callback) => {
      if (value > this.form.capacity) {
        this.isAllowApply = 0;
        callback(new Error("该实验室无法容纳"));
      } else {
        this.isAllowApply = 1;
        callback();
      }
    };
    return {
      //"填写申请时间段"按钮禁用
      isAllowApply: 0,
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      labList: [
        {
          id: 1,
          labName: "实验室名称",
          location: "位置",
          capacity: 50,
          requirement: "软件",
          userId: 1,
          userName: "叶子豪",
          email: "497875761@qq.com",
          phoneNumber: "138415312",
          office: "办公1楼",
          remarks: "备注备注备注备注备注备注备注备注备注",
        },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      courseOpen: false,
      timetableOpen: false,
      // 是否开启实验室预约字典
      statusOptions: [],
      // 创建时间时间范围
      daterangeGmtCreate: [],
      // 更新时间时间范围
      daterangeGmtModified: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "",
        location: "",
        requirement: "",
      },

      courseList: [
        // {
        //   courseId: 1,
        //   courseName: "课程名1",
        //   className: "18软件工程1班",
        //   number: 45,
        // },
        // {
        //   courseId: 2,
        //   courseName: "课程名2",
        //   className: "18软件工程2班",
        //   number: 461010,
        // },
      ],

      form: {
        labId: null,
        courseId: null,
        courseName: null,
        location: null,
        labName: "",
        userName: null,
        phoneNumber: null,
        className: null,
        number: null,
        capacity: null,
      },
      // 表单校验
      rules: {
        courseId: [
          { required: true, message: "请选择课程名称", trigger: "change" },
        ],
        number: [
          { required: true, validator: validateNumber, trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("lms_lab_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getCourseList();
  },
  methods: {
    getCourseList() {
      getMyCourse().then((res) => {
        // console.log(res.data); //回显个人课程信息
        this.courseList = res.data;
      });
    },

    /** 查询实验室信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeGmtCreate && "" != this.daterangeGmtCreate) {
        this.queryParams.params["beginGmtCreate"] = this.daterangeGmtCreate[0];
        this.queryParams.params["endGmtCreate"] = this.daterangeGmtCreate[1];
      }
      if (
        null != this.daterangeGmtModified &&
        "" != this.daterangeGmtModified
      ) {
        this.queryParams.params["beginGmtModified"] =
          this.daterangeGmtModified[0];
        this.queryParams.params["endGmtModified"] =
          this.daterangeGmtModified[1];
      }
      bookLabList(this.queryParams).then((response) => {
        this.labList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 是否开启实验室预约字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },

    // "填写申请时间段"按钮触发
    courseSubmitClick() {
      //先校验一下
      this.$refs["form"].validate((valid) => {
        if (valid) {
          for (let i in this.courseList) {
            if (this.courseList[i].courseId == this.form.courseId) {
              this.form.courseName = this.courseList[i].courseName;
            }
          }
          this.title =
            "实验室位置：" +
            this.form.location +
            " 课程名：" +
            this.form.courseName;
          this.$nextTick(() => {
            //解决this.$refs获取为undefined问题，等页面渲染完后再给子组件赋值
            this.$refs.tbCourse.labId = this.form.labId;
            this.$refs.tbCourse.submitData.courseId = this.form.courseId;
            this.$refs.tbCourse.submitData.email = this.form.email;
            let year = this.$refs.timeSelect.year;
            let term = this.$refs.timeSelect.semester;
            this.$refs.tbCourse.year = year;
            this.$refs.tbCourse.term = term;
            this.$refs.tbCourse.getTableData(this.form.labId, year, term);
          });

          this.courseOpen = false;
          this.timetableOpen = true;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.courseOpen = false;
      this.timetableOpen = false;
      this.$refs.form.clearValidate();
      this.isAllowApply = 1;
    },
    handleClose() {
      this.$refs.form.clearValidate();
      this.isAllowApply = 1;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeGmtCreate = [];
      this.daterangeGmtModified = [];
      this.queryParams = {};
      this.handleQuery();
    },

    /** 申请按钮操作 */
    handleApply(row) {
      this.courseOpen = true;
      this.title = "请填写以下申请信息";
      this.form.labId = row.id;
      this.form.labName = row.labName;
      this.form.location = row.location;
      this.form.userName = this.nickName;
      this.form.phoneNumber = this.phoneNumber;
      this.form.email = row.email;
      this.form.capacity = row.capacity;
    },

    // 选课程后触发
    handleCourse() {
      for (var i = 0; i < this.courseList.length; i++) {
        if (this.form.courseId == this.courseList[i].courseId) {
          this.form.className = this.courseList[i].className;
          this.form.number = this.courseList[i].number;
        }
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有实验室信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return bookLabExport(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>