<template>
  <div class="page">
    <LayoutTable :data="tableData" :config="tableConfig" notDel notAdd>
      <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
        type="primary"
        size="mini"
        slot="table-head-left2"
        v-if="showBtn"
        style="margin-left: 10px"
        @click="formatData"
        :loading="btnLoading"
        >极速计算结果</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
      >
    </LayoutTable>
    <dialog-show ref="dialogform" @ok="getData" />
    <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">
        <div class="title_box" style="margin-bottom: 20px">
          仅支持手动更新近90天的打卡数据，请选择需要更新的时间段：
        </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 slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFresh" :loading="submitLoad"
          >确 定</el-button
        >
        <el-button @click="cancleFresh">取 消</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>
    <!-- 导出记录查看 -->
    <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="item.filePath" target="_blank" type="primary"
                >重新下载</el-link
              >
            </div>
          </div>
          <div class="times mt10">导出时间：{{ item.createTime }}</div>
        </div>
      </div>
    </el-drawer>
    <div class="mask" v-if="progress">
      <el-progress :stroke-width="26" :percentage="percent"></el-progress>
    </div>
  </div>
</template>

<script>
/** 表单弹出框模式需引入 */
import dialogShow from "./dialogshow";
import table from "@/assets/mixins/table";
import {
  timestampToTime,
  getFirstDay,
  getLastDay,
} from "@/assets/utils/dateFormat";
export default {
  name: "AttendanceRecordHikList",
  components: {
    dialogShow,
  },
  mixins: [table],
  data() {
    return {
      // 日期筛选项
      pickerOptions0: {
        disabledDate(time) {
          let curDate = new Date().getTime();
          let three = 90 * 24 * 3600 * 1000;
          let threeMonths = curDate - three;
          return time.getTime() > Date.now() || time.getTime() < threeMonths;
        },
      },
      // 日期绑定值
      freshDate: "",
      // 提交加载状态
      submitLoad: false,
      // 按钮加载状态
      btnLoading: false,
      // 手动更新加载状态
      btnFreshLoading: false,
      // 是否显示弹窗
      dialogOpen: false,
      // 是否展示按钮
      showBtn: false,
      // 是否展示进度
      progress: false,
      // 导出按钮加载状态
      isExport: false,
      // 导出进度绑定值
      percent: 0,
      // 上传接口配置
      upload: {
        headers: {
          Authorization: window.sessionStorage.getItem("token") || "",
        },
        // 是否显示弹出层（员工关怀信息导入）
        open: false,
        // 弹出层标题（员工关怀信息导入）
        title: "导入员工关怀信息数据",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 上传的地址
        url:
          process.env.VUE_APP_API_BASE_URL +
          "/attendance/attendance/record/hik/importData",
      },
      // 表格配置项
      config: {
        isshowTabPane: true,
        search: [
          {
            name: "staffName",
            type: "text",
            label: "员工姓名",
            fuzzy: true,
          },
          {
            name: "workNum",
            type: "text",
            label: "工号",
            fuzzy: false,
          },
          // {
          //     name: "deptId",
          //     type: "select",
          //     label: "所属部门",
          //     fuzzy: false
          // },
          // {
          //     name: "attendanceGroupId",
          //     type: "select",
          //     label: "所属考勤组",
          //     fuzzy: false
          // },
          // {
          //     name: "shiftsId",
          //     type: "select",
          //     label: "班次",
          //     fuzzy: false
          // },
          {
            name: "attendanceDateStart",
            type: "date",
            label: "考勤开始时间",
            fuzzy: false,
          },
          {
            name: "attendanceDateEnd",
            type: "date",
            label: "考勤结束时间",
            fuzzy: false,
          },
        ],
        columns: [
          { type: "selection", width: 60 },
          { type: "index", label: "序号", width: 50 },
          { label: "员工姓名", prop: "staffName" },
          { label: "工号", prop: "workNum" },
          {
            label: "大厅",
            prop: "salaName",
            formatter: this.formatter,
            show: true,
          },
          {
            label: "部门",
            prop: "deptName",
            formatter: this.formatter,
            show: true,
          },
          // {label: "考勤组", prop: "attendanceGroupName"},
          // {label: "职位", prop: "positionName"},
          // {label: "班次", prop: "shiftsName"},
          {
            label: "考勤时间",
            prop: "attendanceDate",
            formatter: this.formatterDate,
          },
          { label: "考勤点名称", prop: "attendanceAddress" },
          { label: "事件源", prop: "eventSource" },
          // {
          //     label: "操作",
          //     width: 240,
          //     formatter: row => {
          //         return (
          //             <table-buttons noAdd noDel noEdit noView  row={row}
          //             onEdit={this.toEdit} onView={this.toView} onDel={this.toDel} />
          //         )
          //     }
          // }
        ],
      },
      drawerhistory: false,
      exportList: [],
      baseUrl: process.env.VUE_APP_API_BASE_URL + "/",
    };
  },
  created() {
    this.query.attendanceDateStart = timestampToTime(new Date(), 3);
    this.query.attendanceDateEnd = timestampToTime(new Date(), 3);
    JSON.parse(sessionStorage.getItem("userData")).id == 1
      ? (this.showBtn = true)
      : (this.showBtn = false);
  },
  methods: {
    submitFresh() {
      if (this.freshDate) {
        this.submitLoad = true;
        this.$post("/attendance/record/hik/addAttendanceHikRecordCustom", {
          attendanceDateStart: this.freshDate[0],
          attendanceDateEnd: this.freshDate[1],
        })
          .then((res) => {
            if (res.code == 1) {
              this.getData();
              this.$message.success(res.msg);
              this.dialogOpen = false;
              this.btnFreshLoading = false;
              this.submitLoad = false;
            }
          })
          .catch((error) => {
            this.$message.error(res.msg);
            this.submitLoad = false;
            this.dialogOpen = false;
            this.btnFreshLoading = false;
          });
      } else {
        this.$message.error("请选择时间范围！");
      }
    },
    cancleFresh() {
      this.dialogOpen = false;
      this.btnFreshLoading = false;
      this.freshDate = "";
    },
    // 手动更新
    handleRefresh() {
      this.btnFreshLoading = true;
      this.dialogOpen = true;
    },
    // 极速计算结果
    formatData() {
      this.btnLoading = 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;
      }
      this.$post("/attendance/record/hik/addAttendanceRecord", {
        ...params,
      }).then((res) => {
        this.btnLoading = false;
        if (res.code == 1) {
          this.$message.success("生成打卡记录成功！");
        }
      });
    },
    // 更改状态
    changeStatus(item) {
      this.$set(item, "islook", !item.islook);
    },
    // 导出记录
    lookexportHis() {
      this.$post("/attendance/export/record/list", {
        type: 1,
        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/hik/downloadTemplate",
        {},
        { type: "excel", name: "打卡记录统计" }
      )
        .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();
    },
    countDown() {
      if (this.percent == 95) {
        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;
        }

        this.$download(
          "/attendance/record/hik/exportExcel",
          {
            ...params,
          },
          { type: "excel", name: "打卡记录统计" }
        )
          .then(() => {
            this.percent = 100;
            this.progress = false;
            this.isExport = false;
          })
          .catch((error) => {
            this.percent = 100;
            this.isExport = false;
            this.progress = false;
            this.$message.error(error.message);
          });
        return;
      } else {
        this.percent = this.percent + 1;
        let that = this;
        setTimeout(function () {
          that.countDown();
        }, 100);
      }
    },
    /** 导出Excel */
    doExport() {
      if (this.isExport == true) {
        this.$message.info("考勤数据正在导出中，请勿重复点击！");
        return false;
      }

      this.isExport = true;
      this.progress = true;
      this.percent = 0;
      this.countDown();
    },
    /** 重写新增方法 */
    toAdd(row) {
      this.$refs.dialogform.add(row);
    },
    /** 重写编辑方法 */
    toEdit(row) {
      this.$refs.dialogform.edit(row);
    },
    /** 重写查看方法 */
    toView(row) {
      this.$refs.dialogform.view(row);
    },
    afterRender(data) {},
  },
};
</script>
<style scoped lang="scss">
.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;
}
.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;
    }
    cursor: pointer;
  }
}
.details {
  cursor: pointer;
}
</style>
