<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="82px">
      <el-form-item label="项目名称" prop="projectId">
        <el-select :disabled="prjDisabled" v-model="queryParams.projectId" placeholder="请选择项目" clearable
          @change="doQuerySub()">
          <el-option v-for="(item, index) in projectOptions" :key="index" :label="item.projectName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="总包单位" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择总包单位" clearable>
          <el-option v-for="(item, index) in depts" :key="index" :label="item.deptName" :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分包商类型" prop="companyTypeId">
        <el-select v-model="queryParams.companyTypeId" placeholder="请选择分包商类型" clearable>
          <el-option value="0" label="所有"></el-option>
          <el-option value="101" label="总包人员"></el-option>
          <el-option value="102" label="监理人员"></el-option>
          <el-option value="103" label="劳务人员"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="createBy">
        <el-date-picker v-model="queryParams.attendanceTime" :picker-options="disableTime" type="date"
          placeholder="选择日期">
        </el-date-picker>
        -
        <el-date-picker v-model="queryParams.attendanceOutTime" :picker-options="disableTime" type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="姓名" prop="workerName">
        <el-input v-model="queryParams.workerName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" plain icon="el-icon-setting" size="mini" @click="handleSetting" v-if="!prjDisabled"
          v-hasPermi="['project:attendanceConfig:edit']">设置</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['project:attendance:export']">导出</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="1 == 2">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['project:attendance:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['project:attendance:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['project:attendance:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['project:attendance:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
      <el-table-column label="照片" align="center" prop="id">
        <template slot-scope="{ row }">
          <el-image :src="row.scanPhoto || row.workerPhoto" :preview-src-list="[row.scanPhoto || row.workerPhoto]"
            style="height: 60px" />
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="workerName" />
      <el-table-column label="籍贯" align="center" prop="nativePlace" />
      <el-table-column label="性别" align="center" prop="attendanceType">
        <template slot-scope="{ row }">{{
      row.workerGender == 1 ? "女" : "男"
    }}</template>
      </el-table-column>
      <el-table-column label="进场时间" align="center" prop="inTime" width="96">
        <template slot-scope="{ row }">
          <span v-if="row.attendanceTime">
            {{ row.attendanceTime | formatDateTime }}
          </span>
          <i v-else class="el-icon-close" style="color: red"></i>
        </template>
      </el-table-column>
      <el-table-column label="离场时间" align="center" prop="outTime" width="96">
        <template slot-scope="{ row }">
          <span v-if="row.attendanceOutTime">
            {{ row.attendanceOutTime | formatDateTime }}
          </span>
          <i v-else class="el-icon-close" style="color: red"></i>
        </template>
      </el-table-column>
      <el-table-column label="分包商名称" align="center" prop="companyName" />
      <el-table-column label="所属班组" align="center" prop="groupName" />
      <el-table-column label="工种" align="center" prop="workTypeName" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="1 == 2">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['project:attendance:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['project:attendance:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改劳务实名制管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="厂商编号参考字典attendance_vendors" prop="vendorsCode">
          <el-input v-model="form.vendorsCode" placeholder="请输入厂商编号参考字典attendance_vendors" />
        </el-form-item>
        <el-form-item label="工人Id" prop="workerId">
          <el-input v-model="form.workerId" placeholder="请输入工人Id" />
        </el-form-item>
        <el-form-item label="考勤时间yyyy-MM-dd HH:mm:ss" prop="attendanceTime">
          <el-input v-model="form.attendanceTime" placeholder="请输入考勤时间yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="作业面Id" prop="workPointId">
          <el-input v-model="form.workPointId" placeholder="请输入作业面Id" />
        </el-form-item>
        <el-form-item label="服务返回的JSON" prop="other">
          <el-input v-model="form.other" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="${comment}" prop="state">
          <el-input v-model="form.state" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="${comment}" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="${comment}" prop="isDel">
          <el-input v-model="form.isDel" placeholder="请输入${comment}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <attConfigDrawer ref="attDrawer"></attConfigDrawer>
  </div>
</template>

<script>
import {
  listAttendance,
  getAttendance,
  delAttendance,
  addAttendance,
  updateAttendance,
} from "@/api/project/attendance";
import {
  listAttendanceWorker,
  getAttendanceWorker,
  delAttendanceWorker,
  addAttendanceWorker,
  updateAttendanceWorker,
  queryAttendanceData,
} from "@/api/project/attendanceWorker";
import attConfigDrawer from "../attendanceConfig/attendanceConfigDrawer.vue";
export default {
  name: "Attendance",
  components: {
    attConfigDrawer,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 劳务实名制管理表格数据
      attendanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        vendorsCode: "huazhu",
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        workerName: "",
        deptId: null,
        companyTypeId: "0",
        attendanceTime: new Date(),
        attendanceOutTime: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      projectOptions: [],
      depts: [],
      prjDisabled: false,
      cfgList: [],
      disableTime: {
        disabledDate: (time) => {
          var t1 = +this.$dt("2023-1-1").$d;
          var t2 = +this.$dt(time).$d;
          var t3 = +this.$dt("2028-12-31").$d;
          return t2 < t1 || t2 > t3;
        },
      },
    };
  },
  created() {
    this.$api.publics.getMyProjectList({}).then((response) => {
      this.projectOptions = response.rows;
    });
    this.$api.publics.findAttendanceCfgList({}).then((response) => {
      this.cfgList = response.data || [];
    });
  },
  methods: {
    init(prj) {
      this.queryParams.projectId = prj.id;
      this.prjDisabled = true;
      this.doQuerySub(true);
    },
    doQuerySub(init) {
      let tmps =
        this.prjDept2 && this.prjDept2[this.queryParams.projectId]
          ? this.prjDept2[this.queryParams.projectId] || []
          : [];
      if (tmps.length > 0) {
        this.depts = tmps;
        if (tmps.length == 1) {
          this.queryParams.deptId = tmps[0].deptId;
        } else {
          this.queryParams.deptId = "";
        }
        if (init) {
          this.getList();
        }
        return;
      }
      this.$api.publics
        .queryUnitList({
          projectId: this.queryParams.projectId,
          unitTypes: "2".split(","),
        })
        .then((d) => {
          let objs = d.rows || [];
          if (!this.prjDept2) {
            this.prjDept2 = {};
          }
          this.prjDept2[this.queryParams.projectId] = objs;
          this.depts = objs;
          if (objs.length == 1) {
            this.queryParams.deptId = objs[0].deptId;
          } else {
            this.queryParams.deptId = "";
          }
          if (init) {
            this.getList();
          }
        });
    },
    handleSetting() {
      this.$refs.attDrawer.show();
    },
    /** 查询劳务实名制管理列表 */
    getList() {
      this.loading = true;
      let postData = {};
      if (this.queryParams.attendanceTime) {
        postData.attendanceTime = this.$dt(this.queryParams.attendanceTime).format(
          "YYYY-MM-DD"
        );
      }
      if (this.queryParams.attendanceOutTime) {
        postData.attendanceOutTime = this.$dt(this.queryParams.attendanceOutTime).format(
          "YYYY-MM-DD"
        );
      }
      let tmps = this.cfgList.filter(
        (d) =>
          d.projectId == this.queryParams.projectId &&
          d.subDeptId == this.queryParams.deptId
      );
      if (tmps.length > 0) {
        postData.cfgid = tmps[0].id;
      } else {
        postData.projectId = this.queryParams.projectId;
        postData.deptId = this.queryParams.deptId;
      }
      postData.pageNum = this.queryParams.pageNum;
      postData.pageSize = this.queryParams.pageSize;
      if (this.queryParams.workerName) {
        postData.workerName = this.queryParams.workerName;
      }
      if (this.queryParams.companyTypeId && this.queryParams.companyTypeId > 0) {
        postData.companyTypeId = this.queryParams.companyTypeId;
      }
      listAttendance(postData).then((response) => {
        this.attendanceList = (response.rows || []).map((it) => {
          if (it.vendorsCode != "yanzhu") {
            let dt1 = it.attendanceTime;
            let dt2 = it.attendanceOutTime;
            if (!dt1 || !dt2 || dt1 == dt2) {
              let dt = dt1 || dt2;
              if (it.remark == "E") {
                it.attendanceTime = dt;
                it.attendanceOutTime = "";
              } else {
                it.attendanceTime = "";
                it.attendanceOutTime = dt;
              }
            }
          }
          it.scanPhoto =
            it.scanPhoto && it.scanPhoto.indexOf("/profile") == 0
              ? "/jhapi" + it.scanPhoto
              : it.scanPhoto;
          return it;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vendorsCode: null,
        workerId: null,
        attendanceType: null,
        attendanceTime: null,
        deviceCode: null,
        workPointId: null,
        other: null,
        state: null,
        remark: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加劳务实名制管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAttendance(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改劳务实名制管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAttendance(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttendance(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除劳务实名制管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delAttendance(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      let postData = {};
      if (this.queryParams.attendanceTime) {
        postData.attendanceTime = this.$dt(this.queryParams.attendanceTime).format(
          "YYYY-MM-DD"
        );
      }
      if (this.queryParams.attendanceOutTime) {
        postData.attendanceOutTime = this.$dt(this.queryParams.attendanceOutTime).format(
          "YYYY-MM-DD"
        );
      }
      let tmps = this.cfgList.filter(
        (d) =>
          d.projectId == this.queryParams.projectId &&
          d.subDeptId == this.queryParams.deptId
      );
      if (tmps.length > 0) {
        postData.cfgid = tmps[0].id;
      } else {
        postData.projectId = this.queryParams.projectId;
        postData.deptId = this.queryParams.deptId;
      }
      postData.pageNum = this.queryParams.pageNum;
      postData.pageSize = this.queryParams.pageSize;
      if (this.queryParams.workerName) {
        postData.workerName = this.queryParams.workerName;
      }
      if (this.queryParams.companyTypeId && this.queryParams.companyTypeId > 0) {
        postData.companyTypeId = this.queryParams.companyTypeId;
      }

      this.download(
        "project/attendance/export",
        {
          ...postData,
        },
        `attendance_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
