<template>
  <div>
    <p class="sub_back" @click="handleBack">&#60;返回</p>
    <p class="sub_title">教师排班</p>
    <el-card class="account-container scheduling">
      <div class="control">
        <p class="control_name">{{termName}}-每日排班详情</p>
        <div>
          <el-button type="primary" @click="handleAdd" style="margin-right:20px;">新增</el-button>
        </div>
      </div>
      <div class="select_box">
        <p class="select_tag">日期：</p>
        <el-date-picker v-model="dayName" value-format="YYYY-MM-DD" type="date" placeholder="选择日期" :clearable="false" @change="dayNameChange">
        </el-date-picker>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%" stripe v-if="tableData.length>0">
        <el-table-column label="时间" align="center">
          <template #default="props">
            <p class="time">{{props.row.startTime}}-{{props.row.endTime}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="辅导类型" align="center">
        </el-table-column>
        <el-table-column prop="teacherName" label="辅导教师" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <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-dialog :title="editTitle" v-model="editBoxShow">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item label="辅导类型：" prop="type">
            <el-radio v-model="form.type" label="1">心理成长</el-radio>
            <el-radio v-model="form.type" label="2">生涯发展</el-radio>
          </el-form-item>
          <el-form-item label="辅导教师：" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择教师">
            <el-option v-for="item in teacherOptions" :key="item.userId" :label="item.name" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="预约时间：" prop="time">
            <el-time-picker is-range v-model="form.time" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" format='HH:mm' value-format='HH:mm'>
            </el-time-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>
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { formatTimeDay,deepClone } from '@/utils'
import download from 'downloadjs'
import axios from '@/utils/axios'
import Moment from 'moment'
export default {
  name: 'SchedulingDetail',
  setup () {
    const formRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const { termId, termName } = route.query

    const state = reactive({
      dayName: '',
      search: '',
      tableData: [],
      total: 0,
      currentPage: 1,
      loading: false,
      editBoxShow: false,//编辑框显示
      editTitle: '',
      form: {
        id: '0',
        recordId: '0',
        dayName: '',//日期
        type: '',//课程类别 1心理评测 2生涯指导
        startTime: '',
        endTime: '',
        time: '',
        teacherId: ''
      },
      rules: {
        type: [
          { required: 'true', message: '请选择课程', trigger: ['change'] }
        ],
        time: [
          { required: 'true', message: '请选择时间', trigger: ['change'] },
        ],
        teacherId: [
          { required: 'true', message: '请选择上课教师', trigger: ['change'] },
        ]
      },
      teacherOptions: [],
      uploadArr: [],//待保存的上传文件
    })
    onMounted(() => {
      // state.dayName = new Date()
      getTeacherList()
      state.dayName = Moment().format('YYYY-MM-DD');
      getArrangeSchedualDetail()
    })
    const dayNameChange = () => {
      getArrangeSchedualDetail()
    }
    // 每日排班详情
    const getArrangeSchedualDetail = () => {
      state.loading = true
      axios.post('/SchedualBooking/ArrangeSchedualDetail/List', {
        "TermId": termId,
        "PageIndex": state.currentPage,
        "PageSize": 1000,
        "RecordId": 0,
        "DayName": state.dayName,
        // "TeacherId": "1"
      }).then(res => {
        // console.log('每日排班详情:', res)
        let tableData = res.data;
        tableData = tableData.sort(compare)
        state.tableData = tableData
        state.total = res.count
        state.loading = false
      }).catch(err => {
        console.log('err', err)

      })
    }
    const getTeacherList = ()=>{
      axios.post('/User/Teacher/List').then(res => {
        // console.log('教师列表:', res)
        state.teacherOptions = res;
      })
    }
    // 搜索
    const searchChange = (e) => {
      getArrangeSchedualDetail()
    }
    // 新建
    const handleAdd = () => {
      state.editTitle = '新增' + state.dayName + '的课程';
      state.form = {
        id: '0',
        recordId: '0',
        dayName: '',//日期
        type: '',//课程类别 1心理评测 2生涯指导
        startTime: '',
        endTime: '',
        time: ['12:00','13:00'],
        teacherId: ''
      };

      state.editBoxShow = true
    }
    // 编辑修改
    const handleEdit = (e) => {
      let form = deepClone(e);
      form.time = [form.startTime,form.endTime];
      state.form = form;
      state.editTitle = '编辑' + state.dayName + '的课程';
      state.editBoxShow = true
    }
    // 删除
    const handleDel = (e) => {
      axios.delete('/SchedualBooking/ArrangeSchedualDetail', {
        params: {
          "id": e.id,
        }
      }).then(() => {
        ElMessage.success('删除成功')
        state.currentPage = 1;
        getArrangeSchedualDetail()
      })
    }
    // 新建或修改提交
    const submitForm = () => {
      formRef.value.validate((vaild) => {
        if (vaild) {
          if (state.form.id == 0) {
            // 新建
            axios.post('/SchedualBooking/ArrangeSchedualDetail', {
              "Id": '0',
              "TermId": termId,
              "Type": state.form.type,
              "DayName": state.dayName,
              "StartTime": state.form.time[0],
              "EndTime": state.form.time[1],
              "TeacherId": state.form.teacherId,
            }).then(() => {
              ElMessage.success('新建成功')
              state.editBoxShow = false
              getArrangeSchedualDetail()
            })
          } else {
            // 修改
            axios.put('/SchedualBooking/ArrangeSchedualDetail', {
              "Id": state.form.id,
              "RecordId": state.form.recordId,
              "Type": state.form.type,
              "DayName": state.dayName,
              "StartTime": state.form.time[0],
              "EndTime": state.form.time[1],
              "TeacherId": state.form.teacherId,
            }).then(() => {
              ElMessage.success('修改成功')
              state.editBoxShow = false
              getArrangeSchedualDetail()
            })
          }
        }
      })
    }
    // 页码改变时
    const handleCurrentChange = (e) => {
      state.currentPage = e;
      getArrangeSchedualDetail()
    }
    // 编辑窗点取消
    const hideEditBox = () => {
      state.editBoxShow = false
      resetForm()
    }

    // 重置表单
    const resetForm = () => {
      formRef.value.resetFields();
      state.form = {
        id: '0',
        recordId: '0',
        dayName: '',//日期
        type: '',//课程类别 1心理评测 2生涯指导
        startTime: '',
        endTime: '',
        time: '',
        teacherId: ''
      };
    }
    const compare = (obj1, obj2) => {
      var val1 = obj1.startTime;
      var val2 = obj2.startTime;
      if (val1 < val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    }
    const handleBack = () => {
      router.back()
    }
    return {
      ...toRefs(state),
      formRef,
      searchChange,
      handleAdd,
      handleEdit,
      handleDel,
      submitForm,
      handleCurrentChange,
      hideEditBox,
      formatTimeDay,
      termName,
      handleBack,
      dayNameChange
    }
  }
}
</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 {
  .select_box {
    margin-bottom: 40px;
    .select_tag {
      font-size: 16px;
      display: inline-block;
    }
  }
  .week_item {
    text-align: center;
    padding: 10px 0;
    position: relative;
    p {
      margin: 0;
    }
    .control_box {
      display: none;
      width: 100%;
      height: 100%;
      background: #f5f6fa;
      border-radius: 4px;
      border: 1px solid #3a84ff;
      box-sizing: border-box;
      position: absolute;
      top: 0;
      left: 0;
      a {
        display: block;
        width: 100%;
      }
    }
    &:hover {
      .control_box {
        display: flex;
        align-content: center;
        justify-content: center;
        flex-wrap: wrap;
      }
    }
  }
}
</style>