<template>
  <el-card class="account-container scheduling">
    <img class="edge" src="@/assets/edge2.png" alt="">
    <div class="control">
      <p class="control_name">{{termName}}-排班管理</p>
      <div>
        <el-button type="primary" @click="handleDownload" style="margin-right:20px;">排班模板导出</el-button>
        <el-button type="primary" @click="uploadShow=true" style="margin-right:20px;">导入排班</el-button>
        <el-button type="primary" @click="handleDetail" style="margin-right:20px;">每日排班详情</el-button>

        <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: 80%" stripe v-if="tableData.length>0">
      <el-table-column label="时间" align="center" min-width="110px">
        <template #default="props">
          <p class="time">{{props.row.timeSlot}}</p>
        </template>
      </el-table-column>
      <el-table-column :label="week" v-for="(week,index) in ['星期一','星期二','星期三','星期四','星期五','星期六','星期日']" :key="index" align="center">
        <template #default="props">
          <template v-for="(item,index2) in props.row.children" :key="index2">
            <div class="week_item" v-if="week==item.dayName">
              <p>{{item.typeName}}</p>
              <p>{{item.teacherName}}</p>
              <div class="control_box">
                <a @click="handleEdit(item)" style="cursor: pointer;">修改</a>
                <el-popconfirm title="确定删除？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDel(item)">
                  <template #reference>
                    <a style="cursor: pointer;margin-top:4px;">删除</a>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-empty description="暂无内容" v-if="tableData.length==0" style="width:80%"></el-empty>
    <el-dialog :title="editTitle" v-model="editBoxShow">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="星期：" prop="dayName">
          <el-radio v-model="form.dayName" label="星期一">星期一</el-radio>
          <el-radio v-model="form.dayName" label="星期二">星期二</el-radio>
          <el-radio v-model="form.dayName" label="星期三">星期三</el-radio>
          <el-radio v-model="form.dayName" label="星期四">星期四</el-radio>
          <el-radio v-model="form.dayName" label="星期五">星期五</el-radio>
          <el-radio v-model="form.dayName" label="星期六">星期六</el-radio>
          <el-radio v-model="form.dayName" label="星期日">星期日</el-radio>
        </el-form-item>
        <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-dialog title="排班导入" v-model="uploadShow">
      <el-upload class="uploader" action="" :http-request="upload" :show-file-list="false">
        <i v-if="uploadArr.length>0" class="el-icon-document-checked uploader-icon" style="border-color:#67c23a;color:#67c23a;"></i>
        <i v-else class="el-icon-plus uploader-icon"></i>
        <template #tip>
          <div class="el-upload__tip">上传文件</div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hideEditBox">取 消</el-button>
          <el-button type="primary" @click="submitUpload">确 定</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 { formatTimeDay,deepClone } from '@/utils'
