<template>
  <div class="app-container">
    <el-form ref="checkForm" :model="checkForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="姓名：">
        <el-input v-model="checkForm.userName" readonly></el-input>
      </el-form-item>
      <el-form-item label="部门：">
        <el-input v-model="checkForm.orgname" readonly></el-input>
      </el-form-item>
      <el-form-item label="月份：">
        <el-input v-model="checkForm.attMon" readonly></el-input>
      </el-form-item>
      <el-form-item label="加班天数：">
        <el-input v-model="overTimes" readonly></el-input>
      </el-form-item>
      <el-form-item label="请假天数：">
        <el-input v-model="leaveTimes" readonly></el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" icon="el-icon-close" size="mini" @click="closePage">关闭</el-button>
    <el-divider></el-divider>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="isEdit==1" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddEa"
                   v-hasPermi="['system:user:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="isEdit==1" type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple1"
                   @click="handleDeleteEa"
                   v-hasPermi="['system:user:remove']">删除
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="clockRecordListEa" stripe @selection-change="handleSelectionChangeEa">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="55" align="center"/>
      <el-table-column label="请假开始时间" align="center" prop="startTime"/>
      <el-table-column label="请假结束时间" align="center" prop="endTime"/>
      <el-table-column label="请假时长" align="center" prop="totalTime">
        <template slot-scope="scope">
          {{ scope.row.totalTime }}天
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks"/>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEditEa(scope.row)" v-hasPermi="['grade:monthRecord:edit']">修改
          </el-button>
          <el-button size="mini" type="text" @click="handleDeleteEa(scope.row)" v-hasPermi="['grade:monthRecord:submit']">删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <el-divider></el-divider>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="isEdit==1" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddOt"
                   v-hasPermi="['system:user:add']">新 增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="isEdit==1" type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple2"
                   @click="handleDeleteOt"
                   v-hasPermi="['system:user:remove']">删 除
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="clockRecordListOt" stripe @selection-change="handleSelectionChangeOt">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="55" align="center"/>
      <el-table-column label="加班开始时间" align="center" prop="startTime"/>
      <el-table-column label="加班结束时间" align="center" prop="endTime"/>
      <el-table-column label="加班时长" align="center" prop="totalTime">
        <template slot-scope="scope">
          {{ scope.row.totalTime }}时
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks"/>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEditOt(scope.row)" v-hasPermi="['grade:monthRecord:edit']">修改
          </el-button>
          <el-button size="mini" type="text" @click="handleDeleteOt(scope.row)" v-hasPermi="['grade:monthRecord:submit']">删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 新增或修改请假 -->
    <el-dialog :title="title" :visible.sync="openForEa" width="800px">
      <el-form ref="formEa" :rules="rulesEa" :model="formEa" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="请假开始时间" prop="startTime">
              <el-date-picker @change="leaveTime" v-model="formEa.startTime" value-format="yyyy-MM-dd" type="date"
                              :picker-options="pickerOptionsStart"
                              placeholder="选择日期">
              </el-date-picker>&nbsp;&nbsp;
            </el-form-item>
            <el-form-item label="" prop="startSort">
              <el-select @change="leaveTime" v-model="formEa.startSort" placeholder="请选择课程节次">
                <el-option v-for="dict in dict.type.course_arrange" :key="dict.value" :label="dict.label"
                           :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假结束时间" prop="endTime">
              <el-date-picker @change="leaveTime" v-model="formEa.endTime" value-format="yyyy-MM-dd" type="date"
                              :picker-options="pickerOptionsEnd"
                              placeholder="选择日期">
              </el-date-picker>&nbsp;&nbsp;
            </el-form-item>
            <el-form-item label="" prop="endSort">
              <el-select @change="leaveTime" v-model="formEa.endSort" placeholder="请选择课程节次">
                <el-option v-for="dict in dict.type.course_arrange" :key="dict.value" :label="dict.label"
                           :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="请假时长" prop="totalTime">
              <el-input :value="formEa.totalTime" clearable>
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 5}" v-model="formEa.remarks" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEaForm">确 定</el-button>
        <el-button @click="cancelEa">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 新增或修改加班 -->
    <el-dialog :title="title" :visible.sync="openForOt" width="800px">
      <el-form ref="formOt" :rules="rulesOt" :model="formOt" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="加班开始时间" prop="startTime">
              <el-date-picker @change="leaveTimeOt" v-model="formOt.startTime"

                              value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                              :picker-options="pickerOptionsStart2"
                              placeholder="选择日期">
              </el-date-picker>&nbsp;&nbsp;
            </el-form-item>
            <!--            <el-form-item label="" prop="startSort">-->
            <!--              <el-select @change="leaveTimeOt" v-model="formOt.startSort"-->
            <!--                         placeholder="请选择课程节次">-->
            <!--                <el-option v-for="dict in dict.type.course_arrange" :key="dict.value" :label="dict.label"-->
            <!--                           :value="dict.value">-->
            <!--                </el-option>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
          </el-col>
          <el-col :span="12">
            <el-form-item label="加班结束时间" prop="endTime">
              <el-date-picker @change="leaveTimeOt" v-model="formOt.endTime" value-format="yyyy-MM-dd HH:mm:ss"
                              type="datetime"
                              :picker-options="pickerOptionsEnd2"
                              placeholder="选择日期">
              </el-date-picker>&nbsp;&nbsp;&nbsp;&nbsp;
            </el-form-item>
            <!--            <el-form-item label="" prop="endSort">-->
            <!--              <el-select @change="leaveTimeOt" v-model="formOt.endSort" placeholder="请选择课程节次">-->
            <!--                <el-option v-for="dict in dict.type.course_arrange" :key="dict.value" :label="dict.label"-->
            <!--                           :value="dict.value">-->
            <!--                </el-option>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="加班时长" prop="totalTime">
              <el-input :value="formOt.totalTime">
                <template slot="append">时</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input type="textarea" style="width: 100%" :autosize="{ minRows: 3, maxRows: 5}" v-model="formOt.remarks"
                    clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOtForm">确 定</el-button>
        <el-button @click="cancelOt">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  checkRow,
  addRow,
  checkDeatil,
  editRow,
  delRow,
  addRowOt,
  checkDeatilOt,
  editRowOt,
  delRowOt,
  getOverTime,
  getLeaveTime
} from "@/api/smartSchool/gradeWork/monthRecord.js"
// import {getLeaveTime} from "@/api/smartSchool/personWork/leaveApply";
import {formatDate} from "@/utils";

