<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
      > -->
    </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>
  </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 = timestampToTime(new Date(), 3);
    this.query.summaryTimeEnd = timestampToTime(new Date(), 3);
    // this.query.summaryTimeStart = getFirstDay();
    // this.query.summaryTimeEnd = getLastDay();
    this.initalArr = this.config.columns;
  },
  methods: {
    // 表格设置弹窗取消操作
    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 ? (
            <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 {
        return "--";
        // 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" }
      )
        .then(() => {
          this.isExport = false;
          this.checkList = [];
        })
        .catch((error) => {
          this.isExport = false;
          this.$message.error(error.message);
        });
    },
  },
  data() {
    return {
      isExport: false,
      config: {
        showType: "tableSelect",
        isshowTabPane: true,
        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: "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: this.formatter,
            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;
}
</style>
