<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="employeeName">
        <el-input v-model="queryParams.employeeName" placeholder="员工姓名" clearable style="width: 250px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <treeselect style="width: 250px" :default-expand-level="1" v-model="queryParams.deptId" :options="deptOptions"
          :normalizer="normalizer" placeholder="选择部门" />
      </el-form-item>
      <el-form-item label="职位" prop="postId">
        <el-select v-model="queryParams.postId" placeholder="请选择" style="width: 250px">
          <el-option v-for="item in postOptions" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="employeeMobile">
        <el-input v-model="queryParams.employeeMobile" placeholder="请输入手机号" clearable style="width: 250px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="日期" prop="attendanceDate">
        <el-date-picker v-model="queryParams.attendanceDate" style="width: 250px" value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['attendance:info:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['attendance:info:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
          v-hasPermi="['attendance:info:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList">
      <el-table-column label="序号" type="index" width="50"align="center"/>
      <el-table-column label="员工姓名" align="center" prop="employeeName" min-width="80" />
      <el-table-column label="部门" align="center" prop="deptName" min-width="100" />
      <el-table-column label="职位" align="center" prop="position" min-width="100" />
      <el-table-column label="手机号" align="center" prop="employeeMobile" min-width="100" />
      <el-table-column label="日期" align="center" prop="attendanceDate" min-width="100" />
      <el-table-column label="上班打卡" align="center" prop="workStartTime" min-width="100" />
      <el-table-column label="下班打卡" align="center" prop="workEndTime" min-width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['attendance:info:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['attendance:info:delete']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-detail" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="员工姓名" prop="employeeName">
              <el-input v-model="form.employeeName" placeholder='点击选择' readonly @click.native="openSingle"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="display: none;">
            <el-form-item label="员工Id" style="display: none;">
              <el-input v-model="form.employeeId" placeholder='员工Id' disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="部门">
              <el-input v-model="form.deptName" placeholder='部门' disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="职位">
              <el-input v-model="form.position" placeholder='职位' disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机号">
              <el-input v-model="form.employeeMobile" placeholder='手机号' disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日期" prop="attendanceDate">
              <el-date-picker value-format="yyyy-MM-dd" v-model="form.attendanceDate" type="date" placeholder="选择日期"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上班打卡" prop="workStartTime">
              <el-time-picker v-model="form.workStartTime" value-format="HH:mm" format="HH:mm" :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }" style="width: 100%;" placeholder="上班时间">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="下班打卡" prop="workEndTime">
              <el-time-picker v-model="form.workEndTime" value-format="HH:mm" format="HH:mm" :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }" style="width: 100%;" placeholder="下班时间">
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </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>
    <!-- 详情对话框 -->
    <el-dialog :title="title" :visible.sync="openDetail" width="800px" append-to-body>
      <div class="widget-list">
        <div class="fx-field x-grid-col-12">
          <div class="field-label">
            <span class="field-required">*</span>
            <div class="field-name">员工姓名</div>
          </div>
          <div class="field-component">
            <span>{{ form.employeeName }}</span>
          </div>
        </div>
        <div class="fx-field x-grid-col-12">
          <div class="field-label">
            <div class="field-name">部门</div>
          </div>
          <div class="field-component">
            <span>{{ form.deptName }}</span>
          </div>
        </div>
        <div class="fx-field x-grid-col-12">
          <div class="field-label">
            <div class="field-name">职位</div>
          </div>
          <div class="field-component">
            <span>{{ form.position }}</span>
          </div>
        </div>
        <div class="fx-field x-grid-col-12">
          <div class="field-label">
            <div class="field-name">手机号</div>
          </div>
          <div class="field-component">
            <span>{{ form.employeeMobile }}</span>
          </div>
        </div>
        <div class="fx-field x-grid-col-12">
          <div class="field-label">
            <div class="field-name">日期</div>
          </div>
          <div class="field-component">
            <span>{{ form.attendanceDate }}</span>
          </div>
        </div>
        <div class="fx-field x-grid-col-12">
          <div class="field-label">
            <div class="field-name">上班打卡时间</div>
          </div>
          <div class="field-component">
            <span>{{ form.workStartTime }}</span>
          </div>
        </div>
        <div class="fx-field x-grid-col-12">
          <div class="field-label">
            <div class="field-name">下班打卡时间</div>
          </div>
          <div class="field-component">
            <span>{{ form.workEndTime }}</span>
          </div>
        </div>
      </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 text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </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>
    <PeopleSelect ref="peopleSelect" type="single" :isCheck="true" :open="singlePeopleOpen"
      @cancel="singlePeopleOpen = false" @submit="submitSingle"></PeopleSelect>
  </div>
