<template>
  <div class="page">
    <div>
      <tab-pane
        :thirdList="thirdList"
        :activeName="activeName"
        @handleClick="handleClick"
      ></tab-pane>
    </div>
    <!-- <div class="totalNum flex">
      <div class="item flex">
        <div>
          需要打卡人数
          <span class="num">{{ attendStatInfo.total }}</span>
        </div>
        <div>
          未出勤 <span class="num">{{ attendStatInfo.noAtt }}</span>
        </div>
        <div>
          出勤率
          <span class="num">{{ attendStatInfo.attPercentage }}</span>
        </div>
      </div>

      <div class="item flex">
        <div>
          迟到 <span class="num">{{ attendStatInfo.beLate }}</span>
        </div>
        <div>
          早退
          <span class="num">{{ attendStatInfo.leaveEarly }}</span>
        </div>
        <div>
          缺卡
          <span class="num">{{ attendStatInfo.lackOfCards }}</span>
        </div>
      </div>
    </div> -->
    <LayoutTable
      :data="tableData"
      :config="tableConfig"
      notDel
      notAdd
      ref="layoutTable"
    >
      <el-button
        slot="table-head-left2"
        style="margin-left: 10px"
        icon="el-icon-tickets"
        size="mini"
        @click="handleImport"
        >导入</el-button
      >
      <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
      > -->
    </LayoutTable>
    <drawer-show ref="drawerform" @ok="getData" />
    <!-- 导出记录查看 -->
    <el-drawer
      title="导出记录"
      :visible.sync="drawerhistory"
      :direction="direction"
    >
      <div class="hisList">
        <div
          class="list mt10"
          v-for="(item, index) in exportList"
          :key="index"
          @click="changeStatus(item)"
        >
          <div class="flex flex-align-center flex-pack-justify">
            <div>每日打卡记录</div>
            <el-button type="text">导出成功</el-button>
          </div>
          <div class="details" v-if="item.islook">
            <div class="mt10" v-if="item.recordIdList">
              选择列表id： {{ item.recordIdList }}
            </div>
            <div class="mt10" v-if="item.deptName">
              选择部门：{{ item.deptName }}
            </div>
            <div class="mt10" v-if="item.groupName">
              选择考勤组：{{ item.groupName }}
            </div>
            <div class="mt10" v-if="item.className">
              选择班次：{{ item.className }}
            </div>

            <div class="mt10">
              <el-link
                :href="baseUrl + item.filePath"
                target="_blank"
                type="primary"
                >重新下载</el-link
              >
            </div>
          </div>
          <div class="times">导出时间：{{ item.createTime }}</div>
        </div>
      </div>
    </el-drawer>
    <!-- 导出表格设置 -->
    <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-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
          <el-link
            type="primary"
            style="font-size: 14px"
            @click="downloadTemplate"
            >下载模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <div class="mask" v-if="progress">
      <el-progress :stroke-width="26" :percentage="percent"></el-progress>
    </div>
  </div>
</template>

