<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="工时分摊月报" name="first">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item prop="year">
            <el-date-picker
              v-model="queryParams.year"
              value-format="yyyy"
              type="year"
              placeholder="选择年"
              clearable>
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="month">
            <el-select v-model="queryParams.month" placeholder="选择月" clearable>
              <el-option v-for="item in 12" :key="item" :value="item">{{item}}月</el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="createBy">
            <el-select v-model="queryParams.createBy" placeholder="请选择操作人" clearable>
              <el-option
                v-for="item in createByOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleMakeMonth">生成月报</el-button>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table stripe v-loading="loading" :data="empwhMonthList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="年度" align="center" prop="year" />
          <el-table-column label="月度" align="center" prop="month" />
          <el-table-column label="工时合计" align="center" prop="totalWork" />
          <el-table-column label="成本合计" align="center" prop="totalCost" />
          <el-table-column label="生成时间" align="center" prop="createTime" />
          <el-table-column label="操作人" align="center" prop="createBy" />
          <el-table-column label="最后操作时间" align="center" prop="updateTime" />
          <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-view"
                @click="handleMonthInfo(scope.row)"
                v-hasPermi="['buyer:empwhmonth:info']"
              >预览</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="listForYearMonthExport(scope.row)"
                v-hasPermi="['buyer:empwhmonth:down']"
              >下载</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getListEmpwhmonth"
        />
      </el-tab-pane>
      <el-tab-pane label="工时出勤管理" name="second">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item prop="project">
            <el-input
              v-model="queryParams.projectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="totalCost">
            <el-select v-model="queryParams.createBy" placeholder="请选择操作人" clearable>
              <el-option
                v-for="item in createByOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery1">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table stripe v-loading="loading" :data="listGrroupProject" @selection-change="handleSelectionChange1">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="项目名称" align="center" prop="projectName" />
          <el-table-column label="负责人" align="center" prop="projectPeople" />
          <el-table-column label="成员人数" align="center" prop="peopleNum" />
          <el-table-column label="工时累积" align="center" prop="totalWork" />
          <el-table-column label="成本累积" align="center" prop="totalCost" />
          <el-table-column label="操作人" align="center" prop="createBy" />
          <el-table-column label="最后操作时间" align="center" prop="updateTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</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="handleCheckWork(scope.row)"
                v-hasPermi="['buyer:empworkhour:edit']"
              >考勤</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleEmpwhViewInfoTitle(scope.row)"
                v-hasPermi="['buyer:empworkhour:view']"
              >详情</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getListGrroupProject"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 生产月报对话框 -->
    <el-dialog title="填写工资" :visible.sync="makeMonthOpen" width="60%" append-to-body>
      <el-form ref="makeMonthForm" :model="makeMonthForm" :rules="makeMonthRules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="年度" prop="year">
              <el-date-picker
                v-model="makeMonthForm.year"
                value-format="yyyy"
                type="year"
                placeholder="选择年"
                @change="changeYearOrMonthOfMakeMonth"
                clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月度" prop="month">
              <el-select v-model="makeMonthForm.month" @change="changeYearOrMonthOfMakeMonth" placeholder="选择月" clearable>
                <el-option v-for="item in 12" :key="item" :value="item">{{item}}月</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table stripe v-loading="loading" :data="empworkhourMakeMonthList"
                  style="width: 100%">
          <el-table-column
            prop="name"
            label="姓名">
          </el-table-column>
          <el-table-column
            prop="dept"
            label="部门">
          </el-table-column>
          <el-table-column label="当月工资" align="center" prop="wages" width="300">
            <template slot-scope="{row ,$index}">
<!--              <el-form-item prop="wages">-->
                <el-input-number v-model="empworkhourMakeMonthList[$index].wages" label="当月工资"
                               onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'')"></el-input-number>
<!--              </el-form-item>-->
            </template>
          </el-table-column>
          <el-table-column label="当月社保五险一金等" align="center" prop="socialSecurity" width="300">
            <template slot-scope="{row ,$index}">
<!--              <el-form-item prop="socialSecurity">-->
                <el-input-number v-model="empworkhourMakeMonthList[$index].socialSecurity" label="当月工资"
                               onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'')"></el-input-number>
