<template>
  <div class="app-container">
    <el-form
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      class="app-container--search"
    >
      <el-form-item label="考勤日期" prop="strDay">
        <el-date-picker
          v-model="queryParams.strDay"
          type="date"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        />
      </el-form-item>

      <el-form-item label="考勤组" prop="attendanceGroupId">
        <el-select
          v-model="queryParams.attendanceGroupIds"
          placeholder="请选择考勤组"
          clearable
          multiple
          style="width: 100%"
        >
          <el-option
            v-for="dict in attendanceGroups"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="员工编号" prop="sysUserName">
        <el-input
          v-model="queryParams.sysUserName"
          placeholder="请输入员工编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="打卡状态" prop="checkInStatus">
        <el-select
          v-model="queryParams.checkInStatus"
          placeholder="请选择打卡状态"
          clearable
        >
          <el-option
            v-for="dict in daka_check_in_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
      <el-form-item style="float: right">
        <el-button type="warning" @click="handleExportSet"
          >导出考勤数据</el-button
        >
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="resultList">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="打卡日期" width="120" prop="checkInTime">
        <template slot-scope="scope">
          {{ formatDate(scope.row.checkInTime) }}
        </template>
      </el-table-column>
      <el-table-column label="员工编号" width="120" prop="sysUserName" />
      <el-table-column label="员工姓名" prop="nickName" width="120" />
      <el-table-column label="考勤组" prop="attendanceGroupName" width="120" />
      <el-table-column label="上班" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.checkInStatus == '0'" style="color: #909399">
            <!-- 上班未打卡 -->
            未打卡
          </span>
          <span
            v-else-if="scope.row.clockInStatus == '1'"
            style="color: #409eff"
          >
            <!--上班已打卡-->
            正常 {{ formatTime(scope.row.clockIn) }}</span
          >
          <span
            v-else-if="scope.row.clockInStatus == '3'"
            style="color: #f56c6c"
          >
            迟到 {{ formatTime(scope.row.clockIn) }}
          </span>
          <span v-else>
            {{ scope.row.clockInStatus }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="下班" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.clockOutStatus == '0'" style="color: #909399">
            <!-- 下班未打卡 -->
            未打卡
          </span>
          <span
            v-else-if="scope.row.clockOutStatus == '2'"
            style="color: #409eff"
          >
            <!--下班已打卡-->
            正常 {{ formatTime(scope.row.clockOut) }}</span
          >
          <span
            v-else-if="scope.row.clockOutStatus == '4'"
            style="color: #f56c6c"
          >
            早退 {{ formatTime(scope.row.clockOut) }}
          </span>
          <span
            v-else-if="scope.row.clockOutStatus == '5'"
            style="color: #f56c6c"
          >
            更新 {{ formatTime(scope.row.clockOut) }}
          </span>
          <span v-else>
            {{ scope.row.clockOutStatus }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="最后更新时间" prop="updateTime" width="200" />
      <el-table-column label="备注" prop="description" />

      <el-table-column
        label="操作"
        width="200"
        align="center"
        v-hasPermi="['attendance:history:edit']"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['attendance:history:edit']"
            type="text"
            @click="handleEdit(scope.row, 0)"
            >上班补卡</el-button
          >
          <el-button
            v-hasPermi="['attendance:history:edit']"
            type="text"
            @click="handleEdit(scope.row, 1)"
            >下班补卡</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="导出考勤数据"
      :visible.sync="open"
      width="460px"
      append-to-body
    >
      <el-form
        ref="exportFormRef"
        :model="exportFormData"
        label-position="top"
        size="small"
        :rules="exportFormRules"
      >
        <el-form-item label="选择区域(区分打卡模版)" prop="modelType">
          <el-select
            v-model="exportFormData.modelType"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in modelTypeDate"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择月份" prop="strMonth">
          <el-date-picker
            v-model="exportFormData.strMonth"
            type="month"
            format="yyyy 年 MM 月"
            value-format="yyyy-MM"
            placeholder="选择月"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="选择考勤组(支持多选)" prop="attendanceGroupIds">
          <el-select
            v-model="exportFormData.attendanceGroupIds"
            placeholder="请选择考勤组"
            clearable
            multiple
            style="width: 100%"
          >
            <el-option
              v-for="dict in attendanceGroups"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="exportDisabled"
          @click="handleExport"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      :title="`${checkStatus == 0 ? '上班' : '下班'}补卡`"
      :visible.sync="editDialogVisible"
      width="460px"
      append-to-body
    >
      <el-descriptions border :column="2" style="margin-bottom: 20px">
        <el-descriptions-item label="打卡日期">{{
          formatDate(editFormData.checkInTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="考勤组">{{
          editFormData.attendanceGroupName
        }}</el-descriptions-item>
        <el-descriptions-item label="员工姓名">{{
          editFormData.nickName
        }}</el-descriptions-item>
        <el-descriptions-item label="员工编号">{{
          editFormData.sysUserName
        }}</el-descriptions-item>
      </el-descriptions>
      <el-form
        ref="editFormRef"
        :model="editFormData"
        label-position="top"
        size="small"
        :rules="editFormRules"
      >
        <el-row :gutter="20">
          <el-col v-if="checkStatus == 0" :span="12">
            <el-form-item label="上班打卡时间" prop="clockIn">
              <el-date-picker
                v-model="editFormData.clockIn"
                type="datetime"
                placeholder="请选择上班时间"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="checkStatus == 1" :span="12">
            <el-form-item label="下班打卡时间" prop="clockOut">
              <el-date-picker
                v-model="editFormData.clockOut"
                type="datetime"
                placeholder="请选择下班时间"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="补卡备注" prop="description">
          <el-input
            v-model="editFormData.description"
            placeholder="请输入打卡备注"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleEditCancel">取 消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { queryList, editRecord } from "@/api/oa/attendance/history";
import { queryAttendanceGroup } from "@/api/oa/attendance/group";
import { formatTime, formatDate } from "@/utils/filters";

export default {
  name: "AttendanceHistory",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      resultList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        sysUserName: undefined,
        checkInStatus: undefined,
        strDay: new Date(),
        flag: "all",
      },
      exportFormData: {
        modelType: undefined,
        strMonth: undefined,
        attendanceGroupIds: [],
      },
      modelTypeDate: [
        { label: "国内", value: "guonei" },
        { label: "日本", value: "riben" },
      ],
      daka_check_in_status: [
        { label: "未打卡", value: "0" },
        { label: "上班已打卡", value: "1" },
        { label: "下班已打卡", value: "2" },
        { label: "迟到打卡", value: "3" },
        { label: "早退打卡", value: "4" },
        { label: "更新打卡", value: "5" },
      ],
      attendanceGroups: [],
      exportDisabled: false,
      exportFormRules: {
        modelType: [
          { required: true, message: "请选择区域", trigger: "change" },
        ],
        strMonth: [
          { required: true, message: "请选择月份", trigger: "change" },
        ],
        attendanceGroupIds: [
          { required: true, message: "请选择考勤组", trigger: "change" },
        ],
      },
      editDialogVisible: false,
      editFormData: {
        checkInTime: undefined,
        checkInStatus: undefined,
        clockIn: undefined,
        clockOut: undefined,
        description: undefined,
      },
      editFormRules: {
        clockIn: [
          { required: true, message: "请选择上班时间", trigger: "change" },
        ],
        clockOut: [
          { required: true, message: "请选择下班时间", trigger: "change" },
        ],
      },
      checkStatus: 0,
    };
  },
  created() {
    this.getList();
    this.queryAttendanceGroup();
  },
  methods: {
    formatDate,
    formatTime,
    handleEditCancel() {
      this.editDialogVisible = false;
      this.editFormData = {
        checkInTime: undefined,
        checkInStatus: undefined,
        clockIn: undefined,
        clockOut: undefined,
        description: undefined,
      };
      this.$nextTick(() => {
        this.$refs.editFormRef.resetFields();
      });
    },
    handleEditSubmit() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          if (this.checkStatus == 0) {
            // 上班补卡
            this.editFormData.clockOut = undefined;
            this.editFormData.clockOutStatus = undefined;
            this.editFormData.clockInStatus = 1;
            this.editFormData.checkInStatus = 1;
          } else {
            // 下班补卡
            this.editFormData.clockIn = undefined;
            this.editFormData.clockInStatus = undefined;
            this.editFormData.clockOutStatus = 2;
            this.editFormData.checkInStatus = 2;
          }
          editRecord({
            id: this.editFormData.id,
            sysUserId: this.editFormData.sysUserId,
            clockIn: this.editFormData.clockIn,
            clockOut: this.editFormData.clockOut,
            description: this.editFormData.description
          })
            .then((response) => {
              this.$message.success("补卡成功");
              this.editDialogVisible = false;
              this.getList();
            })
            .catch(() => {
              this.$message.error("补卡失败");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleEdit(row, checkStatus) {
      this.editDialogVisible = true;
      this.editFormData = row;
      if (!this.editFormData.clockIn) {
        this.editFormData.clockIn =
          formatDate(this.editFormData.checkInTime) + " 00:00:00";
      }
      if (!this.editFormData.clockOut) {
        this.editFormData.clockOut =
          formatDate(this.editFormData.checkInTime) + " 00:00:00";
      }
      this.checkStatus = checkStatus;
    },
    handleExportSet() {
      this.open = true;
      this.reset();
    },
    queryAttendanceGroup() {
      queryAttendanceGroup().then((response) => {
        const data = response.data;
        const newData = data.map((d) => {
          return { label: d.name, value: d.id };
        });
        this.attendanceGroups = newData;
      });
    },
    /** 查询结果列表 */
    getList() {
      this.loading = true;
      this.queryParams.strDay = formatDate(this.queryParams.strDay);
      queryList(this.queryParams).then((response) => {
        this.resultList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.open = false;
    },
    // 表单重置
    reset() {
      this.exportFormData = {
        modelType: undefined,
        strMonth: undefined,
        attendanceGroupIds: [],
      };
      this.$nextTick(() => {
        this.$refs.exportFormRef.resetFields();
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$refs.exportFormRef.validate((valid) => {
        if (valid) {
          this.download(
            "dk/record/exportNew",
            {
              ...this.exportFormData,
            },
            `考勤_${new Date().toLocaleString()}.xls`
          );
          this.open = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
