<!-- 员工数据 -->

<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
    >
      <QueryFormWrapper>
        <el-col :span="6">
          <el-form-item label="员工编号" prop="employeeNo">
            <el-input
              v-model="queryParams.employeeNo"
              placeholder="请输入员工编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="员工名称" prop="employeeName">
            <el-input
              v-model="queryParams.employeeName"
              placeholder="请输入员工名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="移动电话" prop="mobilePhone">
            <el-input
              v-model="queryParams.mobilePhone"
              placeholder="请输入移动电话"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="批量编码" prop="employeeNoArr">
            <el-input
              v-model="queryParams.employeeNoArr"
              placeholder="请输入批量编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <div slot="right">
          <el-form-item label-width="0" class="text-right" style="word">
            <EasyAdvancedQuery
              class="mr10"
              label-width="98px"
              @advQuery="advQuery"
            >
              <template #default="{ model }">
                <el-row :gutter="10" type="flex">
                  <el-col :span="12">
                    <el-form-item label="固定电话" prop="fixedTelephone">
                      <el-input
                        v-model="model.fixedTelephone"
                        placeholder="请输入固定电话"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="邮箱地址" prop="email">
                      <el-input
                        v-model="model.email"
                        placeholder="请输入邮箱地址"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系地址" prop="contactAddress">
                      <el-input
                        v-model="model.contactAddress"
                        placeholder="请输入联系地址"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="个人头像" prop="photograph">
                      <el-input
                        v-model="model.photograph"
                        placeholder="请输入个人头像"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="创建时间" prop="createTime">
                      <el-date-picker
                        v-model="model.createTime"
                        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-col>
                </el-row>
              </template>
            </EasyAdvancedQuery>
            <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>
        </div>
      </QueryFormWrapper>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:employee-master:create']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handlePrint"
          >工卡打印</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:employee-master:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :columns="columnsList"
        :show-search.sync="showSearch"
        @saveSetting="getColumnsList"
        @queryTable="getList"
      />
    </el-row>

    <!-- 列表 -->
    <AutoResizer :given-height="177">
      <template #default="{ height }">
        <el-table
          v-if="columnsList.length > 0"
          ref="multipleTable"
          v-loading="loading"
          :data="list"
          :height="height"
          border
          @selection-change="tableSelected"
        >
          <el-table-column type="selection" width="55" fixed="left" />
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="员工编号"
            align="center"
            prop="employeeNo"
            min-width="130"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="员工名称"
            align="center"
            prop="employeeName"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="移动电话"
            align="center"
            prop="mobilePhone"
            min-width="130"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[3].visible"
            :key="Math.random()"
            label="固定电话"
            align="center"
            prop="fixedTelephone"
            width="130"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="邮箱地址"
            align="center"
            prop="email"
            width="110"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="联系地址"
            align="center"
            prop="contactAddress"
            width="110"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[6].visible"
            :key="Math.random()"
            label="个人头像"
            align="center"
            prop="photograph"
          >
            <template slot-scope="scope">
              <img :src="scope.row.photograph" min-width="70" height="70" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[7].visible"
            :key="Math.random()"
            label="创建时间"
            align="center"
            prop="createTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="160"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['system:employee-master:update']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                v-hasPermi="['system:employee-master:delete']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </AutoResizer>

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

    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      @open="dialogOpen"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="员工编号" prop="employeeNo">
          <el-input
            v-model="form.employeeNo"
            clearable
            placeholder="请输入员工编号"
          />
        </el-form-item>
        <el-form-item label="员工名称" prop="employeeName">
          <el-input
            v-model="form.employeeName"
            clearable
            placeholder="请输入员工名称"
          />
        </el-form-item>
        <el-form-item label="移动电话" prop="mobilePhone">
          <el-input
            v-model="form.mobilePhone"
            clearable
            placeholder="请输入移动电话"
          />
        </el-form-item>
        <el-form-item label="固定电话" prop="fixedTelephone">
          <el-input
            v-model="form.fixedTelephone"
            clearable
            placeholder="请输入固定电话"
          />
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input
            v-model="form.email"
            clearable
            placeholder="请输入邮箱地址"
          />
        </el-form-item>
        <el-form-item label="联系地址" prop="contactAddress">
          <el-input
            v-model="form.contactAddress"
            clearable
            placeholder="请输入联系地址"
          />
        </el-form-item>
        <el-form-item label="个人头像" prop="photograph">
          <!-- <el-input v-model="form.photograph" placeholder="请输入个人头像" /> -->
          <UploadAvatar ref="userAvatar" v-model="form.photograph" />
        </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>

    <!-- 工卡打印 -->
    <IssuePrint ref="issuePrinit" />
    <!-- 修改员工信息 -->
    <UpdateEmployeeForm ref="updateEmployeeForm" @updateSuccess="getList" />
  </div>
</template>

<script>
import {
  createEmployeeMaster,
  updateEmployeeMaster,
  deleteEmployeeMaster,
  getEmployeeMasterPage,
  exportEmployeeMasterExcel,
  getFilesList,
} from "@/api/mes/employeeMaster/index";
import UploadAvatar from "./components/UploadAvatar.vue";
import IssuePrint from "./components/IssuePrinit.vue";
const AccessTokenKey = "ACCESS_TOKEN";
import { mapState } from "vuex";
import { getFormColumnsList } from "@/api/system/saveColumns/index";
import { mapGetters } from "vuex";
import { isArray } from "min-dash";
import UpdateEmployeeForm from "./components/UpdateEmployeeForm.vue";

