<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="工号" prop="userWorkNum">
        <el-input
          v-model="queryParams.userWorkNum"
          placeholder="请输入工号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker
          v-model="daterangePayDate"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="实发金额" prop="fsalary">
        <el-input
          v-model="queryParams.fsalary"
          placeholder="请输入实发金额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布状态" prop="paySlipStatus">
        <el-select v-model="queryParams.paySlipStatus" placeholder="请选择发布状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.pay_slip_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['salary:salaryslip:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleImport"
          v-hasPermi="['salary:salaryslip:add']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-finished"
          size="mini"
          @click="publishWithClick"
          v-hasPermi="['salary:salaryslip:add']"
        >批量发布
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-finished"
          size="mini"
          @click="publishWithOneClick"
        >一键发布
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="6">
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>工资表目录</span>
          </div>
          <div class="item">
            <el-table border v-loading="loading" :data="excelInfo.list" @selection-change="handleSelectionChange"
                      @row-click="rowClick">
              <el-table-column label="工资列表" align="center" prop="source"/>
              <el-table-column label="日期" align="center" prop="payDate" width="100"/>
            </el-table>
            <pagination
              v-show="excelInfo.total>0"
              :total="excelInfo.total"
              :page.sync="excelInfo.pageNum"
              :limit.sync="excelInfo.pageSize"
              @pagination="getList"
            />
          </div>
        </el-card>

      </el-col>
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ excelInfo.source }}</span>
          </div>
          <div class="item">
            <el-table border v-loading="loading" :data="salaryslipList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="40" align="center"/>
              <el-table-column label="日期" align="center" prop="payDate"/>
              <el-table-column label="工号" align="center" prop="userWorkNum"/>
              <el-table-column label="姓名" align="center" prop="userName"/>
              <el-table-column label="实发金额" align="center" prop="fsalary"/>
              <el-table-column label="用户编号" align="center" prop="userCode"/>
              <el-table-column label="发布状态" width="80" align="center" prop="paySlipStatus">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.pay_slip_status" :value="scope.row.paySlipStatus"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="250">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['salary:salaryslip:remove']"
                  >删除
                  </el-button>
                  <el-button style="margin-left: 10px"
                             size="mini"
                             type="text"
                             icon="el-icon-finished"
                             v-hasPermi="['salary:salaryslip:edit']"
                             @click="publishWithClick(scope.row)"
                  >发布
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-tickets"
                    @click="openPayrollDetails(scope.row.id)"
                    v-hasPermi="['salary:salaryslip:edit']"
                  >详细
                  </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"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加或修改工资条基础对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="用户编号" prop="userCode">
          <el-input v-model="form.userCode" placeholder="请输入用户编号"/>
        </el-form-item>
        <el-form-item label="工号" prop="userWorkNum">
          <el-input v-model="form.userWorkNum" placeholder="请输入用户工号"/>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="日期" prop="payDate">
          <el-date-picker clearable size="small"
                          v-model="form.payDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实发金额" prop="fsalary">
          <el-input v-model="form.fsalary" placeholder="请输入实发金额"/>
        </el-form-item>
        <el-form-item label="发布状态">
          <el-radio-group v-model="form.paySlipStatus">
            <el-radio
              v-for="dict in dict.type.pay_slip_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </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="detailed.title" :visible.sync="detailed.open" width="700px" append-to-body>
      <div>
        <el-descriptions class="margin-top" :column="2" :size="size" border>
          <el-descriptions-item v-for="item in detailedForm">
            <template slot="label">
              {{ item.title }}
            </template>
            {{ item.value }}
          </el-descriptions-item>
        </el-descriptions>
      </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"
        :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">
          <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="cancelTemplate">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSalaryslip,
  getSalaryslip,
  delSalaryslip,
  addSalaryslip,
  updateSalaryslip,
  exportSalaryslip, importTempSalaryslip, getSalaryslips, push, excelList
} from '@/api/salary/salaryslip'
import {getToken} from '@/utils/auth'

export default {
  name: 'Salaryslip',
  dicts: ['pay_slip_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工资条基础表格数据
      excelInfo: {
        source: '',
        list: [],
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      salaryslipList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangePayDate: [],
      detailed: {
        title: '完整工资条',
        open: false
      },
      detailedForm: {},
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // 设置上传的请求头部
        headers: {Authorization: 'Bearer ' + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/salary/salaryslip/importData'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userCode: null,
        userWorkNum: null,
        userName: null,
        payDate: null,
        salary: null,
        fsalary: null,
        paySlipStatus: null,
        isDelete: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    rowClick(row, column, event) {
      this.queryParams.source = row.source
      this.excelInfo.source = row.source
      listSalaryslip(this.queryParams).then(response => {
        this.salaryslipList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询工资条基础列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangePayDate && '' !== this.daterangePayDate) {
        this.queryParams.params['beginPayDate'] = this.daterangePayDate[0]
        this.queryParams.params['endPayDate'] = this.daterangePayDate[1]
      }
      excelList(this.excelInfo).then(response => {
        this.excelInfo.list = response.rows
        this.excelInfo.total = response.total
        this.loading = false
        this.queryParams.source = this.excelInfo.list[0].source
        listSalaryslip(this.queryParams).then(response => {
          this.salaryslipList = []
          this.salaryslipList = response.rows
          this.total = response.total
          this.loading = false
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userCode: null,
        userWorkNum: null,
        userName: null,
        payDate: null,
        salary: null,
        fsalary: null,
        paySlipStatus: '0',
        isDelete: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePayDate = []
      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 = '添加工资条基础'
    },
    /** 打开完整工资条点击事件 */
    openPayrollDetails(id) {
      this.detailed.open = true
      this.detailedForm = []
      getSalaryslips(id).then(re => {
        console.log(re.data[0])
        this.detailedForm = re.data[0]
        this.detailedForm.forEach(i => {
          console.log(i)
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getSalaryslip(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) {
            updateSalaryslip(this.form).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addSalaryslip(this.form).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除工资条基础编号为"' + ids + '"的数据项？').then(function () {
        return delSalaryslip(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 批量发布*/
    publishWithClick(row) {
      let ids = []
      if (row.id) {
        ids = [row.id]
      } else {
        ids = this.ids
        if (0 === ids.length) {
          this.$modal.msgError('请选择一个工资条')
          return
        }
      }
      this.$modal.confirm('是否确认发布工资条').then(function () {
        return push(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('发布成功')
      }).catch(() => {
      })
    },
    /** 一键发布*/
    publishWithOneClick() {
      const ids = this.ids
      this.$modal.confirm('是否确认一键发布所有工资条').then(function () {
        return push(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('发布成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal.confirm('是否确认导出所有工资条基础数据项？').then(() => {
        this.exportLoading = true
        return exportSalaryslip(queryParams)
      }).then(response => {
        this.$download.name(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    },
    handleImport() {
      this.upload.title = '工资信息导入'
      this.upload.open = true
    },
    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(response.msg, '导入结果', {dangerouslyUseHTMLString: true})
      this.cancel()
      this.getList()
    },
    importTemplate() {
      importTempSalaryslip().then(response => {
        this.$download.name(response.msg)
      })
    },
    submitFileForm() {
      this.$refs.upload.submit()
    },
    cancelTemplate() {
      this.upload.open = false
      this.form.moneyType = '2'
    }
  }
}
</script>