</template>

<script>
import { listSimplePosts } from "@/api/system/post";
import { getEmployeeInfo } from "@/api/system/user";
import { listInfo, getInfo, delInfo, addInfo, updateInfo, exportInfo } from "@/api/personnel/attendance/info/index";
import PeopleSelect from "@/components/PeopleSelect/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listDept } from "@/api/system/dept";
import { getBaseHeader } from "@/utils/request";
export default {
  name: "SystemDictType",
  components: {
    PeopleSelect,
    Treeselect,
  },
  data() {
    return {
      postOptions: [],
      // 部门列表
      deptOptions: [], // 部门属性结构
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      singlePeopleOpen: false,
      open: false,
      openDetail: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/personnel/attendance/info/import-excel'
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        employeeName: undefined,
        deptId: undefined,
        postId: undefined,
        employeeMobile: undefined,
        attendanceDate: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        employeeName: [
          { required: true, message: "请选择" }
        ],
        attendanceDate: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        workStartTime: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        workEndTime: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getListDept();
  },
  methods: {
    getEmployee() {
      getEmployeeInfo(this.form.employeeId).then(response => {
        let employeeInfo = response.data;
        this.form.deptName = employeeInfo.deptName;
        this.form.position = employeeInfo.position;
        this.form.employeeMobile = employeeInfo.phone;
        // this.form.entryDate = employeeInfo.entryDate;
        // this.form.probationEndDate = employeeInfo.probationEndDate;
      });
    },
    //打开选人弹窗
    openSingle() {
      this.singlePeopleOpen = true;
    },
    submitSingle(userNamelist, nikeNamelist, userIdList) {
      console.log(userNamelist);
      this.form.employeeName = nikeNamelist.join();
      this.form.employeeId = userIdList.join();
      this.getEmployee();
      this.singlePeopleOpen = false;
    },
    /** 查询部门列表 */
    getListDept() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "id");
      });
      listSimplePosts().then(response => {
        // 处理 postOptions 参数
        this.postOptions = [];
        this.postOptions.push(...response.data);
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      listInfo(this.queryParams).then(response => {
        this.typeList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.files = [],
        this.form = {
          employeeName: undefined,
          employeeId: undefined,
          deptName: undefined,
          position: undefined,
          employeeMobile: undefined,
          attendanceDate: undefined,

          workStartTime: undefined,
          workEndTime: undefined,
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },

    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset();
      const id = row.id;
      getInfo(id).then(response => {
        this.form = response.data;
        this.openDetail = true;
        this.title = "详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据项?').then(function () {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      // 执行导出
      this.$modal.confirm('是否确认导出所有数据项?').then(() => {
        this.exportLoading = true;
        return exportInfo(params);
      }).then(response => {
        this.$download.excel(response, '员工考勤信息.xls');
        this.exportLoading = false;
      }).catch(() => { });
    },
     /** 导入按钮操作 */
     handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('personnel/attendance/info/get-import-template', {
      }, `考勤导入模版.xlsx`)
    },
    // 文件上传中处理
    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("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style lang="scss" scoped>
.widget-wrapper>.widget-list {
  display: flex;
  flex-wrap: wrap;
}

.x-grid-col-6 {
  width: 50%;
}

.x-grid-col-12 {
  width: 100%;
}

.fx-field {
  line-height: 20px;
  padding: 7px 12px 12px;
  position: relative;
}

.fx-field .field-label {
  word-wrap: break-word;
  color: #141e31;
  display: flex;
  font-weight: 600;
  line-height: 20px;
  padding: 5px 0;
  position: relative;
  word-break: break-word;
}

.fx-field .field-label .field-required {
  color: #eb5050;
  margin-left: -6px;
  position: relative;
}

.fx-field .field-label .field-name {
  overflow: hidden;
}

.field-component {
  word-wrap: break-word;
  background: #f5f6f8;
  border-radius: 2px;
  color: #141e31;
  font-size: 14px;
  line-height: 20px;
  min-height: 32px;
  padding: 6px 8px;
  white-space: pre-wrap;
  word-break: break-word;
}

ul {
  padding-left: 0px !important;
}

.el-tag+.el-tag {
  margin-left: 10px;
}
</style>
