<template>
  <el-card class="account-container scheduling">
    <div class="control">
      <p class="control_name">学期管理</p>
      <div>
        <el-button type="primary" @click="handleAdd" style="margin-right:20px;">新增</el-button>
        <!-- <el-input placeholder="搜索" v-model="search" clearable prefix-icon="el-icon-search" @change="searchChange">
          </el-input> -->
      </div>
    </div>
    <el-table v-loading="loading" :data="tableData" style="width: 100%" stripe v-if="tableData.length>0">
      <el-table-column prop="name" label="学期" align="center">
      </el-table-column>
      <el-table-column label="开始时间" align="center">
        <template #default="props">
          <p class="time">{{props.row.startTime}}</p>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center">
        <template #default="props">
          <p class="time">{{props.row.endTime}}</p>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <a @click="handleScheduling(scope.row)" style="cursor: pointer; margin-right: 10px">排班管理</a>
          <a @click="handleEdit(scope.row)" style="cursor: pointer; margin-right: 10px">修改</a>
          <el-popconfirm title="确定删除？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDel(scope.row)">
            <template #reference>
              <a style="cursor: pointer; margin-right: 10px">删除</a>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-empty description="暂无内容" v-if="tableData.length==0"></el-empty>
    <el-pagination :hide-on-single-page="total<=10" background layout="prev, pager, next" v-model="currentPage" :total="total" @current-change="handleCurrentChange">
    </el-pagination>
    <el-dialog :title="editTitle" v-model="editBoxShow">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="学期名称：" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="学期时间：" prop="time">
          <el-date-picker v-model="form.time"  format='YYYY-MM-DD' value-format="YYYY-MM-DD" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hideEditBox">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {deepClone } from '@/utils'
import axios from '@/utils/axios'
import Moment from 'moment'
export default {
  name: 'Term',
  setup () {
    const formRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const urlReg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;

    const state = reactive({
      search: '',
      tableData: [],
      total: 0,
      currentPage: 1,
      loading: false,
      editBoxShow: false,//编辑框显示
      editTitle: '',
      form: {
        id: '0',
        name: '',
        startTime: '',
        endTime: '',
        time: ''
      },
      rules: {
        name: [
          { required: 'true', message: '学期名称不能为空', trigger: ['change'] }
        ],
        time: [
          { required: 'true', message: '请选择时间', trigger: ['change'] },
        ]
      },
    })
    onMounted(() => {
      getArrangeSchedualTerm()
    })
    // 学期列表
    const getArrangeSchedualTerm = () => {
      state.loading = true
      axios.post('/SchedualBooking/ArrangeSchedualTerm/List', {
        "PageIndex": state.currentPage,
        "PageSize": 10
      }).then(res => {
        // console.log('学期列表:', res)

        let tableData = res.data;
        for (let i in tableData) {
          tableData[i].startTime = Moment(tableData[i].startTime).format('YYYY-MM-DD')
          tableData[i].endTime = Moment(tableData[i].endTime).format('YYYY-MM-DD')
          tableData[i].time = [tableData[i].startTime, tableData[i].endTime]
        }
        state.tableData = tableData
        state.total = res.count
        state.loading = false
      }).catch(err => {
        console.log('err', err)

      })
    }
    // 搜索
    const searchChange = (e) => {
      getArrangeSchedualTerm()
    }
    // 新建
    const handleAdd = () => {
      state.editTitle = '新建';
      state.form = {
        id: '0',
        title: '',
        url: ''
      };

      state.editBoxShow = true
    }
    // 编辑修改
    const handleEdit = (e) => {
      let form = deepClone(e);
      form.time = [form.startTime,form.endTime];
      state.form = form;
      state.editTitle = '编辑';
      state.editBoxShow = true
    }
    // 删除
    const handleDel = (e) => {
      axios.delete('/SchedualBooking/ArrangeSchedualTerm', {
        params: {
          "id": e.id,
        }
      }).then(() => {
        ElMessage.success('删除成功')
        state.currentPage = 1;
        getArrangeSchedualTerm()
      })
    }
    // 新建或修改提交
    const submitForm = () => {
      formRef.value.validate((vaild) => {
        if (vaild) {
          if (state.form.id == 0) {
            // 新建
            axios.post('/SchedualBooking/ArrangeSchedualTerm', {
              "Id": '0',
              Name: state.form.name,
              StartTime: state.form.time[0],
              EndTime: state.form.time[1]
            }).then(() => {
              ElMessage.success('新建成功')
              state.editBoxShow = false
              getArrangeSchedualTerm()
            })
          } else {
            // 修改
            axios.put('/SchedualBooking/ArrangeSchedualTerm', {
              "Id": state.form.id,
              Name: state.form.name,
              StartTime: state.form.time[0],
              EndTime: state.form.time[1]
            }).then(() => {
              ElMessage.success('修改成功')
              state.editBoxShow = false
              getArrangeSchedualTerm()
            })
          }
        }
      })
    }
    // 页码改变时
    const handleCurrentChange = (e) => {
      state.currentPage = e;
      getArrangeSchedualTerm()
    }
    // 编辑窗点取消
    const hideEditBox = () => {
      state.editBoxShow = false
      resetForm()
    }
    // 点击进入排班
    const handleScheduling = (e) => {
      router.push({ path: '/scheduling', query: { termId: e.id, termName: e.name } })
    }
    // 重置表单
    const resetForm = () => {
      formRef.value.resetFields();
      state.form = {
        id: '0',
        name: '',
        startTime: '',
        endTime: '',
        time: ''
      };
    }
    return {
      ...toRefs(state),
      formRef,
      searchChange,
      handleAdd,
      handleEdit,
      handleDel,
      handleScheduling,
      submitForm,
      handleCurrentChange,
      hideEditBox,
    }
  }
}
</script>
<style lang="scss" scoped>
.control {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .control_name {
    font-size: 23px;
    font-weight: bold;
  }
  .el-input {
    width: 300px;
  }
}
.scheduling {
  background: #fff;
  padding: 0 20px;
  padding-bottom: 40px;
  // position: relative;
  .iframe_mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    position: absolute;
    top: 0;
    left: 0;
    z-index: 99;
    iframe {
      width: 70%;
      height: 70%;
      background: #fff;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>