<template>
  <div class="app-container">

    <div class="company" v-if="!$store.state.user.tenantId">
      <el-input
        style="width: 200px"
        placeholder="公司名称"
        size="small"
        prefix-icon="el-icon-search"
        v-model="gsInfo.tenantName"
        @keyup.enter.native="getGsInfoList">
      </el-input>
      <div class="cp-content" style="width: 200px">
        <div :class="gsInfo.active_id===item.id?'cp-item active':'cp-item'" @click="changCompany(item.id)" v-for="item in gsInfo.list">{{ item.name }}</div>
      </div>
    </div>

    <div :class="$store.state.user.tenantId?'content-all':'content'">

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="年份" prop="year">
          <el-date-picker
            v-model="queryParams.year"
            type="year"
            size="mini"
            placeholder="选择年"
            value-format="yyyy">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            size="mini"
            placeholder="选择月"
            format="MM"
            value-format="MM">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="员工姓名" prop="empName">
          <el-input
            v-model="queryParams.empName"
            placeholder="请输入员工姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            v-model="queryParams.deptName"
            placeholder="请输入部门名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </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="['pay:requireAttendanceReport: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="['pay:requireAttendanceReport: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="['pay:requireAttendanceReport:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['pay:requireAttendanceReport:import']"
          >导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['pay:requireAttendanceReport:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="requireAttendanceReportList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="年份" align="center" prop="year" min-width="80"/>
        <el-table-column label="月份" align="center" prop="month" min-width="80"/>
        <el-table-column label="员工姓名" align="center" prop="empName" min-width="140" :show-overflow-tooltip="true"/>
        <el-table-column label="部门名称" align="center" prop="deptName" min-width="140" :show-overflow-tooltip="true"/>
        <el-table-column label="休息类型" align="center" prop="restType" min-width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.pay_work_rest_type" :value="scope.row.restType"/>
          </template>
        </el-table-column>
        <el-table-column label="应出勤天数" align="center" prop="requireDays" min-width="110"/>
        <el-table-column label="出勤天数" align="center" prop="avtiveDays" min-width="100"/>
        <el-table-column label="出勤小时数" align="center" prop="attendanceHours" min-width="100"/>
        <el-table-column label="加班小时数" align="center" prop="overtimeHours" min-width="100"/>
        <el-table-column label="放假天数" align="center" prop="holidays" min-width="100"/>
        <el-table-column label="放假小时数" align="center" prop="holidayHours" min-width="100"/>
        <el-table-column label="请假天数" align="center" prop="leaveDays" min-width="100"/>
        <el-table-column label="备注" align="center" prop="remark" min-width="100"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['pay:requireAttendanceReport:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['pay:requireAttendanceReport: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"
      />

    </div>

    <!-- 添加或修改应出勤报对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="年份" prop="year">
              <el-date-picker style="width: 100%;"
                v-model="form.year"
                type="year"
                placeholder="选择年"
                value-format="yyyy">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月份" prop="month">
              <el-date-picker style="width: 100%;"
                v-model="form.month"
                type="month"
                placeholder="选择月"
                format="MM"
                value-format="MM">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="empName">
              <el-input placeholder="请选择员工姓名" readonly v-model="form.empName" @focus="selectEmployee">
                <i slot="suffix" class="el-input__icon el-icon-search" style="color:#0f00d1; font-weight: bolder"></i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input hidden v-model="form.deptName" placeholder="请输入部门名称" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应出勤天数" prop="requireDays">
              <el-input v-model="form.requireDays" placeholder="请输入应出勤天数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出勤天数" prop="avtiveDays">
              <el-input v-model="form.avtiveDays" placeholder="请输入出勤天数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出勤小时数" prop="attendanceHours">
              <el-input v-model="form.attendanceHours" placeholder="请输入出勤小时数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加班小时数" prop="overtimeHours">
              <el-input v-model="form.overtimeHours" placeholder="请输入加班小时数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="放假天数" prop="holidays">
              <el-input v-model="form.holidays" placeholder="请输入放假天数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="放假小时数" prop="holidayHours">
              <el-input v-model="form.holidayHours" placeholder="请输入放假小时数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假天数" prop="leaveDays">
              <el-input v-model="form.leaveDays" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择员工信息 -->
    <el-dialog title="双击选择员工信息" :visible.sync="emp.open" width="900px" append-to-body top="6vh">
      <div>
        <el-form :model="emp.queryParams" :inline="true" label-width="70px">
          <el-form-item label="员工名称" prop="name" style="margin-bottom: 10px">
            <el-input
              v-model="emp.queryParams.name"
              placeholder="请输入员工名称"
              clearablesize="small"
              @keyup.enter.native="empQuery"
            />
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <el-button type="primary" icon="el-icon-search" size="small" @click="empQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-table border v-loading="emp.loading" :data="emp.list" @row-dblclick="empRowChange">
          <el-table-column label="员工姓名" align="center" prop="name" :show-overflow-tooltip="true" min-width="120"/>
          <el-table-column label="所属部门" align="center" prop="deptName" :show-overflow-tooltip="true" min-width="120"/>
          <el-table-column label="状态" align="center" prop="deleted">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.pay_del_status" :value="scope.row.deleted"/>
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="sex">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
            </template>
          </el-table-column>
          <el-table-column label="年龄" align="center" prop="age" />
          <el-table-column label="手机号" align="center" prop="phone" min-width="100"/>
          <el-table-column label="身份证号" align="center" prop="idcard" min-width="100" />
          <el-table-column label="休息类型" align="center" prop="restType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.pay_work_rest_type" :value="scope.row.restType"/>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="emp.total>0"
          :total="emp.total"
          :page.sync="emp.queryParams.pageNum"
          :limit.sync="emp.queryParams.pageSize"
          @pagination="empQuery"
        />

        <div slot="footer" class="dialog-footer">
          <el-button @click="empCancel">取 消</el-button>
        </div>
      </div>

    </el-dialog>

    <!-- 应出勤报表导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&date=' + upload.date+ '&tenantId=' + upload.tenantId"
        :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>
          <div class="el-upload__date">
            <span>请选择应出勤月份：</span>
            <el-date-picker
              v-model="upload.date"
              type="month"
              size="mini"
              placeholder="选择月"
              value-format="yyyy-MM"
              style="width:40%;">
            </el-date-picker>
          </div>
          <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>

  </div>
</template>

<script>
import { listRequireAttendanceReport, getRequireAttendanceReport, delRequireAttendanceReport, addRequireAttendanceReport, updateRequireAttendanceReport } from "@/api/pay/requireAttendanceReport";
import { listEmployeeInfo } from "@/api/pay/employeeInfo";
import { getToken } from "@/utils/auth";
import { listTenant } from "@/api/pay/tenant";

export default {
  name: "RequireAttendanceReport",
  dicts: ['sys_user_sex', 'pay_del_status', 'pay_work_rest_type'],
  data() {
    return {
      // 公司信息
      gsInfo:{
        tenantName:'',
        active_id:this.$store.state.user.tenantId,
        list:[]
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应出勤报表格数据
      requireAttendanceReportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantId: undefined,
        year: undefined,
        month: undefined,
        employeeId: undefined,
        empName: undefined,
        deptName: undefined,
        restType: undefined,
        requireDays: undefined,
        avtiveDays: undefined,
        attendanceHours: undefined,
        overtimeHours: undefined,
        holidays: undefined,
        holidayHours: undefined,
        leaveDays: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        year: [
          { required: true, message: "年份不能为空", trigger: "blur" }
        ],
        month: [
          { required: true, message: "月份不能为空", trigger: "blur" }
        ],
        empName: [
          { required: true, message: "员工姓名不能为空", trigger: "change" }
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "change" }
        ],
        requireDays: [
          { required: true, message: "应出勤天数不能为空", trigger: "blur" }
        ],
        avtiveDays: [
          { required: true, message: "出勤天数不能为空", trigger: "blur" }
        ]
      },
      // 应出勤导入参数
      upload: {
        // 是否显示弹出层（应出勤导入）
        open: false,
        // 弹出层标题（应出勤导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的应出勤数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pay/requireAttendanceReport/import",
        date: "",
        tenantId: undefined
      },
      /** 选择员工*/
      emp: {
        // 是否显示弹出层
        open: false,
        // 列表遮罩层
        loading: true,
        // 列表查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined
        },
        // 表格数据
        list: [],
        // 总条数
        total: 0,
      },
    };
  },
  created() {
    if (!this.$store.state.user.tenantId) {
      this.getGsInfoList()
    }else {
      this.gsInfo.active_id = this.$store.state.user.tenantId
      this.getList();
    }
  },
  methods: {
    // 获取左侧公司列表
    getGsInfoList(){
      listTenant({ name: this.gsInfo.tenantName }).then(response => {
        if(response.rows.length>0){
          this.gsInfo.list = response.rows;
          this.gsInfo.active_id = this.gsInfo.list[0].id
          this.getList()
        }else{
          this.$alert(`没有查到相关公司，暂无数据！`, `提示`, {
            type: 'warning'
          });
        }
      });
    },
    // 选择公司
    changCompany(id){
      this.gsInfo.active_id = id
      this.getList()
    },
    /** 查询应出勤报列表 */
    getList() {
      this.loading = true;
      this.queryParams.tenantId = this.gsInfo.active_id;
      listRequireAttendanceReport(this.queryParams).then(response => {
        this.requireAttendanceReportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        tenantId: undefined,
        year: undefined,
        month: undefined,
        employeeId: undefined,
        empName: undefined,
        deptName: undefined,
        restType: undefined,
        requireDays: undefined,
        avtiveDays: undefined,
        attendanceHours: undefined,
        overtimeHours: undefined,
        holidays: undefined,
        holidayHours: undefined,
        leaveDays: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      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 = "添加应出勤报";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getRequireAttendanceReport(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改应出勤报";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.tenantId = this.gsInfo.active_id;
          if (this.form.id != null) {
            updateRequireAttendanceReport(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addRequireAttendanceReport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除应出勤报编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delRequireAttendanceReport(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pay/requireAttendanceReport/export', {
        ...this.queryParams
      }, `requireAttendanceReport_${new Date().getTime()}.xlsx`)
    },
    // 选择员工
    selectEmployee(){
      this.emp.open = true;
      this.emp.queryParams.pageNum = 1;
      this.empQuery();
    },
    /** 员工列表查询 */
    empQuery() {
      this.emp.loading = true;
      this.emp.queryParams.tenantId = this.gsInfo.active_id
      listEmployeeInfo(this.emp.queryParams).then(response => {
        this.emp.list = response.rows;
        this.emp.total = response.total;
        this.emp.loading = false;
      });
    },
    /** 员工选择弹出框关闭*/
    empCancel() {
      this.emp.open = false
    },
    // 客户选择 选中数据
    empRowChange(val) {
      this.form.employeeId = val.id;
      this.form.empName = val.name;
      this.form.deptId = val.deptId;
      this.form.deptName = val.deptName;
      this.form.restType = val.restType;
      this.emp.open = false;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "应出勤报表导入";
      this.upload.open = true;
      this.upload.tenantId = this.gsInfo.active_id;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('pay/requireAttendanceReport/importTemplate', {
      }, `attendance_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    // 文件上传成功处理
    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();
      this.$loading().close();
    },
    // 提交上传文件
    submitFileForm() {
      if (this.isEmpty(this.upload.date)) {
        this.$alert('请选择应出勤月份', '信息', {
          confirmButtonText: '确定',
          customClass:'message_box_alert'
        }).catch((err) => {
          console.log(err)
        })
      } else {
        this.$refs.upload.submit();
      }
    },
    //判断字符是否为空的方法
    isEmpty(obj) {
      if (typeof obj == "undefined" || obj == null || obj == "" || obj.length ==0) {
        return true;
      } else {
        return false;
      }
    }
  }
};
</script>

<style scoped lang="scss">
.app-container {
  display: flex;
  .company {
    border-radius: 5px;
    width: 230px;
    height: calc(100vh - 115px);
    overflow-y: auto;
    .cp-content {
      margin-top: 20px;
      .cp-item {
        cursor: pointer;
        padding: 6px 10px 6px 5px;
        color: #424242;
        font-size: 14px;
        &:hover {
          background: #f6f6f6;
        }
      }
      .active{
        background: #edf6ff;
      }
    }
  }
  .content{
    padding-left: 15px;
    width: calc(100% - 250px);
    .el-button--medium {
      padding: 2px 0px;
    }
  }
  .content-all{
    width: 100%;
    .el-button--medium {
      padding: 2px 0px;
    }
  }
}
</style>
