<template>
  <div class="page">
    <LayoutTable
      :data="tableData"
      :config="tableConfig"
      notAdd
      notDel
      ref="layoutTable"
    >
      <el-button
        slot="table-head-left2"
        style="margin-left: 10px"
        icon="el-icon-tickets"
        size="mini"
        type="primary"
        @click="doExport"
        :disabled="isExport"
        >导出</el-button
      >
      <el-button
        slot="table-head-left2"
        style="margin-left: 10px"
        icon="el-icon-tickets"
        size="mini"
        type="success"
        @click="lookexportHis"
        >导出记录</el-button
      >
      <el-button
        slot="table-head-left2"
        style="margin-left: 10px"
        icon="el-icon-tickets"
        size="mini"
        @click="setdialog(2)"
        >表格设置</el-button
      >
      <el-button
        slot="table-head-left2"
        style="margin-left: 10px"
        icon="el-icon-tickets"
        size="mini"
        @click="setdialog(1)"
        >导出表格设置</el-button
      >
      <!-- <el-button
        slot="table-head-left2"
        style="margin-left: 10px"
        icon="el-icon-tickets"
        size="mini"
        @click="restTable"
        >重新汇总</el-button
      > -->
      <el-button
        type="primary"
        size="mini"
        slot="table-head-left2"
        v-if="showBtn"
        style="margin-left: 10px"
        @click="handleRefresh"
        :loading="btnFreshLoading"
        >手动更新</el-button
      >
      <span class="freshTime" slot="table-head-left2">
        <i class="el-icon-refresh"></i>
        <span
          >上次考勤汇总时间：{{
            tableData.dict.summaryTime ? tableData.dict.summaryTime : "--"
          }}</span
        >
      </span>
    </LayoutTable>
    <dialog-show ref="dialogform" @ok="getData" />
    <!-- 导出表格设置 -->
    <el-dialog :visible.sync="isdialog" title="导出表格设置">
      <div class="tipsword">
        请选择表格展示字段，导出的表格中的内容选中的字段将保持一致。
      </div>
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          v-for="(item, index) in setcolum"
          :key="index"
          :label="item.prop"
        >
          {{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
      <div class="mt20" style="text-align:right">
        <el-button @click="handleCancel(1)">取消</el-button>
        <el-button type="primary" @click="handleSubmit(1)">确定</el-button>
      </div>
    </el-dialog>
    <!-- 显示表格设置 -->
    <el-dialog :visible.sync="setDialog" title="表格显示设置">
      <div class="tipsword">
        请选择表格展示字段，表格中的内容与选中的字段将保持一致。
      </div>
      <el-checkbox-group v-model="checkTableList">
        <el-checkbox
          v-for="(item, index) in setcolum"
          :key="index"
          :label="item.prop"
        >
          {{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
      <div class="mt20" style="text-align:right">
        <el-button @click="handleCancel(2)">取消</el-button>
        <el-button type="primary" @click="handleSubmit(2)">确定</el-button>
      </div>
    </el-dialog>
    <!-- 导出记录查看 -->
    <el-drawer
      title="导出记录"
      :visible.sync="drawerhistory"
      :direction="direction"
    >
      <div class="hisList">
        <div class="list mt10" v-for="item in 10" :key="item">
          <div class="flex flex-align-center flex-pack-justify">
            <div>打卡记录汇总</div>
            <el-button type="text">导出成功</el-button>
          </div>
          <div class="times">
            导出时间：2020-08-13
          </div>
        </div>
      </div>
    </el-drawer>
    <el-dialog
      title="系统提示"
      :visible.sync="dialogOpen"
      width="500px"
      append-to-body
      @close="cancleFresh"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="fresh_box" v-if="showContent">
        <div class="title_box" style="margin-bottom: 20px;">
          仅支持手动更新前一天及当日的打卡数据，请选择需要更新的时间段：
        </div>
        <el-date-picker
          v-model="freshDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          value-format="yyyy-MM-dd"
          end-placeholder="结束日期"
          :picker-options="pickerOptions0"
        >
        </el-date-picker>
      </div>
      <div class="fresh_box" v-else>
        <div
          class="title_box"
          style="margin-bottom: 20px;line-height: 30px;"
          v-if="showTip"
        >
          请确认是否开始进行{{
            freshDate[0] + "至" + freshDate[1]
          }}的考勤数据重新汇总；此过程预计需要
          <span style="color:#ff0000 ;">10</span> 分钟左右，请勿关闭或刷新页面
        </div>
        <div
          class="title_box"
          style="margin-bottom: 20px;line-height: 30px;"
          v-else
        >
          正在进行{{
            freshDate[0] + "至" + freshDate[1]
          }}的考勤数据重新汇总；此过程预计还需要
          <span style="color:#ff0000 ;">{{ restTime }}</span>
          分钟左右，请勿关闭或刷新页面
        </div>
      </div>
      <div slot="footer" class="dialog-footer" v-if="showTip">
        <el-button
          type="primary"
          @click="() => (showContent = false)"
          v-if="showContent"
          >确 定</el-button
        >
        <el-button
          type="primary"
          @click="submitFresh"
          v-else
          :loading="submitLoad"
          >确 定</el-button
        >
        <el-button @click="cancleFresh">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
/** 表单弹出框模式需引入 */
import dialogShow from "./dialogshow";
import table from "@/assets/mixins/table";
import {
  getFirstDay,
  getLastDay,
  getdiffdate,
  timestampToTime,
  getMyDay,
} from "@/assets/utils/dateFormat.js";
export default {
  name: "AttendanceStatList",
  components: {
    dialogShow,
  },
  mixins: [table],
  created() {
    this.query.summaryTimeStart = getFirstDay();
    this.query.summaryTimeEnd = getLastDay();
    this.initalArr = this.config.columns;
  },
  methods: {
    //倒计时
    countdown() {
      let now = Date.parse(new Date());
      let msec = this.endTime - now;

      if (msec < 0) return;

      // let day = parseInt(msec / 1000 / 60 / 60 / 24);
      let hr = parseInt((msec / 1000 / 60 / 60) % 24);
      let min = parseInt((msec / 1000 / 60) % 60);
      let sec = parseInt((msec / 1000) % 60);
      min = min > 9 ? min : "0" + min;
      sec = sec > 9 ? sec : "0" + sec;
      this.restTime = min + "分" + sec + "秒";
      const that = this;
      if (min >= 0 && sec >= 0) {
        if (min == 0 && sec == 0) {
          this.submitLoad = false;
          this.dialogOpen = false;
          this.btnFreshLoading = false;
          this.showContent = true;
          this.showTip = true;
          this.freshDate = "";
          this.getData();
          return;
        }
        setTimeout(function() {
          that.countdown();
        }, 1000);
      }
    },
    submitFresh() {
      console.log(this.freshDate);
      if (this.freshDate) {
        this.submitLoad = true;
        this.$post("/attendance/stat/summary", {
          attendanceDateStart: this.freshDate[0],
          attendanceDateEnd: this.freshDate[1],
        })
          .then((res) => {
            if (res.code == 1) {
              this.showTip = false;
              this.btnFreshLoading = false;
              this.submitLoad = false;
              this.endTime = Date.parse(new Date()) + 10 * 60 * 1000;
              this.countdown();
            }
          })
          .catch((error) => {
            this.$message.error(res.msg);
            this.submitLoad = false;
            this.dialogOpen = false;
            this.btnFreshLoading = false;
            this.showContent = true;
            this.showTip = true;
            this.freshDate = "";
          });
      } else {
        this.$message.error("请选择时间范围！");
      }
    },
    cancleFresh() {
      this.dialogOpen = false;
      this.btnFreshLoading = false;
      this.showContent = true;
      this.freshDate = "";
    },
    // 手动更新
    handleRefresh() {
      this.btnFreshLoading = true;
      this.dialogOpen = true;
    },
    // 表格设置弹窗取消操作
    handleCancel(i) {
      if (i == 1) {
        this.checkList = [];
        this.isdialog = false;
      } else {
        this.setDialog = false;
      }
    },
    // 表格设置提交操作
    handleSubmit(i) {
      if (i == 1) {
        this.doExport();
        this.isdialog = false;
      } else {
        this.config.columns.forEach((v) => {
          v.prop && v.prop != "attendanceStaffStatEntities"
            ? (v.show = false)
            : (v.show = true);
          this.checkTableList.forEach((val) => {
            if (v.prop == val) {
              v.show = true;
            }
          });
        });
        this.$forceUpdate(this.config.columns);
        this.setDialog = false;
      }
    },
    // 处理
    handleArr(arr, currentTime) {
      // 处理createTime相同的数据
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i]["createTime"] == arr[j]["createTime"]) {
            if (arr[i]["attendanceSummary"].indexOf("; ") == -1) {
              arr[i]["attendanceSummary"] =
                arr[i]["attendanceSummary"] + "; " + arr[j].attendanceSummary;
            }
          }
        }
      }

      let index = arr.findIndex((item) => item.createTime == currentTime);
      if (index > -1) {
        return arr[index].attendanceSummary ? (
          arr[index].remark && arr[index].remark != "" ? (
            <el-tooltip
              class="item"
              effect="light"
              content={arr[index].content}
              placement="top-start"
            >
              <el-tag
                type={
                  arr[index].attendanceSummary.includes("缺卡") ||
                  arr[index].attendanceSummary.includes("迟到") ||
                  arr[index].attendanceSummary.includes("早退")
                    ? "danger"
                    : "success"
                }
                size="mini"
              >
                {arr[index].attendanceSummary}
              </el-tag>
            </el-tooltip>
          ) : arr[index].attendanceSummary.includes("缺卡") ||
            arr[index].attendanceSummary.includes("迟到") ||
            arr[index].attendanceSummary.includes("早退") ? (
            <el-tag type={"danger"} size="mini">
              {arr[index].attendanceSummary}
            </el-tag>
          ) : (
            <el-tag type={"success"} size="mini">
              {arr[index].attendanceSummary}
            </el-tag>
          )
        ) : (
          "--"
        );
      } else {
        // if (currentTime < timestampToTime(new Date(), 3)) {
        //   return "正常";
        // } else {
        //   return "--";
        // }
        return "--";
      }
    },
    restTable() {
      this.getTable();
    },
    afterRender(data) {
      this.addColumn = getdiffdate(
        this.query.summaryTimeStart,
        this.query.summaryTimeEnd
      );
      // 动态处理
      let addobjArr = [];
      this.addColumn.map((item, index) => {
        let obj = {
          show: true,
          label: item + "(" + getMyDay(new Date(item)) + ")",
          prop: "attendanceStaffStatEntities",
          width: 100,
          formatter: (row) => {
            if (
              row.attendanceStaffStatEntities &&
              row.attendanceStaffStatEntities.length > 0
            ) {
              return this.handleArr(row.attendanceStaffStatEntities, item);
            } else {
              return "--";
              if (item < timestampToTime(new Date(), 3)) {
                return "正常";
              } else {
                return "--";
              }
            }
          },
        };
        addobjArr.push(obj);
      });
      let arr1 = this.initalArr.slice(0, 8);
      let arr2 = this.initalArr.slice(8);
      this.config.columns = [...arr1, ...addobjArr, ...arr2];
      this.$refs.layoutTable.showType = "tableSelect";
      this.$forceUpdate();
    },
    beforeRender(row) {
      this.tableData.dict = row.dict;
      row.data.forEach((element) => {
        if (
          element.attendanceStaffStatEntities &&
          element.attendanceStaffStatEntities.length > 0
        ) {
          element.attendanceStaffStatEntities.forEach((item1) => {
            item1.createTime = timestampToTime(item1.createTime, 3);
            let Arr = [];
            item1.remark && item1.remark.length > 0
              ? (Arr = JSON.parse(item1.remark))
              : "";
            Arr && Arr.length > 0
              ? (item1.content = Arr.map((v) => {
                  return (
                    <p>
                      {v.goWorkResult == 1 ? (
                        <span style="marginRight:10px">
                          打卡时间：
                          {v.goWorkDate
                            ? (v.goWorkDate = timestampToTime(v.goWorkDate, 6))
                            : (v.goWorkDate = "--")}
                          {"  "} 打卡结果：
                          {this.tableData.dict.goWorkResult[v.goWorkResult]}
                        </span>
                      ) : (
                        <span style="color:red;marginRight:10px">
                          打卡时间：
                          {v.goWorkDate
                            ? (v.goWorkDate = timestampToTime(v.goWorkDate, 6))
                            : (v.goWorkDate = "--")}
                          {"  "} 打卡结果：
                          {this.tableData.dict.goWorkResult[v.goWorkResult]}
                        </span>
                      )}
                      {v.offWorkResult == 1 ? (
                        <span>
                          打卡时间：
                          {v.offWorkDate
                            ? (v.offWorkDate = timestampToTime(
                                v.offWorkDate,
                                6
                              ))
                            : (v.offWorkDate = "--")}
                          {"  "} 打卡结果：
                          {this.tableData.dict.offWorkResult[v.offWorkResult]}
                        </span>
                      ) : (
                        <span style="color:red">
                          打卡时间：
                          {v.offWorkDate
                            ? (v.offWorkDate = timestampToTime(
                                v.offWorkDate,
                                6
                              ))
                            : (v.offWorkDate = "--")}
                          {"  "} 打卡结果：
                          {this.tableData.dict.offWorkResult[v.offWorkResult]}
                        </span>
                      )}
                    </p>
                  );
                }))
              : "";
          });
        }
      });

      return row;
    },
    /** 重写新增方法 */
    toAdd(row) {
      this.$refs.dialogform.add(row);
    },
    /** 重写编辑方法 */
    toEdit(row) {
      this.$refs.dialogform.edit(row);
    },
    /** 重写查看方法 */
    toView(row) {
      this.$refs.dialogform.view(row);
    },
    setdialog(i) {
      if (i == 1) {
        this.isdialog = true;
        this.setcolum = this.config.columns.filter(
          (item) => item.label && item.prop
        );
        this.setcolum = this.setcolum.filter(
          (val) => val.prop !== "attendanceStaffStatEntities"
        );
      } else {
        this.setDialog = true;
        this.setcolum = this.config.columns.filter(
          (item) => item.label && item.prop
        );
        this.setcolum = this.setcolum.filter(
          (val) => val.prop !== "attendanceStaffStatEntities"
        );
        this.checkTableList = this.config.columns.map((item) => {
          if (item.show) {
            return item.prop;
          }
        });
      }
    },
    lookexportHis() {
      this.drawerhistory = true;
    },
    /** 导出Excel */
    doExport() {
      this.isExport = true;
      let params = {};
      for (let value of this.config.search) {
        if (this.query[value.name]) {
          params[value.name] = this.query[value.name];
        }
      }

      if (this.selection.length > 0) {
        params["idList"] = this.selection;
      }
      if (this.checkList.length > 0) {
        params["properties"] = this.checkList;
      }
      this.$download(
        "/attendance/stat/exportExcelExt",
        {
          ...params,
        },
        { type: "excel", name: "考勤汇总" }
      )
        .then(() => {
          this.isExport = false;
          this.checkList = [];
        })
        .catch((error) => {
          this.isExport = false;
          this.$message.error(error.message);
        });
    },
  },
  data() {
    return {
      showTip: true,
      showContent: true,
      endTime: "",
      restTime: "10",
      pickerOptions0: {
        disabledDate(v) {
          let limitDate =
            v.getTime() < new Date().getTime() - 2 * 86400000 ||
            v.getTime() > Date.now();
          return limitDate;
          7;
        },
      },
      freshDate: "",
      submitLoad: false,
      btnFreshLoading: false,
      dialogOpen: false,
      showBtn: true,
      isExport: false,
      config: {
        showType: "tableSelect",
        isshowTabPane: true,
        height: "680px",
        search: [
          {
            name: "salaId",
            type: "selectSalaId",
            label: "大厅",
            fuzzy: false,
          },
          {
            name: "deptId",
            type: "selectDeptId",
            label: "部门",
            fuzzy: false,
          },
          // {
          //   name: "groupId",
          //   type: "select",
          //   label: "全部考勤组",
          //   fuzzy: false,
          // },
          // {
          //   name: "classId",
          //   type: "select",
          //   label: "全部班次",
          //   fuzzy: false,
          // },
          {
            name: "summaryTimeStart",
            type: "date",
            label: "考勤开始时间",
            fuzzy: false,
          },
          {
            name: "summaryTimeEnd",
            type: "date",
            label: "考勤结束时间",
            fuzzy: false,
          },
          {
            name: "staffName",
            type: "text",
            label: "员工姓名",
            fuzzy: true,
          },
        ],
        columns: [
          { type: "selection", width: 60, fixed: "left", show: true },
          {
            type: "index",
            label: "序号",
            width: 50,
            fixed: "left",
            show: true,
          },

          {
            label: "窗口类别",
            prop: "windowCategory",
            fixed: "left",
            width: 100,
            formatter: this.formatter,
            show: true,
          },

          {
            label: "员工姓名",
            prop: "staffName",
            fixed: "left",
            width: 100,
            show: true,
          },
          {
            label: "大厅",
            prop: "salaName",
            formatter: this.formatter,
            show: true,
          },
          {
            label: "部门",
            prop: "deptName",
            formatter: this.formatter,
            show: true,
          },
          {
            label: "应到",
            prop: "workDays",
            formatter: this.formatter,
            show: true,
          },
          {
            label: "实到",
            prop: "goTimes",
            formatter: (row) => {
              return row.goTimes == 0 ? 0 : row.goTimes ? row.goTimes : "--";
            },
            show: true,
          },
          {
            label: "出勤率%",
            prop: "attendanceRate",
            formatter: (row) => {
              return row.attendanceRate
                ? (Number(row.attendanceRate) * 100).toFixed(2) + "%"
                : "--";
            },
            show: true,
          },
          {
            label: "缺卡次数",
            prop: "morningTimes",
            formatter: this.formatter,
            show: true,
          },
          // {
          //   label: "上午缺卡次数",
          //   prop: "morningTimes",
          //   formatter: this.formatter,
          // },

          // {
          //   label: "下午缺卡次数",
          //   prop: "afternoonTimes",
          //   formatter: this.formatter,
          // },
          { label: "回单位（天）", prop: "backToUnit", show: true },

          { label: "因公请假（天）", prop: "onDutyLeave", show: true },

          { label: "外出勘验（天）", prop: "outOfOffice", show: true },

          { label: "值班补班（天）", prop: "shiftCompensation", show: true },

          { label: "体检（天）", prop: "physicalExamination", show: true },

          { label: "隔离（天）", prop: "quarantine", show: true },

          {
            label: "因公外出（与窗口工作无关/天）",
            prop: "businessTrip",
            show: true,
            width: 140,
          },

          { label: "公休（天）", prop: "publicHoliday", show: true },

          { label: "病假（天）", prop: "sickLeave", show: true },

          { label: "丧假（天）", prop: "funeralLeave", show: true },

          { label: "婚假（天）", prop: "marriageLeave", show: true },

          { label: "育儿假（天）", prop: "childRearingLeave", show: true },

          {
            label: "产假（陪护假/天）",
            prop: "maternityLeave",
            show: true,
            width: 140,
          },

          {
            label: "调回单位（或离职/天）",
            prop: "transferBack",
            show: true,
            width: 140,
          },

          { label: "探亲假（天）", prop: "homeLeave", show: true },

          { label: "事假（天）", prop: "personalLeave", show: true },

          { label: "旷工（天）", prop: "absenteeismDays", show: true },

          { label: "其他（天）", prop: "otherDays", show: true },

          {
            label: "未按规定打卡（含忘记打卡）",
            prop: "nonCompliancePunch",
            show: true,
            width: 140,
          },

          { label: "迟到（次）", prop: "lateTimes", show: true },

          { label: "上网耍手机（次）", prop: "surfingMobileTimes", show: true },

          { label: "溜班（次）", prop: "overtimeTimes", show: true },

          { label: "空岗（次）", prop: "vacancy", show: true },

          {
            label: "未规范着装（次）",
            prop: "nonStandardDressTimes",
            show: true,
          },

          {
            label: "无故缺席会议（次）",
            prop: "unexcusedMeetingAbsence",
            show: true,
            width: 140,
          },

          { label: "会议早退", prop: "earlyLeaveMeeting", show: true },
        ],
      },
      setcolum: [],
      isdialog: false,
      setDialog: false,
      checkTableList: [],
      checkList: [],
      drawerhistory: false,
      // 动态新增列表
      addColumn: [],
      initalArr: [],
    };
  },
};
</script>
<style scoped lang="less">
.hisList {
  padding: 15px;
  .list {
    background-color: rgba(64, 158, 255, 0.1);
    font-size: 14px;
    border-radius: 10px;
    padding: 10px;
    .times {
      font-size: 12px;
      color: #999;
    }
  }
}
.tipsword {
  margin: 20px 0;
  color: #999;
}
.freshTime {
  color: #999;
  font-size: 14px;
}
</style>
