<template>
  <div class="app-container">
    <div class="app-container">
      <el-form
        :inline="true"
        :model="get_table_dataParm"
        class="demo-form-inline"
      >
        <el-form-item>
          <el-input
            v-model="get_table_dataParm.parammaps.ename"
            placeholder="姓名"
            style="width: 180px"
            class="filter-item"
            size="small"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="get_table_dataParm.parammaps.departmentId"
            placeholder="部门"
            class="filter-item"
            size="small"
            filterable
            style="width: 130px"
            clearable
          >
            <el-option
              v-for="(item, index) in departmentList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="info"
            plain
            icon="el-icon-search"
            @click="form_search"
            >查询</el-button
          >
          <el-button
            size="small"
            type="info"
            plain
            icon="el-icon-refresh"
            @click="form_clear"
            >重置</el-button
          >
          <el-button
            size="small"
            type="primary"
            icon="el-icon-download"
            @click="handleExport"
            >导出</el-button
          >
          <el-button
            size="small"
            type="success"
            icon="el-icon-plus"
            @click="form_add"
            >新增</el-button
          >
        </el-form-item>
      </el-form>

      <div class="table">
        <el-table
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable"
          row-key="id"
        >
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="50px"
          >
            <template slot-scope="scope">
              <span>{{ scope.$index + (pageNum - 1) * pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.ename }}</span>
            </template>
          </el-table-column>

          <el-table-column label="部门" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.dname }}</span>
            </template>
          </el-table-column>
          <el-table-column label="电话" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.telephone }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            width="200px"
            header-align="center"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column label="顺序" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.sort }}</span>
            </template>
          </el-table-column>
          <el-table-column label="启用" header-align="center" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="change_enable(scope.$index, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            header-align="center"
            align="center"
            class-name="small-padding fixed-width"
            width="250px"
            fixed="right"
          >
            <template slot-scope="{ row }">
              <el-button type="primary" size="mini" @click="form_edit(row)">
                编辑
              </el-button>
              <el-button
                v-if="row.status != '已删'"
                size="mini"
                type="danger"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total >= 0"
          :total="total"
          :page.sync="get_table_dataParm.offset"
          :limit.sync="get_table_dataParm.pagecount"
          :page-sizes="[10, 50, 100, 200, 500]"
          :layout="'total, sizes, prev, pager, next, jumper'"
          @pagination="get_table_data"
        />
      </div>

      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        width="40%"
      >
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="deptform"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left: 50px"
        >
          <el-form-item label="姓名" prop="ename">
            <el-input ref="ename" v-model="deptform.ename" />
          </el-form-item>
          <el-form-item label="部门" prop="parentid">
            <tree-select
              :disabled="disabled"
              :height="280"
              :width="200"
              size="small"
              :data="parent"
              :default-props="defaultProps"
              clearable
              :expandAll="true"
              :node-key="nodeKey"
              :checked-keys="defaultCheckedKeys"
              @popoverHide="popoverHide"
            />
          </el-form-item>
          <el-form-item label="电话" prop="telephone">
            <el-input
              ref="telephone"
              v-model="deptform.telephone"
              maxlength="11"
            />
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input ref="remark" v-model="deptform.remark" />
          </el-form-item>

          <el-form-item label="顺序" prop="sort">
            <el-input ref="sort" v-model="deptform.sort" />
          </el-form-item>
          <el-form-item label="启用" prop="enable">
            <el-switch
              ref="enable"
              v-model="deptform.enable"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            class="cancelClose"
            @click="
              dialogFormVisible = false;
              get_table_data();
            "
            >关闭</el-button
          >
          <el-button
            class="success"
            @click="
              dialogStatus === 'create' ? add_dialog_save() : form_edit_save()
            "
            >确认</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import TreeSelect from "@/components/TreeSelect";
import waves from "@/directive/waves"; // waves directive
import Cookies from "js-cookie";
import { isIntegerZero } from "@/utils/validate";
import {
  PostDataByName,
  GetDataByName,
  transData,
  failproccess,
} from "@/api/common";
import { MessageBox } from "element-ui";
import Pagination from "@/components/Pagination";
import XLSX from "xlsx";