export default {
  name: "EmployeeInformation",
  components: {
    UploadAvatar,
    IssuePrint,
    UpdateEmployeeForm,
  },
  data() {
    return {
      imageUrl: "",
      fileList: [],
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // MES 员工列表主档列表
      list: [],
      // 工卡打印
      currentRows: [],
      ids: "",
      tokens: "",
      baseUrl: "",
      reportId: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        employeeNo: null,
        employeeName: null,
        mobilePhone: null,
        fixedTelephone: null,
        email: null,
        contactAddress: null,
        photograph: null,
        employeeNoArr: null,
        createTime: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        employeeNo: [
          { required: true, message: "员工编号不能为空", trigger: "blur" },
        ],
        employeeName: [
          { required: true, message: "员工名称不能为空", trigger: "blur" },
        ],
        contactAddress: [
          { required: true, message: "联系地址不能为空", trigger: "blur" },
        ],
      },
      user: {},
      // 回显
      filesList: [],
      userFiles: [],
      showImgUrl: "",
      // 显示隐藏列参数
      columns: [
        { key: 0, label: "员工编号", visible: true },
        { key: 1, label: "员工名称", visible: true },
        { key: 2, label: "移动电话", visible: true },
        { key: 3, label: "固定电话", visible: true },
        { key: 4, label: "邮箱地址", visible: true },
        { key: 5, label: "联系地址", visible: true },
        { key: 6, label: "个人头像", visible: true },
        { key: 7, label: "创建时间", visible: true },
      ],
      // 显示隐藏持久化参数
      columnsList: [],
    };
  },
  computed: {
    ...mapGetters(["userId"]),
    ...mapState({
      routeLists: (state) => state.permission.addRoutes,
    }),
  },
  created() {
    this.tokens = localStorage.getItem(AccessTokenKey);
    this.baseUrl = process.env.VUE_APP_REPORT_API;
  },
  mounted() {
    // 获取显隐列列表
    this.getColumnsList();
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      this.loading = true;
      // 执行查询
      const res = await getFilesList();
      this.fileList = res.data.list;
      const params = { ...this.queryParams, ...this.advParams };
      getEmployeeMasterPage(params)
        .then((response) => {
          this.list = response.data.list;
          this.total = response.data.total;
          // 头像
          this.list.forEach((item) => {
            this.fileList.map((val) => {
              if (val.id === item.photograph * 1) {
                item.photograph = val.url;
              }
            });
          });
          this.loading = false;
          this.reportId = this.$route.meta.reportId;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        employeeNo: undefined,
        employeeName: undefined,
        mobilePhone: undefined,
        fixedTelephone: undefined,
        email: undefined,
        contactAddress: undefined,
        photograph: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.advParams = {};
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加MES 员工列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const { id } = row;
      this.$refs.updateEmployeeForm.id = id;
      this.$refs.updateEmployeeForm.fileList = this.fileList;
      this.$refs.updateEmployeeForm.drawer = true;
    },
    // 转文件格式
    base64toFile(dataurl, filename = "photograph") {
      const arr = dataurl.split(",");

      const mime = arr[0].match(/:(.*?);/)[1];

      const suffix = mime.split("/")[1];

      const bstr = atob(arr[1]);

      let n = bstr.length;

      const u8arr = new Uint8Array(n);

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }

      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      });
    },
    /** 提交按钮 */
    submitForm() {
      const photo = this.$refs.userAvatar;
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          this.form.photograph = photo.imgsId.toString();
          updateEmployeeMaster(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        this.form.photograph = photo.imgsId;
        createEmployeeMaster(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除MES 员工列表编号为"' + id + '"的数据项?')
        .then(function () {
          return deleteEmployeeMaster(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      const params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal
        .confirm("是否确认导出所有MES 员工列表数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportEmployeeMasterExcel(params);
        })
        .then((response) => {
          this.$download.excel(response, "MES 员工列表主档.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    // 表格选中
    tableSelected(val) {
      this.currentRows = val;
      const list = this.currentRows.map((item) => item.id);
      this.ids = list.join(",");
    },
    dialogOpen() {
      this.$nextTick(() => {
        this.userFiles = this.$refs.userAvatar;
        this.userFiles.options.img = this.showImgUrl.url;
      });
    },
    // 工卡打印
    handlePrint() {
      if (this.ids === "") {
        this.$modal.msgWarning("请选择你要打印的数据行");
        return;
      }
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&id=${this.ids}`;
      this.$refs.issuePrinit.src = src;
      this.$refs.issuePrinit.title = "工卡打印";
      this.$refs.issuePrinit.dialogVisible = true;
    },
    // 高级查询
    advQuery(advQueryParams) {
      this.advParams = advQueryParams;
      this.handleQuery();
    },
    // 获取显示隐藏列
    getColumnsList() {
      const { componentName } = this.$route.meta || null;
      const params = {
        userId: this.userId,
        vueForm: componentName,
      };
      getFormColumnsList(params)
        .then((res) => {
          if (isArray(res.data)) {
            this.columnsList = res.data.length === 0 ? this.columns : res.data;
          } else {
            this.columnsList = this.columns;
          }
        })
        .catch((err) => {
          if (err) {
            this.columnsList = this.columns;
          }
        });
    },
  },
};
</script>