<script>
/** 表单弹出框模式需引入 */
import drawerShow from "./drawershow";
import table from "@/assets/mixins/table";
import TabPane from "@/components/tabPane.vue";
import { timestampToTime } from "@/assets/utils/dateFormat";
import { formatterDateOnly } from "@/assets/utils/table";
export default {
  name: "AttendanceRecordList",
  components: {
    drawerShow,
    TabPane,
  },
  mixins: [table],
  computed: {
    thirdList() {
      if (!this.$store.state.CurrentThirdArr) return [];
      return this.$store.state.CurrentThirdArr;
    },
    activeName() {
      return this.$store.state.ThirdPath;
    },
  },
  created() {
    this.$post("/attendance/record/stat", {}).then((res) => {
      if (res.code === 1) {
        this.attendStatInfo = res.data;
      }
    });

    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;
      }
    },
    // 表格接收数据后
    afterRender(data) {
      console.log(data);
      let addobjArr = [];
      data.dyncColumns.map((item) => {
        let obj = {
          show: true,
          label: item.name,
          prop: "",
          formatter: (row) => {
            if (row.attendanceRecordDetailList.length < 1) {
              return "-";
            } else {
              return this.handleArr(
                row.attendanceRecordDetailList,
                item.orderNum,
                item.property
              );
            }
          },
        };
        addobjArr.push(obj);
      });
      this.config.columns = [...this.initalArr, ...addobjArr];
      this.$refs.layoutTable.showType = "tableSelect";
      this.$forceUpdate();
    },
    // 表格接收数据前
    beforeRender(data) {
      return data;
    },
    // 处理
    handleArr(arr, currentorderNum, property) {
      let index = arr.findIndex((item) => item.orderNum === currentorderNum);
      if (index > -1) {
        if (!arr[index][property]) {
          return "-";
        } else if (property === "goWorkDate" || property === "offWorkDate") {
          // 打卡时间
          return timestampToTime(arr[index][property], 6);
        } else if (
          property === "goWorkResult" ||
          property === "offWorkResult"
        ) {
          let val = arr[index][property];
          return this.tableData.dict.goWorkResult[val];
        }
      } else {
        return "-";
      }
    },

    changeStatus(item) {
      this.$set(item, "islook", !item.islook);
    },
    // 导出记录
    lookexportHis() {
      this.$post("/attendance/export/record/list", {
        type: 2,
        page: 1,
        size: -1,
      }).then((res) => {
        if (res.code == 1) {
          let arr = res.data.data;
          this.exportList = arr.map((item) => {
            item.createTime = timestampToTime(item.createTime, 6);
            item.islook = false;
            return item;
          });
        }
      });
      // 导出记录
      this.drawerhistory = true;
    },
    /** 导入 */
    handleImport() {
      this.upload.title = "打卡记录导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    downloadTemplate() {
      this.isExport = true;
      this.$download(
        "/attendance/record/downloadTemplate",
        {},
        { type: "excel" }
      )
        .then(() => (this.isExport = false))
        .catch((error) => {
          this.isExport = false;
          this.$message.error(error.message);
        });
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getData();
    },
    /** 提交上传文件 */
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出Excel */
    doExport() {
      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;
      }
      let flag = this.checkDate(
        params.attendanceDateStart,
        params.attendanceDateEnd,
        1
      );
      if (!flag) {
        this.isExport = true;

        this.progress = true;
        this.$download(
          "/attendance/record/exportExcel",
          {
            ...params,
          },
          { type: "excel" }
        )
          .then((res) => {
            this.percent = 100;
            this.progress = false;
            this.isExport = false;
            this.checkList = [];
          })
          .catch((error) => {
            this.percent = 100;
            this.progress = false;

            this.isExport = false;
            this.$message.error(error.message);
          });
      }
    },
    checkDate(startTime, endTime, compDay) {
      if (startTime == "" || startTime == null || startTime == undefined) {
        this.$message.error("开始时间为空，请检查！");
        return true;
      }
      if (endTime == "" || endTime == null || endTime == undefined) {
        this.$message.error("结束时间为空，请检查！");
        return true;
      }
      var data1 = Date.parse(startTime.replace(/-/g, "/"));
      var data2 = Date.parse(endTime.replace(/-/g, "/"));
      var datadiff = data2 - data1;
      var time = parseInt(compDay) * (60 * 60 * 24 * 1000);
      if (datadiff < 0) {
        this.$message.error("开始时间应小于结束时间");
        return true;
      }
      if (datadiff > time) {
        this.$message.error("时间间隔大于" + parseInt(compDay) + "天，请检查!");
        return true;
      }
      return false;
    },
    setdialog(i) {
      if (i == 1) {
        this.isdialog = true;
        this.setcolum = this.config.columns.filter(
          (item) => item.label && item.prop
        );
      } else {
        this.setDialog = true;
        this.setcolum = this.config.columns.filter(
          (item) => item.label && item.prop
        );

        this.checkTableList = this.config.columns.map((item) => {
          if (item.show) {
            return item.prop;
          }
        });
      }
    },
    renderTable(tableData) {
      return (
        <el-table stripe data={tableData} class="total-table">
          {this.columnSet.map((item) => this.renderTableColumn(item))}
        </el-table>
      );
    },
    renderTableColumn(options) {
      return (
        <el-table-column
          prop={options.prop}
          label={options.label}
          width={options.width}
          formatter={options.formatter}
        ></el-table-column>
      );
    },
    /** 重写新增方法 */
    toAdd(row) {
      this.$refs.drawerform.add(row);
    },
    /** 重写编辑方法 */
    toEdit(row) {
      this.$refs.drawerform.edit(row);
    },
    /** 重写查看方法 */
    toView(row) {
      this.$refs.drawerform.view(row);
    },
    handleClick(key) {
      console.log(key);
      this.$store.commit("setThirdPath", key);
      this.$router.push({
        path: key,
      });
    },
  },
  data() {
    return {
      // 动态新增列表
      addColumn: [],
      progress: false,
      percent: 0,
      upload: {
        // 是否显示弹出层（员工关怀信息导入）
        open: false,
        // 弹出层标题（员工关怀信息导入）
        title: "每日打卡记录",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 上传的地址
        url: "/attendance/record/importData",
      },
      /** 子表列元素 */
      columnSet: [
        { prop: "shiftsName", label: "班次名称", width: 150, show: true },
        {
          prop: "goWorkDate",
          label: "上班打卡时间",
          width: 100,
          formatter: this.formatterDate,
          show: true,
        },
        {
          prop: "goWorkResult",
          label: "上班打卡结果",
          width: 100,
          formatter: this.formatterString,
          show: true,
        },
        {
          prop: "offWorkDate",
          label: "下班打卡时间",
          width: 100,
          formatter: this.formatterDate,
          show: true,
        },
        {
          prop: "offWorkResult",
          label: "下班打卡结果",
          width: 100,
          formatter: this.formatterString,
          show: true,
        },
      ],
      config: {
        showType: "tableSelect",
        search: [
          {
            name: "staffName",
            type: "text",
            label: "员工姓名",
            fuzzy: true,
          },

          // {
          //   name: "workNum",
          //   type: "text",
          //   label: "员工工号",
          //   fuzzy: true,
          // },
          {
            name: "phone",
            type: "text",
            label: "手机号",
            fuzzy: true,
          },
          {
            name: "deptId",
            type: "select",
            label: "所属部门",
            fuzzy: false,
          },
          {
            name: "groupId",
            type: "select",
            label: "所属考勤组",
            fuzzy: false,
          },
          {
            name: "classId",
            type: "select",
            label: "班次",
            fuzzy: false,
          },
          {
            name: "punchResult",
            type: "select",
            label: "打卡结果",
            fuzzy: false,
          },
          {
            name: "attendanceDateStart",
            type: "date",
            label: "考勤开始时间",
            fuzzy: false,
          },
          {
            name: "attendanceDateEnd",
            type: "date",
            label: "考勤结束时间",
            fuzzy: false,
          },
        ],
        columns: [
          { type: "selection", width: 60, show: true },
          { type: "index", label: "序号", width: 50, show: true },
          {
            label: "打卡日期",
            prop: "attendanceDate",
            formatter: this.formatterDateOnly,
            show: true,
          },
          { label: "员工姓名", prop: "staffName", show: true },
          { label: "员工工号", prop: "workNum", show: true },
          {
            label: "考勤组",
            prop: "attendanceGroupName",
            show: true,
          },
          { label: "部门", prop: "deptName", show: true },
          { label: "职位", prop: "positionName", show: true },
          {
            label: "班次",
            prop: "classId",
            formatter: this.formatter,
            show: true,
          },
          // {
          //   label: "签到结果",
          //   prop: "signInResult",
          //   formatter: this.formatter,
          //   show: true,
          // },
          // {
          //   label: "签退结果",
          //   prop: "signOutResult",
          //   formatter: this.formatter,
          //   show: true,
          // },
          // {
          //   label: "打卡结果",
          //   prop: "punchResult",
          //   formatter: this.formatter,
          //   show: true,
          // },
          // {
          //   label: "考勤类型",
          //   prop: "attendType",
          //   formatter: this.formatter,
          //   show: true,
          // },

          // {
          //   label: "考勤打卡记录详细信息",
          //   width: 120,
          //   prop: "subColumns",
          //   show: true,
          //   formatter: (row) => {
          //     let widthsize = this.columnSet.reduce((pre, cur) => {
          //       return pre + Number(cur.width);
          //     }, 50);
          //     return (
          //       <el-popover placement="right" width={widthsize} trigger="click">
          //         {this.renderTable(row.attendanceRecordDetailList)}
          //         <el-button type="text" slot="reference">
          //           详细
          //         </el-button>
          //       </el-popover>
          //     );
          //   },
          // },
          // {
          //     label: "操作",
          //     width: 240,
          //     formatter: row => {
          //         return (
          //             <table-buttons noAdd noEdit noView noDel
          //             row={row} onEdit={this.toEdit} onView={this.toView} onDel={this.toDel} />
          //     );
          //     }
          // }
        ],
      },
      drawerhistory: false,
      isdialog: false,
      setcolum: [],
      checkList: [],
      setDialog: false,
      checkTableList: [],
      exportList: [], //导出记录
      baseUrl: process.env.VUE_APP_API_BASE_URL + "/",
      initalArr: [],
      attendStatInfo: {},
    };
  },
};
</script>
<style scoped lang="less">
.mask {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
  padding: 0 30%;
  padding-top: 20%;
  background: rgba(0, 0, 0, 0.6);
}
::v-deep .el-progress__text {
  color: #409eff;
  font-weight: 600;
}
.totalNum {
  background: rgba(64, 158, 255, 0.2);
  padding: 15px;
  border-left: 4px solid rgb(20, 134, 248);
  color: rgb(100, 100, 100);
  .item {
    padding: 0 10px;
    border-right: 1px solid gray;
  }
  .item:last-child {
    border: none;
  }
  .num {
    color: #409eff;
    margin-left: 10px;
    margin-right: 20px;
  }
}
.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>
