<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      老师考勤列表
      <filter-search
        @reload="reloadSearch"
        :keys="['attendanceStatus', 'visitFlag']"
        :moreKeys="['start', 'end', 'organId']"
      />
    </h2>
    <div class="m-core">
      <save-form
        :inline="true"
        @submit="search"
        @reset="onReSet"
        ref="searchForm"
        :model="searchForm"
      >
        <el-form-item prop="search">
          <el-input
            v-model.trim="searchForm.search"
            clearable
            @keyup.enter.native="search"
            placeholder="课程编号/课程名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="organId">
          <el-select
            class="multiple"
            v-model.trim="searchForm.organId"
            filterable
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="courseScheduleType">
          <el-select
            v-model.trim="searchForm.courseScheduleType"
            clearable
            placeholder="请选择课程类型"
          >
            <el-option
              v-for="(item, index) in courseType"
              :key="index"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="jobNature">
          <el-select
            v-model.trim="searchForm.jobNature"
            filterable
            clearable
            placeholder="工作类型"
          >
            <el-option
              v-for="item in jobNature"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="signInStatus">
          <el-select
            v-model.trim="searchForm.signInStatus"
            clearable
            placeholder="签到状态"
          >
            <el-option :value="1" label="正常签到"></el-option>
            <el-option :value="0" label="异常签到"></el-option>
            <el-option :value="3" label="未签到"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="signOutStatus">
          <el-select
            v-model.trim="searchForm.signOutStatus"
            clearable
            placeholder="签退状态"
          >
            <el-option :value="1" label="正常签退"></el-option>
            <el-option :value="0" label="异常签退"></el-option>
            <el-option :value="3" label="未签退"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="courseTime">
          <el-date-picker
            v-model.trim="searchForm.courseTime"
            style="width: 410px"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="考勤开始日期"
            :picker-options="{
              firstDayOfWeek: 1,
            }"
            end-placeholder="考勤结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
          <el-button native-type="reset" type="primary">重置</el-button>
        </el-form-item>
        <el-form-item>
          <!-- <div class="newBand" @click="onExport">导出</div> -->
          <el-button
            @click="onExport"
            type="primary"
            v-permission="'export/queryTeacherAttendances'"
            style="background-color: #14928a; border: 1px solid #14928a"
            >导出</el-button
          >
        </el-form-item>
      </save-form>
      <div class="tableWrap">
        <el-table
          style="width: 100%"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :data="tableList"
        >
          <el-table-column
            align="center"
            prop="organName"
            label="分部"
          ></el-table-column>
          <el-table-column align="center" prop="teacherName" label="老师名称">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.teacherName }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="courseScheduleId"
            label="课程编号"
          >
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.courseScheduleId }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="courseScheduleName"
            label="课程名称"
          >
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.courseScheduleName }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="classDate"
            label="上课日期"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="startClassTime"
            label="上课时间"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.startClassTime + "-" + scope.row.endClassTime }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="startClassTime"
            label="课程类型"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.courseScheduleType | coursesType }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="工作类型">
            <template slot-scope="scope">{{
              scope.row.jobNature | jobNature
            }}</template>
          </el-table-column>
          <el-table-column align="center" label="签到时间">
            <template slot-scope="scope">
              <div>
                {{ scope.row.signInTime }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="签到状态">
            <template slot-scope="scope">
              <div v-if="scope.row.courseScheduleStatus != 'NOT_START'">
                {{ scope.row.signInStatus | attendanceType }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            prop="startClassTime"
            label="签退时间"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.signOutTime }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="签退状态">
            <template slot-scope="scope">
              <div v-if="scope.row.courseScheduleStatus != 'NOT_START'">
                {{ scope.row.signOutStatus | attendanceOutType }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="申诉状态">
            <template slot-scope="scope">
              <div>
                {{ $constant.complaintsStatus[scope.row.complaintsStatus] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="remark"
            label="备注"
          ></el-table-column>
          <el-table-column
            align="center"
            label="操作"
            fixed="right"
            width="220px"
          >
            <template slot-scope="scope">
              <auth auths="teacherAttendance/repealComplaints">
                <el-button
                  type="text"
                  v-if="
                    scope.row.jobNature === 'PART_TIME' &&
                    scope.row.complaintsStatus == 2
                  "
                  @click="unappeal(scope.row)"
                  >撤销申诉</el-button
                >
              </auth>
              <auth auths="teacherAttendance/addComplaints">
                <el-button
                  v-if="
                    scope.row.jobNature === 'PART_TIME' &&
                    (scope.row.complaintsStatus == null ||
                      scope.row.complaintsStatus == 3)
                  "
                  type="text"
                  @click="appeal(scope.row)"
                  >申诉</el-button
                >
              </auth>
              <auth auths="teacherAttendance/update">
                <el-button type="text" @click="hand(scope.row)"
                  >处理意见</el-button
                >
              </auth>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog title="申诉" width="400px" :visible.sync="appealVisible">
          <appeal
            v-if="appealVisible && detail"
            :detail="detail"
            @close="appealVisible = false"
            @submited="getList"
          />
        </el-dialog>
        <el-dialog title="处理意见" width="400px" :visible.sync="handVisible">
          <hand
            v-if="handVisible && detail"
            :detail="detail"
            @close="handVisible = false"
            @submited="getList"
          />
        </el-dialog>
        <pagination
          sync
          :total.sync="rules.total"
          :page.sync="rules.page"
          :limit.sync="rules.limit"
          :page-sizes="rules.page_size"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import pagination from "@/components/Pagination/index";
import load from "@/utils/loading";
import qs from "qs";
import cleanDeep from "clean-deep";
import { getTeacher, getEmployeeOrgan } from "@/api/buildTeam";
import { queryTeacherAttendances } from "@/api/recodeManager";
import { jobNature, courseType } from "@/utils/searchArray";
import { repealComplaints } from "./api";
import appeal from "./modals/appeal";
import hand from "./modals/hand";
import { getTimes } from "@/utils";
let nowTime = new Date();
nowTime =
  nowTime.getFullYear() +
  "-" +
  (nowTime.getMonth() + 1) +
  "-" +
  nowTime.getDate();
export default {
  components: { pagination, appeal, hand },
  data() {
    return {
      searchForm: {
        search: null,
        organId: null,
        signInStatus: null,
        signOutStatus: null,
        jobNature: null,
        courseTime: [],
      },
      detail: null,
      appealVisible: false,
      handVisible: false,
      jobNature: jobNature, // 工作类型

      courseType,
      // teacherList: [],
      tableList: [],
      organList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
    };
  },
  computed: {
    isEmptyQuery() {
      return (
        !Object.keys(
          cleanDeep({
            ...this.searchForm,
            // courseTime: this.courseTime,
          })
        ).length && !this.teacherAttendanceId
      );
    },
    teacherAttendanceId() {
      return this.$route.query.teacherAttendanceId;
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    if (this.searchForm.courseTime.length <= 0)
      this.searchForm.courseTime = [nowTime, nowTime];
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // getTeacher().then(res => {
    //   if (res.code == 200) {
    //     this.teacherList = res.data;
    //   }
    // });
    // 获取分部
    // getEmployeeOrgan().then(res => {
    //   if (res.code == 200) {
    //     this.organList = res.data;
    //   }
    // });
    const { query } = this.$route;
    this.$store.dispatch("setBranchs");
    if (query.organId) {
      this.searchForm.organId = query.organId;
    }
    if (query.start || query.end) {
      this.searchForm.courseTime = [query.start, query.end];
    } else {
    }
    this.init();
  },
  methods: {
    init() {
      this.getList();
    },
    getSearchValues() {
      const { courseTime, ...rest } = this.searchForm;
      let obj = {
        ...rest,
        page: this.rules.page,
        rows: this.rules.limit,
        attendanceStatus: this.$route.query.attendanceStatus,
        visitFlag: this.$route.query.visitFlag,
        ...getTimes(courseTime, ["courseStartDate", "courseEndDate"]),
      };
      return obj;
    },
    reloadSearch() {
      if (this.isEmptyQuery) {
        this.courseTime = [nowTime, nowTime];
      }
      this.getList();
    },
    getList() {
      let obj = this.getSearchValues();
      if (this.isEmptyQuery) {
        this.$message.error("请至少选择一个条件");
        return;
      }
      queryTeacherAttendances(obj).then((res) => {
        if (res.code == 200) {
          this.tableList = res.data.rows;
          this.rules.total = res.data.total;
        }
      });
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
      this.$refs["searchForm"].resetFields();
      this.searchForm.courseTime = [nowTime, nowTime];
      this.search();
    },
    hand(row) {
      this.handVisible = true;
      this.detail = row;
    },
    appeal(row) {
      this.appealVisible = true;
      this.detail = row;
    },
    async unappeal(row) {
      try {
        await this.$confirm("是否确认撤销申诉?", "提示", {
          type: "warning",
        });
        await repealComplaints({
          courseScheduleId: row.courseScheduleId,
          userId: row.teacherId,
        });
        this.$message.success("撤销成功");
        this.getList();
      } catch (error) {}
    },
    onExport() {
      let obj = this.getSearchValues();
      if (this.isEmptyQuery) {
        this.$message.error("请至少选择一个条件");
        return;
      }
      let url = "/api-web/export/queryTeacherAttendances";
      const options = {
        method: "POST",
        headers: {
          Authorization: getToken(),
        },
        params: obj,
        url,
        responseType: "blob",
      };
      this.$confirm("您确定导出考勤列表", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          load.startLoading();
          axios(options)
            .then((res) => {
              let blob = new Blob([res.data], {
                // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                type: "application/vnd.ms-excel;charset=utf-8",
                //word文档为application/msword,pdf文档为application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
              });

              let text = new Response(blob).text();
              text.then((res) => {
                // 判断是否报错
                if (res.indexOf("code") != -1) {
                  let json = JSON.parse(res);
                  this.$message.error(json.msg);
                } else {
                  let objectUrl = URL.createObjectURL(blob);
                  let link = document.createElement("a");
                  let fname = "考勤列表" + new Date().getTime() + ".xls"; //下载文件的名字
                  link.href = objectUrl;
                  link.setAttribute("download", fname);
                  document.body.appendChild(link);
                  link.click();
                }
              });
              load.endLoading();
            })
            .catch((error) => {
              this.$message.error("导出数据失败，请联系管理员");
              load.endLoading();
            });
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang='scss' scoped>
</style>
