<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" size="medium" :rules="rulesEa" :model="formEa" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="请假开始时间" prop="startTime">
              <el-date-picker @change="leaveTime" style="width: 100%" v-model="formEa.startTime" type="datetime"
                              :picker-options="pickerOptionsStart"
                              placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假结束时间" prop="endTime">
              <el-date-picker @change="leaveTime" style="width: 100%" v-model="formEa.endTime" type="datetime"
                              :picker-options="pickerOptionsEnd"

                              placeholder="选择日期时间"></el-date-picker>
            </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}" style="width: 100%" 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" :picker-options="pickerOptionsStart2" v-model="formOt.startTime"
                              type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加班结束时间" prop="endTime">
              <el-date-picker @change="leaveTimeOt" :picker-options="pickerOptionsEnd2" v-model="formOt.endTime"
                              type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="加班时长" prop="totalTime">
              <el-input :value="formOt.totalTime" style="width: 100%">
                <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="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/officialWork/monthRecord.js"
// import {getLeaveTime} from "@/api/smartSchool/personWork/leaveApply";
import {formatDate} from "@/utils";

export default {
  name: '',
  dicts: ['course_num'],
  components: {},
  props: {},
  created() {
    this.getList();
    this.getInfo();
    this.employeeType = this.$store.state.user.employeeType;
  },
  data() {
    return {
      isEdit: "",
      deadlineTime: undefined,
      //当前登录人类型 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 (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() - 3600 * 24 * 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;
          }
        }

        // disabledDate: (time) => {
        //   let endDateVal = this.formOt.endTime;
        //   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() - 3600 * 24 * 1000
            );
          }
        }
      },
    };
  },
  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.userId = this.$route.query.userId;
      this.checkForm.orgname = this.$route.query.orgname;
      this.checkForm.attMon = this.$route.query.attMon;
      this.checkForm.attEa = this.$route.query.attEa;
      this.checkForm.attOt = this.$route.query.attOt;
      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.$tab.closeOpenPage({path: '/officialwork/clockmanage/clickmon'});
    },
    // 选中请假数组
    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.$nextTick(() => {
        this.$refs.formEa.clearValidate();
      })
      this.title = "请假新增";
      this.openForEa = true;
      // this.formEa.startTime = new Date(this.checkForm.attMon)
    },
    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,
      //     }
      //     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),
          applyType: 1,
        }
        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 && this.formOt.startSort && this.formOt.endSort) {
      //     const leaveTime0 = {
      //       startTime: formatDate(this.formOt.startTime),
      //       endTime: formatDate(this.formOt.endTime),
      //       startSort: this.formOt.startSort,
      //       endSort: this.formOt.endSort,
      //     }
      //     getLeaveTime(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),
          userType: 1,
          userId: this.userId,
        }
        getOverTime(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.$nextTick(() => {
        this.$refs.formOt.clearValidate();
      })
      // this.formOt.startTime = this.checkForm.attMon
      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;
    },
  },


};
</script>
<style scoped>
</style>