<!--              </el-form-item>-->
            </template>
          </el-table-column>
        </el-table>
        <el-form-item>
          <span style="color: #D9001B">提示：如果选择月份已生成过月报，再次提交将覆盖之前已生成月报</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMakeMonthForm">提 交</el-button>
        <el-button @click="makeMonthCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 考勤按钮对话框 -->
    <el-dialog :title="title" :visible.sync="checkWorkOpen" width="60%" append-to-body>
      <el-form ref="checkWorkForm" :model="checkWorkForm" :rules="checkWorkRules" label-width="80px">
        <el-row v-if="isEpmWKEdit">
          <el-col :span="12">
            <el-form-item label="年度" prop="year">
              <el-date-picker
                v-model="checkWorkForm.year"
                value-format="yyyy"
                type="year"
                placeholder="选择年"
                @change="changeYearOrMonth"
                clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="isEpmWKEdit" label="月度" prop="month">
              <el-select v-model="checkWorkForm.month" @change="changeYearOrMonth" placeholder="选择月" clearable>
                <el-option v-for="item in 12" :key="item" :value="item">{{item}}月</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-calendar v-model="timeValue">
            <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
            <template
              slot="dateCell"
              slot-scope="{date, data}">
              <div @click="clickData(data, date)" style="height: 200px;width: 200px">
                <p style="float: left">
                  {{ data.day.split('-')[2] }}
                </p>
                <div style="float: left" v-for="item in selectYearMonthList1" :key="item">
                  <img style="float: left" v-if="item == data.day" src="@/assets/images/green-point.svg">
                </div>
                <div style="float: left" v-for="item in selectYearMonthList2" :key="item">
                  <img style="float: left" v-if="item == data.day" src="@/assets/images/bue-point.svg">
                </div>
              </div>
            </template>
          </el-calendar>

          <el-form-item>
            <img src="@/assets/images/bue-point.svg">手动填写
            <img src="@/assets/images/green-point.svg">表格导入
            <span v-if="isEpmWKEdit" style="color: #D9001B;float: right">提醒：如果选择月份已有记录，将覆盖之前记录</span>
          </el-form-item>

          <el-form-item v-if="isEpmWKEdit">
            <el-upload :disabled="!checkWorkForm.year || !checkWorkForm.month"
               style="float: left"
              ref="upload"
              :action="checkWorkForm.url"
              multiple
              :headers="checkWorkForm.headers"
              :limit="checkWorkForm.limit"
              :on-success="(response, file, fileList) => {this.changeYearOrMonth();this.listEmpworkhour(this.selectDate);}"
              :file-list="fileList"
              :data="checkWorkForm">
              <el-tooltip placement="bottom" effect="light">
                <div slot="content" v-html="'只能上传xls/xlsx文件'"></div>
                <el-button :disabled="!checkWorkForm.year || !checkWorkForm.month" type="success" @click="uploadFile">导入EXCEL</el-button>
              </el-tooltip>
            </el-upload>

            <el-button style="float: left;margin-left: 10px" type="warning" @click="downTemplate" >下载EXCEL模板</el-button>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="2" style="float: right" v-if="isEpmWKEdit">
            <el-button type="primary" icon="el-icon-circle-plus" circle style="margin-top: 40px; margin-left: 10px;"
                       :disabled="this.selectDate.length <= 0" @click="handleAddEmpworkhourList"></el-button>
            <el-button type="primary" icon="el-icon-remove" circle style="margin-top: 20px" @click="handleDeleteEmpworkhourList" :disabled="multiple2"></el-button>
          </el-col>
          <el-col :span="22">
            <span v-if="isEpmWKEdit">手动填写（{{selectDate}}）：</span>
            <el-table stripe v-loading="loading" :data="empworkhourList"
                      @selection-change="handleSelectionChange2"
                      style="width: 100%;margin-top: 20px">
              <el-table-column v-if="isEpmWKEdit" type="selection" align="center"/>
              <el-table-column
                prop="name"
                label="姓名">
              <template slot-scope="{row ,$index}">
                <div v-if="row.type == '0' && isEpmWKEdit">
                  <el-select v-model="empworkhourList[$index].name"
                             filterable
                             allow-create
                             placeholder="请输入姓名" clearable>
                    <el-option
                      v-for="item in employeeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.name"
                    />
                  </el-select>
                </div>
                <div v-else>{{row.name}}</div>
              </template>
              </el-table-column>
              <el-table-column
                prop="dept"
                label="部门">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.type == '0' && isEpmWKEdit">
                    <el-input v-model="empworkhourList[$index].dept" placeholder="请输入部门" clearable  />
                  </div>
                  <div v-else>{{row.dept}}</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="cost"
                label="所耗工时">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.type == '0' && isEpmWKEdit">
                    <el-input v-model="empworkhourList[$index].cost" onkeyup="if(isNaN(value))execCommand('undo')"/>
                  </div>
                  <div v-else>{{row.cost}}</div>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="this.selectDate.length <= 0" @click="submitForm">提 交</el-button>
        <el-button @click="checkWorkCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--预览员工工时分摊月报对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-table stripe v-loading="loading" :data="empwhMonthViewList" style="width: 100%">
        <el-table-column v-if="empwhMonthViewHeader && empwhMonthViewHeader.length > 0"
                         v-for="(key,index) in empwhMonthViewHeader"
                         :prop="key" :label="key"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="empwhMonthViewHeader && empwhMonthViewHeader.length > 0"
          type="primary"
         size="medium"
         icon="el-icon-download"
          @click="listForYearMonthExport()"
        >下载</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--项目考勤详情弹框 -->
    <el-dialog title="项目考勤详情" :visible.sync="empwhViewInfoOpen" width="90%" append-to-body>
      <el-row>
        <el-col :span="12">
          <el-button type="primary" @click="handleCheckWork(selectEmpworkhour)">新增记录</el-button>
          <el-button @click="empwhViewInfoCancel">取 消</el-button>
        </el-col>
      </el-row>
      <el-row style="margin-top: 35px">
        <el-col :span="8">
          <span>{{ selectEmpworkhour.projectName }}</span>
          <el-table stripe v-loading="loading" :show-header="false" :data="empwhViewInfoOfProject" style="width: 90%;margin-top: 20px">
            <el-table-column label="key" align="left" prop="key" ></el-table-column>
            <el-table-column label="value" align="left" prop="value" ></el-table-column>
          </el-table>
        </el-col>
        <el-col :span="16">
          <span>工时考勤明细</span>
          <el-table stripe v-loading="loading" :data="empwhViewInfo" style="width: 100%;margin-top: 20px">
            <el-table-column label="年月份" align="left" prop="projectName" >
              <template slot-scope="{row ,$index}">
                {{row.year}}年{{row.month}}月
              </template>
            </el-table-column>
            <el-table-column label="成员人数" align="left" prop="peopleNum" >
              <template slot-scope="{row ,$index}">
                {{row.peopleNum}}人
              </template>
            </el-table-column>
            <el-table-column label="工时累积" align="left" prop="totalWork" >
              <template slot-scope="{row ,$index}">
                {{row.totalWork}}h
              </template>
            </el-table-column>
            <el-table-column label="成本累积" align="left" prop="totalCost" />
            <el-table-column label="操作" align="left" >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleViewCheckWork(scope.row)"
                >查看</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-download"
                  @click="handleExport(scope.row)"
                  v-hasPermi="['buyer:empwhmonth:down']"
                >下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>

  </div>
