<template>
  <div class="fullHeight">
    <div class="searchBox whiteBlock">
      <el-form
        :inline="true"
        size="medium"
        :model="searchForm"
        ref="searchForm"
      >
        <el-form-item label="人员类型">
          <el-input
            v-model="searchForm.personType"
            :placeholder="$t('message.personnelPosition.please_enter')"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="企业名称">
          <el-input
            v-model="searchForm.enterpriseName"
            :placeholder="$t('message.personnelPosition.please_enter')"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="班组/部门">
          <el-input
            v-model="searchForm.teamDepartmentName"
            :placeholder="$t('message.personnelPosition.please_enter')"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.workerName"
            :placeholder="$t('message.personnelPosition.please_enter')"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="使用时间">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            value-format="yyyy-MM-dd hh:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="loadCardData">
            {{ $t("message.personnelPosition.beaconManage.query") }}
          </el-button>
          <el-button type="warning" plain @click="resetForm">
            {{ $t("message.personnelPosition.beaconManage.refresh") }}
          </el-button>
          <!-- 导出 -->
          <el-button type="primary" @click="exportFn">{{
            $t("message.laborMange.export")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_wrap whiteBlock">
      <el-table class="tables" :data="pointList">
        <el-table-column
          type="index"
          width="50"
          align="center"
          :label="$t('message.personnelPosition.beaconManage.table.index')"
        ></el-table-column>
        <el-table-column
          prop="personType"
          label="人员类型"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="enterpriseName"
          label="企业名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="teamDepartmentName"
          label="班组/部门"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="workerName"
          label="姓名"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="使用时间"
          align="center"
        ></el-table-column>
      </el-table>
      <el-pagination
        class="pagerBox"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="$store.state.PAGESIZRS"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :total="Number(total)"
        background
      ></el-pagination>
    </div>
    <!-- 添加卡片弹框 -->
    <el-dialog
      :modal-append-to-body="false"
      :title="cardDialogTitle"
      :visible.sync="cardDialog"
      width="667px"
      @close="close"
    >
      <div class="dialog_content">
        <el-form
          size="medium"
          :model="cardForm"
          ref="cardForm"
          :rules="cardFormRules"
          label-width="125px"
          class="dialogFormBox"
        >
          <el-form-item
            :label="$t('message.laborDev.addToBlackReason')"
            prop="addReason"
          >
            <el-input
              v-model="cardForm.addReason"
              :placeholder="$t('message.personnelPosition.please_enter')"
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('message.laborDev.addToBlackTime')"
            prop="addTime"
          >
            <el-date-picker
              v-model="cardForm.addTime"
              type="date"
              :placeholder="$t('message.laborMange.pleaseSelectADate')"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            :label="$t('message.laborDev.blackNames')"
            prop="workerId"
          >
            <!-- multiple clearable-->
            <el-select
              v-model="cardForm.workerId"
              :placeholder="$t('message.personnelPosition.please_select')"
              filterable
            >
              <el-option
                :label="item.workerName"
                :value="item.id"
                v-for="(item, index) in allPersonList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <div class="dialog-footer">
            <el-button
              class="cancleBtn"
              @click="cardDialog = false"
              icon="el-icon-circle-close"
              size="medium"
              >{{ $t("message.personnelPosition.cancel") }}
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="saveCardFn"
              size="medium"
              >{{ $t("message.personnelPosition.determine") }}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getWorkerInfoListApi } from "@/assets/js/api/personnelPosition.js";
import {
  entryRecordListApi,
  workerBlacklistAddApi,
  workerBlacklistEditApi,
  workerBlacklistDeleteApi,
} from "@/assets/js/api/laborPerson.js";
export default {
  data() {
    return {
      timeRange: [],
      searchForm: {
        personType: "",
        enterpriseName: "",
        teamDepartmentName: "",
        workerName: "",
      },
      pointList: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      cardDialogTitle: "",
      cardDialog: false,
      cardForm: {
        addReason: "",
        addTime: "",
        idCard: "",
        reason: "",
        workerId: "",
        workerName: "",
        projectSn: this.$store.state.projectSn,
      },
      cardFormRules: {
        addReason: [
          {
            required: true,
            message: this.$t("message.personnelPosition.required"),
            trigger: "blur",
          },
        ],
        addTime: [
          {
            required: true,
            message: this.$t("message.personnelPosition.mandatory"),
            trigger: "change",
          },
        ],
        workerId: [
          {
            required: true,
            message: this.$t("message.personnelPosition.mandatory"),
            trigger: "change",
          },
        ],
      },
      isAdd: false,
      allPersonList: [],
    };
  },
  mounted() {
    this.loadAllPerson();
    this.loadCardData();
  },
  methods: {
    exportFn() {
      fetch(this.$http.defaults.baseURL + "xmgl/workerAccessRecord/exportXls", {
        headers: {
          Authorization: this.$store.state.userInfo.token,
        },
      })
        .then((response) => {
          // 处理响应
          if (!response.ok) {
            throw new Error("导出失败");
          }
          return response.blob();
        })
        .then((blob) => {
          console.log("导出成功");
          // 创建一个下载链接
          const url = window.URL.createObjectURL(blob);
          // 创建一个<a>元素
          const link = document.createElement("a");
          link.href = url;
          link.download = "导出文件.xlsx"; // 指定下载文件的文件名
          // 模拟点击下载链接
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          // 释放URL对象
          window.URL.revokeObjectURL(url);
          // 处理导出的文件
          // 这里可以使用blob对象来获取导出的文件内容或者将其保存到本地
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },
    //获取所有人员
    loadAllPerson() {
      getWorkerInfoListApi({
        projectSn: this.$store.state.projectSn,
        userEnterpriseId: this.$store.state.userInfo.userEnterpriseId,
      }).then((res) => {
        this.allPersonList = res.result;
      });
    },
    addPoint(event) {
      this.isAdd = true;
      this.cardDialog = true;
      this.cardForm = {
        addReason: "",
        addTime: "",
        idCard: "",
        reason: "",
        workerId: "",
        workerName: "",
        projectSn: this.$store.state.projectSn,
      };
      this.cardDialogTitle = this.$t("message.laborDev.add2");
    },
    editPoint(item) {
      this.isAdd = false;
      this.cardDialogTitle = this.$t("message.laborDev.btn_edit"); //编辑卡片
      this.cardForm = JSON.parse(JSON.stringify(item));
      this.cardDialog = true;
    },
    removePoint(item) {
      this.$confirm(
        this.$t("message.personnelPosition.beaconManage.table.confirmText") +
          "【" +
          item.workerName +
          "】?",
        this.$t("message.personnelPosition.beaconManage.table.Tips"),
        {
          type: "warning",
        }
      ).then(() => {
        workerBlacklistDeleteApi({ id: item.id }).then((res) => {
          this.loadCardData();
          this.$message.success(
            this.$t("message.personnelPosition.delete_success")
          ); //删除成功!
        });
      });
    },
    //获取卡片列表
    loadCardData() {
      let requestData = {
        projectSn: this.$store.state.projectSn,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        ...this.searchForm,
      };
      if (this.timeRange && this.timeRange.length > 0) {
        requestData.createTime_begin = this.timeRange[0];
        requestData.createTime_end = this.timeRange[1];
      }
      entryRecordListApi(requestData).then((res) => {
        this.pointList = res.result.records;
        this.total = res.result.total;
      });
    },
    //添加或编辑卡片
    saveCardFn() {
      this.$refs["cardForm"].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            // this.cardForm.floorId = this.currentFloorDetail.floorId
            workerBlacklistAddApi(this.cardForm).then((res) => {
              this.cardDialog = false;
              this.loadCardData();
              this.$message.success(
                this.$t("message.personnelPosition.add_success")
              ); //添加成功！
            });
          } else {
            workerBlacklistEditApi(this.cardForm).then((res) => {
              this.cardDialog = false;
              this.loadCardData();
              this.$message.success(
                this.$t("message.personnelPosition.edit_success")
              ); //编辑成功！
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.searchForm = {
        personType: "",
        enterpriseName: "",
        teamDepartmentName: "",
        workerName: "",
      };
      this.timeRange = [];
      this.loadCardData();
    },

    //查看条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadCardData();
    },
    //查看页
    handleCurrentChange(val) {
      this.pageNo = val;
      this.loadCardData();
    },
    close() {
      this.$nextTick(() => {
        this.$refs.cardForm.clearValidate();
      });
    },
  },
};
</script>
<style lang="less" scoped>
.searchBox .el-form-item {
  margin: 5px 15px 0px 0;
}
</style>
