<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="姓名" prop="userId">
            <el-select v-model="queryParams.userId" filterable clearable @change="handleQuery">
              <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发放月份" prop="payMonth">
            <el-date-picker clearable v-model="queryParams.payMonth" type="month" value-format="yyyy-MM-dd"
              placeholder="请选择发放月份">
            </el-date-picker>
          </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-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="['oa:wage: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="['oa:wage: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="['oa:wage: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="['oa:wage:export']">导出</el-button>
      </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-upload2" size="mini" @click="handleImport"
              v-hasPermi="['oa:wage:export']">上传社保公积金</el-button>
          </el-col>

          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="wageList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="姓名" align="center" prop="user.nickName" />
          <el-table-column label="部门" align="center" prop="dept.deptName" />
          <!-- <el-table-column label="基础工资" align="center" prop="baseSalary" />
      <el-table-column label="工龄工资" align="center" prop="yearSalary" />
      <el-table-column label="岗位工资" align="center" prop="postSalary" />
      <el-table-column label="绩效工资" align="center" prop="performanceSalary" />
      <el-table-column label="注册测绘师" align="center" prop="certificatesSubsidy" />
      <el-table-column label="过节补贴" align="center" prop="festivalSubsidy" />
      <el-table-column label="稳岗补贴" align="center" prop="postStableSubsidy" />
      <el-table-column label="高温补贴" align="center" prop="highTemperatureSubsidy" />
      <el-table-column label="考勤扣款" align="center" prop="attendanceDeduct" />
      <el-table-column label="应发小计" align="center" prop="payableWage" /> -->
          <el-table-column label="公积金单位部分" align="center" prop="houseFund" />
          <!-- <el-table-column label="养老保险" align="center" prop="endowmentInsurance" />
      <el-table-column label="失业保险" align="center" prop="unemploymentInsurance" />
      <el-table-column label="医疗保险" align="center" prop="medicalInsurance" />
      <el-table-column label="水韵物管费" align="center" prop="propertyFee" />
      <el-table-column label="扣款小计" align="center" prop="deductTotal" /> -->
          <el-table-column label="社保单位部分" align="center" prop="socialSecurityUnit" />
          <!-- <el-table-column label="个税" align="center" prop="individualIncomeTax" />
      <el-table-column label="实发工资" align="center" prop="paidWage" /> -->
          <!-- <el-table-column label="发放日期" align="center" prop="payDay" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payDay, '{y}-{m}-{d}') }}</span>
        </template>