import download from 'downloadjs'
import axios from '@/utils/axios'
export default {
  name: 'Scheduling',
  setup () {
    const formRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const { termId, termName } = route.query

    const state = reactive({
      search: '',
      tableData: [],
      total: 0,
      currentPage: 1,
      loading: false,
      editBoxShow: false,//编辑框显示
      editTitle: '',
      form: {
        id: '0',
        dayName: '',//星期
        type: '',//课程类别 1心理评测 2生涯指导
        startTime: '',
        endTime: '',
        time: '',
        teacherId: ''
      },
      defaultTime: new Date('2021-08-07 12:00:00'),
      rules: {
        dayName: [
          { required: 'true', message: '请选择星期', trigger: ['change'] }
        ],
        type: [
          { required: 'true', message: '请选择课程', trigger: ['change'] }
        ],
        time: [
          { required: 'true', message: '请选择时间', trigger: ['change'] },
        ],
        teacherId: [
          { required: 'true', message: '请选择上课教师', trigger: ['change'] },
        ]
      },
      teacherOptions: [],
      uploadShow: false,//导入模板弹出框
      uploadArr: [],//待保存的上传文件
    })
    onMounted(() => {
      getArrangeSchedualRecord()
      getTeacherList()
    })
    // 星期
    const getArrangeSchedualRecord = () => {
      state.loading = true
      axios.post('/SchedualBooking/ArrangeSchedualRecord/List', {
        "TermId": termId,
        "PageIndex": state.currentPage,
        "PageSize": 1000
      }).then(res => {
        // console.log('星期:', res)
        let tableData = res.data;
        for (let i in tableData) {
          tableData[i].time = [tableData[i].startTime, tableData[i].endTime]
        }
        let timeArr = [];
        // 创建一个时间段数组
        for (let i in tableData) {
          timeArr.push({
            timeSlot: `${tableData[i].startTime}-${tableData[i].endTime}`,
            children: []
          })
        }
        // 对时间段去重
        timeArr = unique(timeArr)
        // timeArr = timeArr.sort(compare)
        console.log(timeArr)
        // 往时间段内添加对应时间数据
        for (let i in timeArr) {
          for (let j in tableData) {
            if (timeArr[i].timeSlot == `${tableData[j].startTime}-${tableData[j].endTime}`) {
              timeArr[i].children.push(tableData[j])
            }
          }
        }
        // console.log(timeArr)
        state.tableData = timeArr
        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) => {
      getArrangeSchedualRecord()
    }
    // 新建
    const handleAdd = () => {
      state.editTitle = '新建';
      state.form = {
        id: '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.editBoxShow = true
    }
    // 删除
    const handleDel = (e) => {
      axios.delete('/SchedualBooking/ArrangeSchedualRecord', {
        params: {
          "id": e.id,
        }
      }).then(() => {
        ElMessage.success('删除成功')
        state.currentPage = 1;
        getArrangeSchedualRecord()
      })
    }
    // 新建或修改提交
    const submitForm = () => {
      formRef.value.validate((vaild) => {
        if (vaild) {
          if (state.form.id == 0) {
            // 新建
            axios.post('/SchedualBooking/ArrangeSchedualRecord', {
              "Id": '0',
              "TermId": termId,
              "Type": state.form.type,
              "DayName": state.form.dayName,
              "StartTime": state.form.time[0],
              "EndTime": state.form.time[1],
              "TeacherId": state.form.teacherId,
            }).then(() => {
              ElMessage.success('新建成功')
              state.editBoxShow = false
              getArrangeSchedualRecord()
            })
          } else {
            // 修改
            axios.put('/SchedualBooking/ArrangeSchedualRecord', {
              "Id": state.form.id,
              "TermId": termId,
              "Type": state.form.type,
              "DayName": state.form.dayName,
              "StartTime": state.form.time[0],
              "EndTime": state.form.time[1],
              "TeacherId": state.form.teacherId,
            }).then(() => {
              ElMessage.success('修改成功')
              state.editBoxShow = false
              getArrangeSchedualRecord()
            })
          }
        }
      })
    }
    // 页码改变时
    const handleCurrentChange = (e) => {
      state.currentPage = e;
      getArrangeSchedualRecord()
    }
    // 编辑窗点取消
    const hideEditBox = () => {
      state.editBoxShow = false
      state.uploadShow = false
      resetForm()
    }
    // 点击查看
    const handleView = (e) => {
      // router.push({ path: '/study_detailstudy_detail', query: { seriesId: item.id, seriesName: item.seriesName } })
    }
    // 重置表单
    const resetForm = () => {
      formRef.value.resetFields();
      state.form = {
        id: '0',
        dayName: '',//星期
        type: '',//课程类别 1心理评测 2生涯指导
        startTime: '',
        endTime: '',
        time: '',
        teacherId: ''
      };
    }
    // 下载模板
    const handleDownload = () => {
      axios.post('/Download/ArrangeFile', {}, { responseType: 'blob' },).then(res => {
        var blob = new Blob([res]);
        download(blob, '排班.xlsx')
      })
    }
    // 上传
    const upload = (param) => {
      console.log(param)
      const formData = new FormData()
      formData.append('file', param.file)
      axios.post('/Upload/ArrangeSchedualRecordFile/List', formData, { headers: { "Content-Type": "multipart/form-data" } }).then(res => {
        state.uploadArr = res
      })
    }
    // 保存上传文件
    const submitUpload = () => {
      if (state.uploadArr.length > 0) {
        let uploadArr = state.uploadArr;
        console.log('待保存原始数据：', uploadArr)
        for (let i in uploadArr) {
          uploadArr[i].TermId = termId
        }
        console.log('待保存数据：', uploadArr)
        axios.post('/SchedualBooking/ArrangeSchedualRecordBatch', uploadArr).then(() => {
          ElMessage.success('导入成功')
          state.uploadShow = false
          state.uploadArr = []
        })
      } else {
        ElMessage.error('文件未上传，或文件中无有效数据')
      }
    }
    const unique = (arr) => {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.timeSlot) && res.set(arr.timeSlot, 1))
    }
    const compare = (obj1, obj2) => {
      var val1 = obj1.timeSlot.split('-')[0];
      var val2 = obj2.timeSlot.split('-')[0];
      if (val1 < val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    }
    // 点击进入每日排班详情
    const handleDetail = (e) => {
      router.push({ path: '/scheduling_detail', query: { termId: termId, termName: termName } })
    }
    return {
      ...toRefs(state),
      formRef,
      searchChange,
      handleAdd,
      handleEdit,
      handleDel,
      handleView,
      submitForm,
      handleCurrentChange,
      hideEditBox,
      formatTimeDay,
      termName,
      handleDownload,
      submitUpload,
      upload,
      handleDetail
    }
  }
}
</script>
<style lang="scss" scoped>
.account-container {
  position: relative;
  min-height: 500px;
}
.edge {
  width: 289px;
  position: absolute;
  bottom: 0;
  right: 16px;
  z-index: 0;
}
.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;
  .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;
      }
    }
  }
  .uploader {
    margin-bottom: 50px;
  }
  .uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .el-upload__tip {
    display: inline-block;
    font-size: 16px;
    color: #999;
    margin-left: 50px;
  }
}
</style>