</template>

<style>
.el-calendar-table .el-calendar-day{
  width: 60px;
  height: 40px;
}
.el-calendar__button-group{
  display: none;
}
</style>
<script>
import { listEmpworkhour, workDatelist, getEmpworkhour, delEmpworkhour, addEmpworkhour,
  updateEmpworkhour,listGrroupProject,batchUpdateEmpworkhour,listForYearMonth, listByProjectId, batchAdd} from "@/api/buyer/empworkhour";
import { listEmpwhmonth, getEmpwhmonth, delEmpwhmonth, addEmpwhmonth, updateEmpwhmonth } from "@/api/buyer/empwhmonth";
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";
import { listEmployee, getEmployee, delEmployee, addEmployee, updateEmployee } from '@/api/buyer/employee'
import {getToken} from "@/utils/auth";

export default {
  name: "Empworkhour",
  data() {
    return {
      // 默认点击第一个tab
      activeName: 'first',
      // 操作人列表
      createByOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      // 选中数组
      ids1: [],
      // 非单个禁用
      single1: true,
      // 非多个禁用
      multiple1: true,

      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目分组信息
      listGrroupProject: [],
      // 选择后的分组项目对象
      selectEmpworkhour: {},
      // 项目分组信息
      empwhViewInfo: [],
      // 项目分组信息
      empwhViewInfoOfProject: [],
      empwhViewInfoOpen: false,
      // 员工工时分摊记录表格数据
      empwhMonthList: [],
      // 员工工时分摊记录表格数据
      empwhMonthViewHeader: [],
      // 员工工时分摊记录表格数据
      empwhMonthViewList: [],
      // 员工工时分摊记录表格数据
      empworkhourList: [],
      // 员工工时分摊记录总条数
      empworkhourTotal: 0,
      // 考勤页面是否显示弹出层
      checkWorkOpen: false,
      // 是查看考勤或者是编辑考勤
      isEpmWKEdit: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        remarks: null,
        projectName: null,
        year: null,
        month: null,
        createBy: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 考勤表单校验
      checkWorkRules: {
        year: [
          { required: true, message: "年度不能为空", trigger: "blur" }
        ],
        month: [
          { required: true, message: "月度不能为空", trigger: "change" }
        ],
      },

      // 当前日历值
      timeValue: '',
      // 选择年或者月刷新日历
      selectYearMonthList1: [],
      selectYearMonthList2: [],

      // 文件上传列表
      fileList: [],
      // 日历上选择日期
      selectDate: '',
      // 考勤表单参数
      checkWorkForm:{
        // 项目id
        projectId: '',
        // 年度
        year: '',
        // 月度
        month: '',
        // 工作时间
        workDate: '',
        limit: 3,
        // 上传的地址,这个地方写自己的后台地址
        url: process.env.VUE_APP_BASE_API + "/buyer/empworkhour/importTable",
        headers: { 'Authorization': 'Bearer ' + getToken() },
        ContentType:"application/json"
      },

      makeMonthForm:{},
      makeMonthOpen: false,
      empworkhourMakeMonthList: [],
      empworkhourMakeMonthTotal: 0,
      makeMonthRules: {
        year: [
          { required: true, message: "年度不能为空", trigger: "blur" }
        ],
        month: [
          { required: true, message: "月度不能为空", trigger: "change" }
        ],
        wages: [
          { required: true, message: "工资不能为空", trigger: "blur" }
        ],
        socialSecurity: [
          { required: true, message: "当月社保五险一金等不能为空", trigger: "blur" }
        ],
      },

      /** 工时分摊月报预览 **/
      wkMonthInfoOpen: false,

      // 选中的员工工时月报对象
      selectWKMonthInfo: {},

      // 选中数组
      ids2: [],
      // 非单个禁用
      single2: true,
      // 非多个禁用
      multiple2: true,

      // 员工台账列表
      employeeList: [],
    };
  },
  created() {
    this.getListEmpwhmonth();
    this.getListUser();
  },
  methods: {
    // 上传文件
    uploadFile() {
      this.$refs.upload.submit();
    },

    // 点击日期
    clickData(data, date){
      this.selectDate = data.day;
      this.listEmpworkhour(data.day);
      this.checkWorkForm.workDate = data.day;
      // 根据时间获取员工台账
      listEmployee({params:{beginTime: data.day}, employeeStatus: '1'})
        .then(response => {
          this.employeeList = response.rows
        })
    },

    // 选择年或者月
    changeYearOrMonth(){
      if(this.checkWorkForm.month && this.checkWorkForm.year){
        // 刷新日历
        this.timeValue = this.checkWorkForm.year + "-" + this.checkWorkForm.month;
        workDatelist({year: this.checkWorkForm.year,
                                month: this.checkWorkForm.month,
                                type: '1',
                                projectId: this.checkWorkForm.projectId}).then(response => {
          this.selectYearMonthList1 = response.rows;
        });
        workDatelist({year: this.checkWorkForm.year,
          month: this.checkWorkForm.month,
          type: '0',
          projectId: this.checkWorkForm.projectId}).then(response => {
          this.selectYearMonthList2 = response.rows;
        });
      }
    },

    // 切换tab
    handleClick(tab, event) {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        remarks: null,
        project: null,
        year: null,
        month: null,
        createBy: null
      }
      if(tab.index == 1){
        this.getListGrroupProject();
      }else{
        this.getListEmpwhmonth();
      }
    },

    /** 查询员工列表 */
    getListUser(){
      listUser(null).then(response => {
          this.createByOptions = response.rows;
        }
      );
    },

    /** 查询员工工时分摊月统计列表 */
    getListEmpwhmonth() {
      this.loading = true;
      listEmpwhmonth(this.queryParams).then(response => {
        this.empwhMonthList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getListGrroupProject() {
      this.loading = true;
      listGrroupProject(this.queryParams).then(response => {
        this.listGrroupProject = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 考勤取消按钮
    checkWorkCancel() {
      this.checkWorkOpen = false;
      this.checkWorkReset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remarks: null,
        delFlag: null,
        projectId: null,
        type: null,
        name: null,
        dept: null,
        cost: null,
        year: null,
        month: null,
        workDate: null
      };
      this.resetForm("form");
    },
    // 考勤表单重置
    checkWorkReset() {
      this.checkWorkForm = {
        year: null,
        month: null,
      };
      this.resetForm("checkWorkForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getListEmpwhmonth();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 搜索按钮操作 */
    handleQuery1() {
      this.queryParams.pageNum = 1;
      this.getListGrroupProject();
    },
    /** 重置按钮操作 */
    resetQuery1() {
      this.resetForm("queryForm1");
      this.handleQuery1();
    },
    // 多选框选中数据
    handleSelectionChange1(selection) {
      this.ids1 = selection.map(item => item.id)
      this.single1 = selection.length!==1
      this.multiple1 = !selection.length
    },

    /** 员工工时列表 */
    listEmpworkhour(workDate) {
      this.loading = true;
      listEmpworkhour({workDate: workDate, projectId: this.checkWorkForm.projectId}).then(response => {
        this.empworkhourList = response.rows;
        this.empworkhourTotal = response.total;
        this.loading = false;
      });
    },

    // 多选框选中数据
    handleSelectionChange2(selection) {
      this.ids2 = selection.map(item => item.name)
      this.single2 = selection.length!==1
      this.multiple2 = !selection.length
    },

    /** 手动新增考勤 */
    handleAddEmpworkhourList() {
      this.empworkhourList.push({
        type: '0',
        name: '',
        dept: '',
        cost: ''
      })
    },

    /** 手动删除考勤 */
    handleDeleteEmpworkhourList() {
      for(const name of this.ids2){
        for(const item in this.empworkhourList){
          if(this.empworkhourList[item].name == name){
            this.empworkhourList.splice(item, 1);
          }
        }
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加员工工时分摊记录";
    },

    /** 详情按钮操作 */
    handleMonthInfo(row) {
      this.selectWKMonthInfo = row;
      this.open = true;
      this.title = row.year + "年" + row.month + "月人工成本分摊表预览";
      this.loading = true;
      this.empwhMonthViewHeader = [];
      this.empwhMonthViewList = [];
      listForYearMonth({year: row.year, month: row.month}).then(response => {
        this.empwhMonthViewList = response.rows;
        if(this.empwhMonthViewList && this.empwhMonthViewList.length > 0){
          // 取最后一个综合统计的key集合这样列显示就比较全了
          this.empwhMonthViewHeader = Object.keys(this.empwhMonthViewList[this.empwhMonthViewList.length - 1]);
        }
        this.loading = false;
      });
    },

    /** 考勤按钮操作 */
    handleCheckWork(row) {
      this.isEpmWKEdit = true;
      if(!row){
        row = this.selectEmpworkhour;
      }
      this.checkWorkOpen = true;
      this.checkWorkForm.projectId = row.id;
      this.title = row.projectName + " - 考勤登记";

      let d=new Date();
      this.checkWorkForm.year = d.getFullYear() + '';
      this.checkWorkForm.month = d.getMonth() + 1;
    },

    /** 查看考勤按钮操作 */
    handleViewCheckWork(row) {
      this.isEpmWKEdit = false;
      this.checkWorkOpen = true;
      this.checkWorkForm.year = row.year;
      this.checkWorkForm.month = row.month;
      this.changeYearOrMonth();
      this.title = this.selectEmpworkhour.projectName + " - " + row.year + "年" + row.month + "月" + " - 考勤登记";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEmpworkhour(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改员工工时分摊记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["checkWorkForm"].validate(valid => {
        if (valid) {
          batchAdd({
            projectId: this.checkWorkForm.projectId,
            year: this.checkWorkForm.year,
            month: this.checkWorkForm.month,
            workDate: this.selectDate
          }, this.empworkhourList).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.checkWorkOpen = false;
            this.getListGrroupProject();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除员工工时分摊记录选中的数据项？').then(function() {
        return delEmpworkhour(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport(row) {
      this.download('buyer/empworkhour/export', {
        ...{year: row.year,
          month: row.month,
          projectId: this.checkWorkForm.projectId}
      }, `工时考勤明细.xlsx`)
    },
    /** 导出按钮操作 */
    downTemplate() {
      this.download('buyer/empworkhour/downTemplate', {
        ...this.queryParams
      }, `员工工时考勤表模板.xlsx`)
    },

    /** 导出按钮操作 */
    listForYearMonthExport(row) {
      if(row){
        this.selectWKMonthInfo = row;
      }
      this.download('buyer/empworkhour/listForYearMonthExport', {
        ...{year: this.selectWKMonthInfo.year, month: this.selectWKMonthInfo.month}
      }, `员工工时分摊月报详情.xlsx`)
    },

    // 上传文件回调函数
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    },

    // 显示月报信息录入弹出框
    handleMakeMonth(){
      this.makeMonthForm = {};
      this.makeMonthOpen = true;
      this.empworkhourMakeMonthList = [];
      this.empworkhourMakeMonthTotal = 0;
    },

    // 取消按钮
    makeMonthCancel() {
      this.makeMonthOpen = false;
      this.makeMonthForm = {};
      this.resetForm("makeMonthForm");
    },

    // 选择年或者月
    changeYearOrMonthOfMakeMonth() {
      if (this.makeMonthForm.month && this.makeMonthForm.year) {
        // 查询当月所有的考勤人员
        this.loading = true;
        listEmpworkhour({year: this.makeMonthForm.year, month: this.makeMonthForm.month}).then(response => {
          if(response.rows.length > 0){
            this.empworkhourMakeMonthList = response.rows;
            this.empworkhourMakeMonthTotal = response.total;
          }else{
            this.empworkhourMakeMonthList = [];
            this.empworkhourMakeMonthTotal = 0;
            this.$modal.msgWarning("选择时段无项目/无考勤记录/无人员信息");
          }
          this.loading = false;
        });
      }
    },

    // 生成月报提交
    submitMakeMonthForm() {
      this.$refs["makeMonthForm"].validate(valid => {
        if (valid) {
          batchUpdateEmpworkhour(this.empworkhourMakeMonthList).then(response => {
            this.$modal.msgSuccess("月报更新成功");
            this.makeMonthOpen = false;
            this.getListEmpwhmonth();
          });
        }
      });
    },

    // 员工工时详情
    handleEmpwhViewInfoTitle(row) {
      this.checkWorkForm.projectId = row.id;
      this.empwhViewInfoOpen = true,
      this.selectEmpworkhour = row;
      this.empwhViewInfoOfProject = [];
      this.empwhViewInfoOfProject.push(
        {
          key: "负责人",
          value: row.projectPeople,
        },{
          key: "项目成员人数",
          value: row.peopleNum + "人",
        },{
          key: "累积工时",
          value: row.totalWork + "h",
        },{
          key: "累积成本",
          value: row.totalCost,
        },{
          key: "开始时间",
          value: row.startDate,
        },{
          key: "结束时间",
          value: row.endDate,
        },
      );
      this.loading = true;
      listByProjectId({projectId: row.id}).then(response => {
        this.empwhViewInfo = response.rows;
        this.loading = false;
      });
    },

    // 详情返回按钮
    empwhViewInfoCancel() {
      this.empwhViewInfoOpen = false;
    }
  }
};
</script>