</el-table-column> -->
          <el-table-column label="发放月份" align="center" prop="payMonth" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.payMonth, '{y}-{m}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['oa:wage:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['oa:wage: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-col>
    </el-row>
    <!-- 添加或修改员工工资对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入员工id" />
        </el-form-item>
        <el-form-item label="基础工资" prop="baseSalary">
          <el-input v-model="form.baseSalary" placeholder="请输入基础工资" />
        </el-form-item>
        <el-form-item label="工龄工资" prop="yearSalary">
          <el-input v-model="form.yearSalary" placeholder="请输入工龄工资" />
        </el-form-item>
        <el-form-item label="岗位工资" prop="postSalary">
          <el-input v-model="form.postSalary" placeholder="请输入岗位工资" />
        </el-form-item>
        <el-form-item label="绩效工资" prop="performanceSalary">
          <el-input v-model="form.performanceSalary" placeholder="请输入绩效工资" />
        </el-form-item>
        <el-form-item label="注册测绘师" prop="certificatesSubsidy">
          <el-input v-model="form.certificatesSubsidy" placeholder="请输入注册测绘师" />
        </el-form-item>
        <el-form-item label="过节补贴" prop="festivalSubsidy">
          <el-input v-model="form.festivalSubsidy" placeholder="请输入过节补贴" />
        </el-form-item>
        <el-form-item label="稳岗补贴" prop="postStableSubsidy">
          <el-input v-model="form.postStableSubsidy" placeholder="请输入稳岗补贴" />
        </el-form-item>
        <el-form-item label="高温补贴" prop="highTemperatureSubsidy">
          <el-input v-model="form.highTemperatureSubsidy" placeholder="请输入高温补贴" />
        </el-form-item>
        <el-form-item label="考勤扣款" prop="attendanceDeduct">
          <el-input v-model="form.attendanceDeduct" placeholder="请输入考勤扣款" />
        </el-form-item>
        <el-form-item label="应发小计" prop="payableWage">
          <el-input v-model="form.payableWage" placeholder="请输入应发小计" />
        </el-form-item>
        <el-form-item label="公积金" prop="houseFund">
          <el-input v-model="form.houseFund" placeholder="请输入公积金" />
        </el-form-item>
        <el-form-item label="养老保险" prop="endowmentInsurance">
          <el-input v-model="form.endowmentInsurance" placeholder="请输入养老保险" />
        </el-form-item>
        <el-form-item label="失业保险" prop="unemploymentInsurance">
          <el-input v-model="form.unemploymentInsurance" placeholder="请输入失业保险" />
        </el-form-item>
        <el-form-item label="医疗保险" prop="medicalInsurance">
          <el-input v-model="form.medicalInsurance" placeholder="请输入医疗保险" />
        </el-form-item>
        <el-form-item label="水韵物管费" prop="propertyFee">
          <el-input v-model="form.propertyFee" placeholder="请输入水韵物管费" />
        </el-form-item>
        <el-form-item label="扣款小计" prop="deductTotal">
          <el-input v-model="form.deductTotal" placeholder="请输入扣款小计" />
        </el-form-item>
        <el-form-item label="社保单位部分" prop="socialSecurityUnit">
          <el-input v-model="form.socialSecurityUnit" placeholder="请输入社保单位部分" />
        </el-form-item>
        <el-form-item label="个税" prop="individualIncomeTax">
          <el-input v-model="form.individualIncomeTax" placeholder="请输入个税" />
        </el-form-item>
        <el-form-item label="实发工资" prop="paidWage">
          <el-input v-model="form.paidWage" placeholder="请输入实发工资" />
        </el-form-item>
        <el-form-item label="发放日期" prop="payDay">
          <el-date-picker clearable v-model="form.payDay" type="date" value-format="yyyy-MM-dd" placeholder="请选择发放日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发放月份" prop="payMonth">
          <el-date-picker clearable v-model="form.payMonth" type="date" value-format="yyyy-MM-dd" placeholder="请选择发放月份">
          </el-date-picker>
        </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>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-change="handleFileUploadChange"
        :on-success="handleFileSuccess" :auto-upload="false" drag v-loading="uploadLoading"
        element-loading-text="正在上传，请稍等">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { deptTreeSelectNew } from "@/api/system/user";
import { listWage, getWage, delWage, addWage, updateWage } from "@/api/oa/wage/wage";
import { downloadTemplate } from "@/api/file/project";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "Wage",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工工资表格数据
      wageList: [],
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        deptId: null,
        baseSalary: null,
        yearSalary: null,
        postSalary: null,
        performanceSalary: null,
        certificatesSubsidy: null,
        festivalSubsidy: null,
        postStableSubsidy: null,
        highTemperatureSubsidy: null,
        attendanceDeduct: null,
        payableWage: null,
        houseFund: null,
        endowmentInsurance: null,
        unemploymentInsurance: null,
        medicalInsurance: null,
        propertyFee: null,
        deductTotal: null,
        socialSecurityUnit: null,
        individualIncomeTax: null,
        paidWage: null,
        payDay: null,
        payMonth: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "上传社保公积金",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部'Content-Type': 'multipart/form-data', 
        headers: { 'Authorization': "Bearer " + getToken() },
        data: undefined,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/oa/wage/uploadSheet"
      },
      uploadLoading: false,
      uploadFormData: undefined,
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询员工工资列表 */
    getList() {
      this.loading = true;
      listWage(this.queryParams).then(response => {
        this.wageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelectNew().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        wageId: null,
        userId: null,
        deptId: null,
        baseSalary: null,
        yearSalary: null,
        postSalary: null,
        performanceSalary: null,
        certificatesSubsidy: null,
        festivalSubsidy: null,
        postStableSubsidy: null,
        highTemperatureSubsidy: null,
        attendanceDeduct: null,
        payableWage: null,
        houseFund: null,
        endowmentInsurance: null,
        unemploymentInsurance: null,
        medicalInsurance: null,
        propertyFee: null,
        deductTotal: null,
        socialSecurityUnit: null,
        individualIncomeTax: null,
        paidWage: null,
        payDay: null,
        payMonth: 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.wageId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加员工工资";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const wageId = row.wageId || this.ids
      getWage(wageId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改员工工资";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.wageId != null) {
            updateWage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const wageIds = row.wageId || this.ids;
      this.$modal.confirm('是否确认删除员工工资编号为"' + wageIds + '"的数据项？').then(function () {
        return delWage(wageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/wage/export', {
        ...this.queryParams
      }, `wage_${new Date().getTime()}.xlsx`)
    },
    handleImport() {
      this.upload.open = true;
    },
    /**Excel文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.uploadLoading = true;
    },
    /* Excel文件改变时 */
    handleFileUploadChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.uploadFormData = new FormData();
      this.uploadFormData.append("file", file);
      this.upload.data = this.uploadFormData;
    },
    /** Excel文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.uploadLoading = false;
      this.fileList = [];
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.$refs["uploadRef"].clearFiles();
      this.getList();
    },
    /* Excel上传提交按钮 */
    submitUpload() {
      this.$refs['uploadRef'].submit();
    },
    /* 下载模板 */
    importTemplate() {
      const path = '/profile/upload/template/userWage.xlsx'
      downloadTemplate(path).then(res => {
        const blob = new Blob([res])
        saveAs(blob, '社保公积金模版.xlsx');
      });
    },
  }
};
</script>