export default {
  name: "StaffManagement",
  components: { TreeSelect, Pagination },
  directives: { waves },

  filters: {
    menutypeFilter(menutype) {
      const menutypeMap = {
        menu: "",
        button: "warning",
      };
      return menutypeMap[menutype];
    },
  },
  data() {
    return {
      disabled: false,
      tableKey: 0,
      list: [{ deptname: "公司", id: 1, parentid: -1, remark: "" }],
      parent: [],
      parentmenu: [],
      parentButton: [],

      departmentList: [],

      requestParam: {
        name: "insertEmployees",
        parammaps: {},
      },
      deptform: {
        id: "",
        ename: "",
        remark: "",
        sort: "",
        parentid: "0",
        telephone: "",
        enable: "1",
      },
      get_table_dataParm: {
        name: "getEmployees",
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: "Map",
        parammaps: {
          ename: "",
          departmentId: "",
        },
      },

      listLoading: true,
      tableKey: 0,
      list: [],
      total: 0,

      getRecuListParm: { name: "getDepartmentCascade" },
      getRecuListBParm: {
        name: "getMenuListBRecu",
        idname: "id",
        parammaps: { id: 0 },
      },
      rules: {
        ename: [
          {
            type: "string",
            required: true,
            message: "姓名必填",
            trigger: "change",
          },
        ],
        parentid: [
          { required: true, message: "部门名称必填", trigger: "change" },
        ],
        telephone: [
          { required: true, message: "电话不能为空" },
          { min: 11, max: 11, message: "必填11个字符", trigger: "blur" },
        ],
        sort: [{ validator: isIntegerZero, trigger: "blur" }],
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "新增",
      },
      rowStyle: { maxHeight: 50 + "px", height: 45 + "px" },
      cellStyle: { padding: 0 + "px" },
      defaultProps: {
        children: "children",
        label: "title",
      },
      nodeKey: "id",
      defaultCheckedKeys: [],
    };
  },
  created() {
    this.get_table_data();
    this.get_select_list();
  },
  methods: {
    popoverHide(checkedIds, checkedData) {
      this.deptform.parentid = checkedIds;
    },

    form_search() {
      console.log("点击了查询");
      this.get_table_dataParm.offset = 1;
      this.get_table_data();
    },
    form_clear() {
      console.log("点击了重置");
      this.get_table_dataParm.parammaps.departmentId = "";
      this.get_table_dataParm.parammaps.ename = "";
      this.get_table_dataParm.offset = 1;
      this.get_table_data();
    },

    get_table_data() {
      this.listLoading = true;
      GetDataByName(this.get_table_dataParm).then((response) => {
        if (response.data.list !== null) {
          for (var i = 0; i < response.data.list.length; i++) {
            response.data.list[i].enable = parseInt(
              response.data.list[i].enable
            );
          }

          this.list = response.data.list;

          this.pageNum = response.data.pageNum;
          this.pageSize = response.data.pageSize;
          this.total = response.data.total;
        } else {
          this.list = [];
        }

        setTimeout(() => {
          this.listLoading = false;
        }, 0.5 * 1000);
      });
    },
    get_select_list() {
      GetDataByName(this.getRecuListParm).then((response) => {
        if (response.data.list !== null) {
          this.parentmenu = transData(
            response.data.list,
            "id",
            "parentid",
            "children"
          );
        }
      });

      GetDataByName({
        name: "getDepartmentsSelect",
        offset: 0,
        pagecount: 0,
        parammaps: {},
      }).then((response) => {
        console.log("部门下拉框", response);
        this.departmentList = response.data.list;
      });
    },
    refreshDownList() {
      for (var val of this.parentmenu) {
        this.parent = [];
        this.parent.push({
          id: val.id,
          title: val.title,
          parentid: val.parentid,
        });
      }
    },
    resetRequestParam() {
      this.deptform.parentid = "0";
      this.deptform.departmentid = "0";
      this.deptform.ename = "";
      this.deptform.remark = "";
      this.deptform.sort = "0";
      this.deptform.telephone = "";
      this.deptform.id = "";
      this.deptform.enable = 1;
    },
    form_add() {
      this.resetRequestParam();
      this.dialogStatus = "create";
      this.parent = this.parentmenu;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    add_dialog_save() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.requestParam.name = "insertEmployees";

          if (this.deptform.parentid === "") this.deptform.parentid = "0";

          this.requestParam.parammaps = {
            id: "",
            ename: this.deptform.ename,
            telephone: this.deptform.telephone,
            remark: this.deptform.remark,
            sort: this.deptform.sort,
            departmentId: this.deptform.parentid,
            enable: this.deptform.enable,
          };

          PostDataByName(this.requestParam).then((response) => {
            console.log("新增保存发送参数", this.requestParam);
            if (response.msg !== "fail") {
              this.get_table_data();
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                duration: 2000,
              });
            } else {
              this.$notify({
                title: "失败",
                message: "保存失败",
                type: "error",
                duration: 2000,
              });
            }
          });
        }
      });
    },

    form_edit(row) {
      this.parent = this.parentmenu;
      console.log("row=====>", row);
      this.defaultCheckedKeys = [row.departmentid];
      console.log(this.defaultCheckedKeys);
      this.deptform.departmentid = row.departmentid;
      this.deptform.parentid = row.departmentid;
      this.deptform.ename = row.ename;
      this.deptform.remark = row.remark;
      this.deptform.sort = row.sort;
      this.deptform.telephone = row.telephone;
      this.deptform.id = row.id;
      this.deptform.enable = row.enable;
      this.dialogStatus = "update";

      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    form_edit_save() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.requestParam.name = "updateEmployees";

          this.requestParam.parammaps = {
            id: this.deptform.id,
            ename: this.deptform.ename,
            telephone: this.deptform.telephone,
            remark: this.deptform.remark,
            sort: this.deptform.sort,
            departmentId: this.deptform.parentid,
            enable: this.deptform.enable,
          };

          console.log(this.requestParam);
          PostDataByName(this.requestParam).then((response) => {
            console.log("编辑保存发送参数", this.requestParam);
            if (response.msg !== "fail") {
              this.get_table_data();
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                duration: 2000,
              });
            } else {
              this.$notify({
                title: "失败",
                message: "保存失败",
                type: "error",
                duration: 2000,
              });
            }
          });
        }
      });
    },
    change_enable(index, row) {
      this.requestParam.name = "updateEmployees";
      this.requestParam.parammaps = {
        id: row.id,
        ename: row.ename,
        telephone: row.telephone,
        remark: row.remark,
        sort: row.sort,
        departmentId: row.departmentid,
        enable: row.enable,
      };

      PostDataByName(this.requestParam).then((response) => {
        console.log("编辑保存发送参数", this.requestParam);
        if (response.msg !== "fail") {
          this.get_table_data();
          this.dialogFormVisible = false;
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            duration: 2000,
          });
        } else {
          this.$notify({
            title: "失败",
            message: "保存失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    handleDelete(row) {
      MessageBox.confirm("确认删除此信息？", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.requestParam.name = "delEmployees";
        this.requestParam.parammaps = {
          id: row.id,
        };
        PostDataByName(this.requestParam).then(() => {
          this.get_table_data();
          this.dialogFormVisible = false;
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000,
          });
        });
      });
    },
    async handleExport() {
      try {
        const exportParams = {
          name: "getEmployees",
          returntype: "Map",
          parammaps: this.get_table_dataParm.parammaps,
        };

        const response = await GetDataByName(exportParams);
        if (response.msg !== "ok") {
          this.$message.error("获取导出数据失败");
          return;
        }

        const data = response.data.list || [];
        if (data.length === 0) {
          this.$message.warning("暂无数据可导出");
          return;
        }

        const headers = [
          "序号",
          "姓名",
          "部门",
          "电话",
          "备注",
          "顺序",
          "启用状态",
        ];

        const rows = data.map((item, index) => [
          index + 1,
          item.ename || "",
          item.dname || "",
          item.telephone || "",
          item.remark || "",
          item.sort,
          item.enable === 1 ? "启用" : "禁用",
        ]);

        const wb = XLSX.utils.book_new();
        const wsData = [headers, ...rows];
        const ws = XLSX.utils.aoa_to_sheet(wsData);

        const colWidths = [
          { wch: 8 },
          { wch: 15 },
          { wch: 20 },
          { wch: 15 },
          { wch: 30 },
          { wch: 10 },
          { wch: 10 },
        ];
        ws["!cols"] = colWidths;

        XLSX.utils.book_append_sheet(wb, ws, "职工列表");

        const fileName = `职工列表_${this.getFormattedDateTime()}.xlsx`;

        XLSX.writeFile(wb, fileName);
        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("导出失败");
      }
    },
    getFormattedDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      return `${year}${month}${day}${hours}${minutes}${seconds}`;
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 15px;
  background-color: #f5f7fa;

  .demo-form-inline {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    margin-bottom: 15px;

    :deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 10px;
      vertical-align: top;

      // 统一输入框和选择框高度
      .el-input,
      .el-select {
        .el-input__inner {
          height: 32px;
          line-height: 32px;
        }
      }
    }

    :deep(.el-button) {
      margin-left: 5px;
      height: 32px;
      line-height: 30px;
      padding: 0 15px;
      font-weight: 500;
      border-radius: 4px;
      font-size: 14px;
      transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }

      &[type="primary"] {
        background-color: #409eff;
        border-color: #409eff;
        &:hover {
          background-color: #66b1ff;
          border-color: #66b1ff;
        }
      }

      &[type="success"] {
        background-color: #67c23a;
        border-color: #67c23a;
        &:hover {
          background-color: #85ce61;
          border-color: #85ce61;
        }
      }

      &[type="info"] {
        &.is-plain {
          color: #909399;
          background: #f4f4f5;
          border-color: #d3d4d6;
          &:hover {
            color: #409eff;
            background-color: #ecf5ff;
            border-color: #b3d8ff;
          }
        }
      }

      &[type="danger"] {
        background-color: #f56c6c;
        border-color: #f56c6c;
        &:hover {
          background-color: #f78989;
          border-color: #f78989;
        }
      }

      // 图标样式
      [class*="el-icon-"] {
        margin-right: 5px;
        & + span {
          margin-left: 0;
        }
      }
    }
  }

  .table {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

    :deep(.el-table) {
      .el-button--mini {
        height: 32px;
        padding: 0 15px;
        font-weight: 500;
        border-radius: 4px;
        transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
        margin: 2px 4px;

        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }

        &[type="primary"] {
          background-color: #409eff;
          border-color: #409eff;
          &:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
          }
        }

        &[type="danger"] {
          background-color: #f56c6c;
          border-color: #f56c6c;
          &:hover {
            background-color: #f78989;
            border-color: #f78989;
          }
        }
      }
    }
  }
}

.search {
  margin-bottom: 15px;
}

.operation {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
}

// 弹窗按钮样式
:deep(.el-dialog) {
  .dialog-footer {
    padding: 15px 20px;
    text-align: right;
    background: #f8f9fa;
    border-top: 1px solid #e9ecef;
    border-radius: 0 0 4px 4px;

    .el-button {
      height: 32px;
      line-height: 30px;
      padding: 0 20px;
      font-size: 14px;
      font-weight: 500;
      border-radius: 4px;
      transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      margin-left: 10px;

      &:first-child {
        margin-left: 0;
      }

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }

      &.cancelClose {
        color: #606266;
        background: #fff;
        border-color: #dcdfe6;
        &:hover {
          color: #409eff;
          border-color: #c6e2ff;
          background-color: #ecf5ff;
        }
      }

      &.success {
        color: #fff;
        background-color: #67c23a;
        border-color: #67c23a;
        &:hover {
          background-color: #85ce61;
          border-color: #85ce61;
        }
      }
    }
  }
}
</style>