export default {
  name: '',
  dicts: ['course_arrange'],
  components: {},
  props: {},


  data() {
    return {
      userId: "",
      deadlineTime: undefined,
      isEdit: 1,
      //当前登录人类型 0代表教工，1代表职工
      employeeType: "",
      // 模糊搜索
      queryParams: {},
      // 加载遮罩
      loading: true,
      // 请假记录列表
      clockRecordListEa: [],
      // 加班记录列表
      clockRecordListOt: [],
      // 查看表单
      checkForm: {},
      // 请假单个禁用
      multiple1: true,
      // 加班单个禁用
      multiple2: true,
      // 选中请假数组
      idEas: [],
      // 选中请假数组
      idOts: [],
      // 新增或修改请假对话框
      openForEa: false,
      // 新增或修改加班对话框
      openForOt: false,
      // 标题
      title: "",
      // 请假表单
      formEa: {
        startTime: '',
        startSort: '',
        endTime: '',
        endSort: '',
      },
      // 加班表单
      formOt: {
        startTime: '',
        startSort: '',
        endTime: '',
        endSort: '',
      },
      // 选择节数
      options: [{
        value: '1',
        label: '第1节'
      }, {
        value: '2',
        label: '第2节'
      }, {
        value: '3',
        label: '第3节'
      }, {
        value: '4',
        label: '第4节'
      }, {
        value: '5',
        label: '第5节'
      }, {
        value: '6',
        label: '第6节'
      }, {
        value: '7',
        label: '第7节'
      }, {
        value: '8',
        label: '第8节'
      }],
      value: '',
      // 请假表单验证
      rulesEa: {
        startTime: [{required: true, message: "请假开始日期不能为空", trigger: 'blur'}],
        startSort: [{required: true, message: "节数不能为空", trigger: ['change', 'blur']}],
        endTime: [{required: true, message: "请假结束日期不能为空", trigger: 'blur'}],
        endSort: [{required: true, message: "节数不能为空", trigger: ['change', 'blur']}],
      },
      // 请假表单验证
      rulesOt: {
        startTime: [{required: true, message: "请假开始日期不能为空", trigger: 'blur'}],
        startSort: [{required: true, message: "节数不能为空", trigger: ['change', 'blur']}],
        endTime: [{required: true, message: "请假结束日期不能为空", trigger: 'blur'}],
        endSort: [{required: true, message: "节数不能为空", trigger: ['change', 'blur']}],
      },


      pickerOptionsStart: {
        disabledDate: (time) => {
          let endDateVal = this.formEa.endTime;

          // if (endDateVal) {
          //   return (
          //     time.getTime() > new Date(endDateVal).getTime() + 1 * 24 * 60 * 60 * 1000
          //   );
          // }
          if (time.getTime() < new Date(this.checkForm.attMon).getTime() - 3600 * 24 * 1000) {
            return true;
          }
          if (time.getTime() > new Date(this.deadlineTime).getTime() - 3600 * 24 * 1000) {
            return true;
          }
          if (time.getTime() > new Date(endDateVal).getTime()) {
            return true;
          }
        },
      },
      pickerOptionsEnd: {
        disabledDate: (time) => {
          let beginDateVal = this.formEa.startTime;
          if (beginDateVal) {
            return (
              time.getTime() < new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000

            );
          }
        }
      },
      pickerOptionsStart2: {
        disabledDate: (time) => {
          let endDateVal = this.formOt.endTime;

          if (time.getTime() < new Date(this.checkForm.attMon).getTime() - 3600 * 24 * 1000) {
            return true;
          }
          if (time.getTime() > new Date(this.deadlineTime).getTime() - 3600 * 24 * 1000) {
            return true;
          }
          if (time.getTime() > new Date(endDateVal).getTime()) {
            return true;
          }
          // if (endDateVal) {
          //   return (
          //     time.getTime() > new Date(endDateVal).getTime() + 1 * 24 * 60 * 60 * 1000
          //   );
          // }
        },
      },
      pickerOptionsEnd2: {
        disabledDate: (time) => {
          let beginDateVal = this.formOt.startTime;
          if (beginDateVal) {
            return (
              time.getTime() < new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000

            );
          }
        }
      }


    };
  },
  watch: {},
  computed: {
    leaveTimes: {
      get() {
        let arr = this.clockRecordListEa.map(item => {
          return item.totalTime
        })
        return arr.reduce((pre, cur) => {
          return pre + cur
        }, 0)
      },
      set(value) {
      }
    },
    overTimes: {
      get() {
        let arr = this.clockRecordListOt.map(item => {
          return item.totalTime
        })
        return arr.reduce((pre, cur) => {
          return pre + cur
        }, 0)
      },
      set(value) {
      }
    },

  },
  methods: {
    // 从url获取信息
    getInfo() {
      this.checkForm.userName = this.$route.query.userName;
      this.checkForm.orgname = this.$route.query.orgname;
      this.checkForm.attMon = this.$route.query.attMon;
      this.userId = this.$route.query.userId;
      this.isEdit = this.$route.query.isEdit
      this.deadlineTime = new Date(this.checkForm.attMon);
      this.deadlineTime.setMonth(this.deadlineTime.getMonth() + 1);
    },
    // 获取列表
    getList() {
      this.loading = true;
      const attMonId = this.$route.query.attMonId;
      checkRow(attMonId).then(response => {
        this.clockRecordListEa = response.eaList;
        this.clockRecordListOt = response.otList;
        this.loading = false;
      }).catch(() => {

      })
    },
    // 关闭页面
    closePage() {
      // this.$router.push("/gradeWork/clockmanage/monthmanage")
      this.$tab.closeOpenPage({path: '/gradeWork/clockmanage/monthmanage'});
    },
    // 选中请假数组
    handleSelectionChangeEa(val) {
      this.idEas = val.map(item => item.id);
      this.multiple1 = !val.length;
    },
    // 选中加班数组
    handleSelectionChangeOt(val) {
      this.idOts = val.map(item => item.id);
      this.multiple2 = !val.length;
    },
    // 增加请假
    handleAddEa() {
      this.formEa = {};
      this.title = "增加请假";
      this.openForEa = true;
    },
    leaveTime() {
      //0代表教工，1代表职工
      // if (this.employeeType == 0) {
      if (this.formEa.startTime && this.formEa.endTime && this.formEa.startSort && this.formEa.endSort) {
        const leaveTime0 = {
          startTime: formatDate(this.formEa.startTime),
          endTime: formatDate(this.formEa.endTime),
          startSort: this.formEa.startSort,
          endSort: this.formEa.endSort,
          applyType: 0,
        }
        getLeaveTime(leaveTime0).then((res) => {
          if (res.code == 200) {
            this.$set(this.formEa, 'dayCourse', res.dayCourse)
            this.$set(this.formEa, 'totalTime', res.data)
          }
        })
      }
      // } else {
      //   if (this.formEa.startTime && this.formEa.endTime) {
      //     const leaveTime1 = {
      //       startTime: formatDate(this.formEa.startTime),
      //       endTime: formatDate(this.formEa.endTime)
      //     }
      //     getLeaveTime(leaveTime1).then((res) => {
      //       if (res.code == 200) {
      //         this.$set(this.formEa, 'totalTime', res.data)
      //       }
      //     })
      //   }
      // }
    },
    leaveTimeOt() {
      //0代表教工，1代表职工
      // if (this.employeeType == 0) {
      if (this.formOt.startTime && this.formOt.endTime) {
        const leaveTime0 = {
          startTime: formatDate(this.formOt.startTime),
          endTime: formatDate(this.formOt.endTime),
          userId: this.userId,
          // startSort: this.formOt.startSort,
          // endSort: this.formOt.endSort,
          userType: 0,
        }

        getOverTime(leaveTime0).then((res) => {
          if (res.code == 200) {
            this.$set(this.formOt, 'dayCourse', res.dayCourse)
            this.$set(this.formOt, 'totalTime', res.data)
          }
        })
      }
      // } else {
      //   if (this.formOt.startTime && this.formOt.endTime) {
      //     const leaveTime1 = {
      //       startTime: formatDate(this.formOt.startTime),
      //       endTime: formatDate(this.formOt.endTime)
      //     }
      //     getLeaveTime(leaveTime1).then((res) => {
      //       if (res.code == 200) {
      //         this.$set(this.formOt, 'totalTime', res.data)
      //       }
      //     })
      //   }
      // }
    },
    // 删除请假
    handleDeleteEa(row) {
      const ids = row.id || this.idEas;
      this.$modal.confirm('是否确认删除？').then(function () {
        return delRow(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 修改请假
    handleEditEa(row) {
      this.title = "修改请假";
      this.openForEa = true;
      const id = row.id;
      checkDeatil(id).then(response => {
        this.formEa = response.data;
      }).catch(() => {
      })
    },
    // 提交请假
    submitEaForm() {
      const attMonId = this.$route.query.attMonId;
      this.formEa.userId = this.$route.query.userId;
      this.formEa.userName = this.$route.query.userName;
      this.formEa.userType = this.$route.query.userType;
      this.formEa.startTime = formatDate(this.formEa.startTime)
      this.formEa.endTime = formatDate(this.formEa.endTime)

      this.$refs["formEa"].validate(valid => {
        if (valid) {
          if (this.formEa.id != undefined) {
            editRow(this.formEa).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openForEa = false;
              this.getList();
            });
          } else {
            addRow(this.formEa, attMonId).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openForEa = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消请假
    cancelEa() {
      this.formEa = {};
      this.openForEa = false;
    },
    // 增加加班
    handleAddOt() {
      this.formOt = {};
      this.title = "增加加班信息"
      this.openForOt = true;
    },
    // 提交加班
    submitOtForm() {
      const attMonId = this.$route.query.attMonId;
      this.formOt.userId = this.$route.query.userId;
      this.formOt.userName = this.$route.query.userName;
      this.formOt.userType = this.$route.query.userType;
      this.formOt.startTime = formatDate(this.formOt.startTime)
      this.formOt.endTime = formatDate(this.formOt.endTime)
      this.$refs["formOt"].validate(valid => {
        if (valid) {
          if (this.formOt.id != undefined) {
            editRowOt(this.formOt).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openForOt = false;
              this.getList();
            });
          } else {
            addRowOt(this.formOt, attMonId).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openForOt = false;
              this.getList();
            });
          }
        }
      });
    },
    // 删除加班
    handleDeleteOt(row) {
      const ids = row.id || this.idOts;
      this.$modal.confirm('是否确认删除？').then(function () {
        return delRowOt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 修改加班
    handleEditOt(row) {
      this.title = "修改加班信息";
      this.openForOt = true;
      checkDeatilOt(row.id).then(response => {
        this.formOt = response.data;
      }).catch(() => {
      })

    },
    // 取消加班
    cancelOt() {
      this.formOt = {};
      this.openForOt = false;
    },
  },
  created() {
    this.getList();
    this.getInfo();
    this.employeeType = this.$store.state.user.employeeType;
  },
  mounted() {
  }
};
</script>
<style scoped>
</style>
