<template>
  <div style=" position: relative; background: #fff; padding: 20px; min-height: calc(100vh - 160px);">
    <el-tabs v-model="activeName2" type="card">

      <div class="inline-block-btn-list">
        <el-button v-if="activeName2 == 'type_1'" type="primary" @click="addHoliday">添加假期</el-button>
      </div>

      <el-tab-pane label="假期规则" name="type_1">
        <el-table v-loading="loading" ref="multipleTable" :data="tableData" :border="false" tooltip-effect="dark">
          <el-table-column prop="name" label="假期名称"></el-table-column>
          <el-table-column prop="min_time" label="请假单位" align="center">
            <template slot-scope="scope">
              <span>按小时请假</span>
            </template>
          </el-table-column>

          <el-table-column label="余额规则" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.balance_enabled == 1">
                <span v-if="scope.row.grant_type == 1">
                  按月发放
                </span>
                <span v-if="scope.row.grant_type == 2">
                  按年发放
                </span>
                <span v-if="scope.row.grant_type == 3">
                  手工发放
                </span>
                <span v-if="scope.row.grant_type == 4">
                  加班转换得到
                </span>
              </div>
              <div v-else>
                未开启余额
              </div>

            </template>
          </el-table-column>



          <el-table-column label="操作" align="center">
            <template slot-scope="scope">

              <el-button type="text" @click="set_review_status(scope.row.id)">编辑
              </el-button>

              <el-button style="color:#f56c6c" type="text" @click="dlete(scope.row.id)">删除
              </el-button>

              <el-button style="color:#606266" type="text" @click="exactly(scope.row.id)">详情
              </el-button>

            </template>
          </el-table-column>
        </el-table>


      </el-tab-pane>

      <el-tab-pane label="员工假期余额" name="type_2">
        <!-- 员工假期余额 -->
        <div class="inline-block-btn-list">

          <el-cascader clearable :options="dept_tree" change-on-select v-model="department_id"
            ref="dept1" @change="onFilterChanged"
            placeholder="选择部门" style="width:120px;" class="gap-right-8"></el-cascader>

          <el-select v-model="target_id_set" filterable multiple :multiple-limit='3' placeholder="选择员工进行筛选（最多3个）"
            @change="onFilterChanged" class="gap-right-8" style="width:250px;margin-left:10px;">
            <el-option v-for="item in employeeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <div>
            <el-tabs v-model="getid" @tab-click="getIdClass" v-if="tableData.length!=0">
              <el-tab-pane v-for="item in tableData" v-if="item.balance_enabled==1" :name="item.id.toString()" :key="item.id" :label="item.name"></el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <el-table v-loading="loading" ref="multipleTable" :data="typeTData" :border="false" tooltip-effect="dark"
          style="margin-top:20px;">


          <el-table-column label="姓名" width="120">
            <template slot-scope="scope">
              <div>{{scope.row.name}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="dept_name" label="部门">

          </el-table-column>
          <el-table-column label="入职时间">
            <template slot-scope="scope">
              {{dateFormatter('','',scope.row.accedence_time)}}
            </template>
          </el-table-column>
          <!-- <el-table-column :label="holidayName+ '余额'"> -->
          <el-table-column label="余额">
            <template slot-scope="scope">
              <div>{{scope.row.balance || '0'}}</div>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="getReturn(scope.row)">修改假期余额</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane v-if="employId>0" :label="nameId+'-'+holidayName" name="type_3">
        <div class="typeThree" v-if="activeName2 == 'type_3'" style="padding:0 15px;">
          <div class="picture" style="padding-top: 20px;padding-bottom: 15px;">
            <img style="width: 35px;height:35px;border-radius: 50%;"
              :src="img_url ||'static/images/head_default.png' " />
            <!-- <img  v-if="img_url=='' ||img_url== undefined " style="width: 35px;height:35px;border-radius: 50%;" src="static/images/head_default.png" /> -->

            <div class="pictureOne">
              <div style="color: #606266;font-size: 16px;">{{nameId}}-假期使用记录</div>
              <div style="color:#909399;font-size:12px;">{{dept_name}}</div>
            </div>
          </div>
          <!-- <el-tabs v-model="changeType" @tab-click="handleClickType">

        </el-tabs> -->
        <div v-loading="balanceLoad">
          <div>
            <el-tabs v-model="getid" @tab-click="getIdMoney" v-if="tableData.length!=0">
              <!-- @tab-click="handleClickType(item)"   -->
              <el-tab-pane v-for="(item,index) in tableData" :key="index" v-if="item.balance_enabled == 1"
                :name="item.id.toString()" :label="item.name">

              </el-tab-pane>

            </el-tabs>
          </div>


          <div style="padding-top: 20px;padding-bottom: 20px;">当前总余额 {{balance}}小时 <el-button style="margin-left: 29px;"
              @click="changeMoney()">增加余额</el-button>
          </div>
          
          <el-table
            :data="moneyList"
            style="width: 100%">
            <el-table-column prop="create_time" label="增加时间" width="140">
              <template slot-scope="scope">
                <div>{{dateTimeFormatter('','',scope.row.create_time)}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="balance" align="center" label="剩余时长" width="300">
              <template slot-scope="scope">
                <div>{{scope.row.balance}}小时<span v-if="scope.row.expire_time != 0" :style="pastDue(scope.row.expire_time)?'color:#ff2020':''">(有效期至{{dateTimeFormatter('','',scope.row.expire_time)}}<span v-if="pastDue(scope.row.expire_time)">,已过期</span>)</span></div>
              </template>
            </el-table-column>

            <el-table-column
              prop="remark" align="center"
              show-overflow-tooltip
              label="备注/原因">
            </el-table-column>

            
            <el-table-column
              prop="type" align="center"
              label="来源">
              <template slot-scope="scope">
                <span v-if="scope.row.type == 1">手工发放的</span>
                <span v-if="scope.row.type == 2">系统自动发放的</span>
                <span v-if="scope.row.type == 3">下班打卡转换得到</span>
                <span v-if="scope.row.type == 4">请假申请扣除的</span>
                <span v-if="scope.row.type == 5">手工发放</span>
                <span v-if="scope.row.type == 6">加班转换</span>
              </template>
            </el-table-column>

            
            <el-table-column
              prop="address" align="center"
              label="操作">
              <template slot-scope="scope">
                <div v-if="scope.row.total != -1" style="color:rgb(95 172 243);cursor:pointer" @click="balanceList(scope.row.id)">余额明细</div>
              </template>
            </el-table-column>
          </el-table>

          <!-- <div class="text_item" v-if="moneyList.length == 0 " style="text-align: center;"> 暂无数据</div>
          <el-timeline style="width: 100%;" v-if="moneyList.length !=0 ">
            <el-timeline-item v-for="(activity, index) in moneyList" :key="index" :icon="activity.icon"
              :type="activity.type.toString()" :color="activity.color" :size="activity.size">


              <div style="display: flex;justify-content : space-between;">
                <div style="width: 150px;line-height:15px;">
                  {{dateTimeFormatter('','',activity.create_time)}}
                </div>
                <div style="text-align:left;width:10%">
                  <div><span>{{activity.balance}}小时</span></div>
                </div>
                <div style="text-align:left;width:65%">
                  <div>{{activity.remark}}</div>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline> -->
        </div>

        </div>
      </el-tab-pane>

      <center style="margin:20px 0;">
        <el-pagination background layout="total,sizes, prev, pager, next" :page-size="pageLimit" :page-sizes="[10, 20, 50, 100]" :total="totalCount"
          @size-change="handleSizeChange" :current-page.sync="currentPage" @current-change="changePage"></el-pagination>
      </center>

    </el-tabs>

    <el-dialog width="520px" :visible.sync="outerVisible" class="balanceStatement" @close="deductClose">
      <el-dialog
        width="520px"
        title="扣除假期余额"
        :visible.sync="detainVisible"
        append-to-body>
        <el-form :model="deductTime" ref="deductTaskForm" label-width="100px" style="padding-right:20px;" v-loading="taskFormLoadj">
          <!-- <el-form-item :label=" '修改' + holidayName"> -->
          <el-form-item label="扣除" prop="time" :rules="[{ required: true, message: '请输入时长', trigger: 'blur' }]">
            <el-col :span="12">
              <el-input auto-complete="off" :min='1' type="number" v-model="deductTime.time" @onkeyup="this.value=this.value.replace(/\D/g,'')" @afterpaste="this.value=this.value.replace(/\D/g,'')"></el-input>
            </el-col>
            <el-col :span="5">小时</el-col>
          </el-form-item>
          <el-form-item label="理由" prop="remark" :rules="[{ required: true, message: '请输入扣除原因', trigger: 'blur' }]">
            <el-input type="textarea" placeholder="请输入理由" rows="5" v-model="deductTime.remark"></el-input>
          </el-form-item>
          <el-form-item style=" text-align: right;">
            <el-button @click="deductDialogn('deductTaskForm')">取 消</el-button>
            <el-button type="primary" :loading="loading" @click="deductDialogC('deductTaskForm')">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      
      <div v-loading="outerLoad">
        <span style="font-size:17px">余额明细 (当前记录余额：{{outerBalance.balance}}小时)</span><a @click="detainVisible = true" style="color:#268DEC;text-decoration:underline;font-size:16px;padding-left:15px;" v-if="!pastDue(outerBalance.expire_time)">扣除假期余额</a>
        <p style="margin:8px 0 14px 0;color:#ff2020;">注意：当余额超过有效期，余额失效</p>
        <div class="balanceLists" v-if="outerList.length>0">
          <div v-for="(item,index) in outerList" :key="index">
            <p style="margin:20px 0 10px 0;"><span v-if="item.create_time" style="margin-right:20px;">{{item.create_time}}</span><span>{{item.total}}小时</span><span v-if="item.expire_time">(有效期至<span :style="pastDue1(item.expire_time)?'color:#ff2020':''">{{item.expire_time}}</span>)</span></p>
            <p style="margin:0;overflow:hidden; text-overflow:ellipsis;display:-webkit-box; -webkit-box-orient:vertical;-webkit-line-clamp:1 ;">理由：{{item.remark}}<span v-if="item.type_mark">（{{item.type_mark}}）</span></p>
          </div>
        </div>
        <div v-else>
          <p style="text-align:center;margin-top:40px;font-size:16px;color:#828181">暂无记录</p>
        </div>
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button @click="outerVisible = false">取 消</el-button>
        <el-button type="primary" @click="detainVisible = true">打开内层 Dialog</el-button>
      </div> -->
    </el-dialog>


    <el-dialog class="attendance_group" title="详情" custom-class="exactlY" :visible.sync="ExactlyOpen" width="540px"
      top="50px">
      <el-form style="padding-right:20px;padding-left:30px;">

        <el-form-item label="假期名称:" label-width="100px">
          {{taskform.name}}
        </el-form-item>
        <el-form-item label="请假时长核算:" label-width="100px" v-show="false">

          <span v-if="taskform.calculation_type == 1">工作日</span>
          <span v-if="taskform.calculation_type == 2">自然日</span>
        </el-form-item>

        <el-form-item label="奖扣积分" label-width="100px" class="oneYear">

          每请假一小时扣{{taskform.point}}分
        </el-form-item>
        <el-form-item label="设置员工假期余额：" label-width="140px" class="exactly">
          <span v-if="taskform.balance_enabled== 0">否</span>
          <span v-if="taskform.balance_enabled == 1">是</span>
        </el-form-item>
        <div v-if="taskform.balance_enabled == 1">
          <el-form-item label="余额发放方式:" label-width="100px">
            <span v-if="taskform.grant_type == 1">每月</span>
            <span v-if="taskform.grant_type == 2">每年</span>
            <span v-if="taskform.grant_type == 3">手工发放</span>
            <span v-if="taskform.grant_type == 4">加班转换</span>
          </el-form-item>

          <el-form-item label="额度:" label-width="100px" class="oneYear">
            每人
            <span v-if="taskform.grant_type == 1">每月</span>
            <span v-if="taskform.grant_type == 2">每年</span>
            <span v-if="taskform.grant_type == 3">手工</span>
            <span v-if="taskform.grant_type == 4">加班转换</span>

            发放{{taskform.grant_total}}小时
          </el-form-item>



          <el-form-item label="有效期:" prop="expire_type" class="twoYear" label-width="100px">

            <span v-if="taskform.expire_type == 0">永久</span>
            <span v-if="taskform.expire_type == 1">每年过期</span>
            <span v-if="taskform.expire_type == 2">每月过期</span>
          </el-form-item>
        </div>
        <el-button style="margin-left: 150px;margin-top: 15px;" @click="ExactlyOpen = false;">取消</el-button>
      </el-form>
    </el-dialog>

    <el-dialog class="attendance_group" :title='title' :visible.sync="ReviewDetailDialogVisible"
      :before-close="openClose" width="640px" top="50px">
      <el-form :model="taskform" ref="newTaskForm" :rules="rules" @submit.native.prevent style="padding-right:20px;">

        <el-form-item label="假期名称" prop="name" label-width="100px">
          <el-col :span="15">
            <el-input auto-complete="off" placeholder="请输入假期名称" max='20' v-model="taskform.name"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="新员工请假" label-width="100px">
          <div>入职即可请假</div>
        </el-form-item>

        <!-- <el-form-item label="适用范围:" prop="point" label-width="100px">
           <div>全公司<span style="color: #409EFF;cursor: pointer;padding-left: 10px;" @click="changeShpw">修改</span></div>
          </el-form-item> -->


        <!-- <el-form-item label="最小请假单位:" prop="fixed_cycle" label-width="100px">
            <el-select

              filterable
              clearable
              placeholder="选择任务周期"
              class="gap-right-8 first-element-btn"
              style="width:290px;"
            >
              <el-option

              ></el-option>
            </el-select>
              <div style="width: 323px;color:　#909399; font-size: 13px;">员工以半天为最小单位选择时间，考勤报表按天统计</div>
          </el-form-item> -->
        <!--
               <el-option
                v-for="item in fixed_cycle"
                :key="item.id"
                :label="item.type"
                :value="item.id"
              ></el-option>
           -->
        <el-form-item label="奖扣积分" label-width="100px" class="oneYear">
          每请假一小时扣<el-input v-model="taskform.point" oninput ="value=value.replace(/[^\d]/g,'')"></el-input><span
            style="display: inline-block;margin-left: 17px;">分</span>

          <div style="width: 390px;color:　#909399; font-size: 13px;"> 员工以小时为最小单位选择时间，考勤报表按小时统计</div>
        </el-form-item>

        <el-form-item label="请假时长核算" prop="calculation_type" label-width="100px" v-show="false">
          <el-select v-model="taskform.calculation_type" filterable clearable placeholder="请选择核算方式"
            class="gap-right-8 first-element-btn" style="width:290px;">
            <el-option v-for="item in calculation" :key="item.id" :label="item.content" :value="item.id"></el-option>
          </el-select>
          <div style="width: 390px;color:　#909399; font-size: 13px;" v-show="false">请假时段中不包含员工的休息日，例如为排班的双休日、法定节假日</div>
        </el-form-item>
        <el-form-item label="设置员工假期余额" label-width="125px" class="exactly">
          <el-switch v-model="balance_enabled" @change="changeBalande"></el-switch>
        </el-form-item>
        <div v-if="balance_enabled">
          <el-form-item label="余额发放方式" prop="grant_type" label-width="100px">
            <el-select v-model="taskform.grant_type" filterable clearable @change="changgeName" placeholder="选择余额发放方式"
              class="gap-right-8 first-element-btn" style="width:290px;">
              <el-option v-for="item in grant_type" :key="item.id" :label="item.content" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="发放日期" label-width="100px">
            <el-time-picker

              placeholder="任意时间点">
            </el-time-picker>
          </el-form-item> -->

          <el-form-item label="额度配置规则" prop="point" label-width="100px">
            <div>固定额度</div>
          </el-form-item>
          <div style="margin-bottom: 24px;">
            <el-form-item label="额度" prop="grant_total" label-width="100px" class="oneYear">
              每人
              <span v-if="taskform.grant_type == 1">每月</span>
              <span v-if="taskform.grant_type == 2">每年</span>
              <span v-if="taskform.grant_type == 3">手工</span>
              <span v-if="taskform.grant_type == 4">加班转换</span>
              发放<el-input v-model="taskform.grant_total" oninput ="value=value.replace(/[^\d]/g,'')" style="padding:0 10px;"></el-input><span
                style="display: inline-block;margin-left: 17px;">小时</span>
            </el-form-item>
            <!-- <el-checkbox style="margin-left: 201px;" v-model="checked">按实际工作时长发放余额</el-checkbox> -->
          </div>

          <div style="margin-bottom: 24px;">
            <el-form-item label="有效期" prop="expire_type" class="twoYear" label-width="100px">
              <el-select v-model="taskform.expire_type" filterable clearable placeholder="请选择有效期"
                class="gap-right-8 first-element-btn" style="width:290px;">
                <el-option v-for="item in expire_type" :key="item.id" :label="item.content" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-checkbox style="margin-left: 201px;" v-model="checked">允许延长有效期</el-checkbox> -->
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTaskClose('newTaskForm')">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="dialogTaskSend">确 定</el-button>
      </span>
    </el-dialog>

    <!-- <attenChange :iShow ='iShow' @changeShow="changeShow" /> -->
    <el-dialog class="attendance_group" :title=" '修改' + holidayName+ '余额'" :visible.sync="showMoeney" width="640px"
      top="50px">
      <el-form :model="newTaskForm" ref="newTaskForm" :rules="newTaskrules" label-width="100px" style="padding-right:20px;" v-loading="taskFormLoad">
        <!-- <el-form-item :label=" '修改' + holidayName"> -->
        <el-form-item label="增加假期余额">
          <el-col :span="5">
            <el-select v-model="newTaskForm.type" filterable placeholder="请选择">
              <el-option v-for="item in pullrow" :key="item.id" :label="item.value" :value="item.id"></el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input auto-complete="off" :min='1' type="number" v-model="newTaskForm.time"></el-input>
          </el-col>
          <el-col :span="5">小时</el-col>
        </el-form-item>
        <!-- <el-form-item label="过期时间">
          <el-date-picker
            v-model="newTaskForm.expire_date"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="理由" :rules="[{ required: true}]">
          <el-input type="textarea" placeholder="请输入理由" rows="5" v-model="newTaskForm.remark"></el-input>
        </el-form-item>
        <el-form-item style=" text-align: right;">
          <el-button @click="dialogChange('newTaskForm')">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="ChanfeSend('newTaskForm')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
  import moment from 'moment'
  import qs from 'qs'
  import Vue from 'vue'
  import preview from 'vue-photo-preview'
  // import attenChange from '@/views/attendance/attenadenChange'
  import 'vue-photo-preview/dist/skin.css'

  Vue.use(preview, {
    tapToClose: false
  })
  export default {
    components: {
      // attenChange
    },
    data() {
      return {
        outerBalance:{},
        recordID:'',
        outerList:[],
        outerLoad:false,
        outerVisible:false,
        detainVisible:false,

        taskFormLoad:false,
        balanceLoad:false,
        title: '添加假期',
        rules: {
          // name: [
          //   { required: true, message: '请输入假期名称', trigger: 'blur' },
          //   { max: 20, message: '假期名称不能超过20个字符', trigger: 'blur' }
          // ],
        },
        newTaskrules:{
          time: [
            { required: true, message: '请输入时长', trigger: 'blur' }
          ],
          // expire_date: [
          //   { required: true, message: '请选择过期时间', trigger: 'blur' }
          // ],
          remark: [
            { required: true, message: '请输入理由', trigger: 'blur' }
          ]
        },
        pullrow: [{
            value: '增加',
            id: 1
          },
          // {
          //   value: '减少',
          //   id: 2
          // }
        ],
        taskFormLoadj:false,
        deductTime:{
          time: 1,
          remark: '',
        },
        newTaskForm: {
          type: 1,
          time: 0,
          remark: '',
          // expire_date: moment().add(1, 'years').format("YYYY-MM-DD")
        },
        nameId: '',
        dept_name: '',
        employId: 0,
        getid: '',
        holidayName: '',
        department_id: [],
        target_id_set: [],
        employeeOptions: [],
        dept_tree: [],
        showMoeney: false,
        changeType: 1,
        ExactlyOpen: false,
        typeTData: [],
        id: 0,
        balance: 0,
        iShow: false,
        ReviewDetailDialogVisible: false,
        activeName2: 'type_1',
        filter: {
          type: 4,
          time_range: [],
          status: 0,
          keywords: ''
        },
        formdata: {
          id: 0,
          status: 0,
          remark: ''
        },
        review_list: [{
          content: '支持使用图标',
          timestamp: '2018-04-12 20:46',
          size: 'large',
          type: 'primary',
          icon: 'el-icon-more'
        }],
        profile: this.$store.getters.user_info,
        calculation: [{
            id: 1,
            content: '按工作日'
          },
          {
            id: 2,
            content: '按自然日'
          }
        ],
        grant_type: [{
            id: 1,
            content: '每月1号自动发放'
          },
          {
            id: 2,
            content: '每年1月1号自动发放'
          },
          {
            id: 3,
            content: '手动发放'
          },
          {
            id: 4,
            content: '加班转换成假期'
          }
        ],
        nameContent: '',
        expire_type: [{
            id: 0,
            content: '永久有效'
          },
          {
            id: 1,
            content: '自发放日起的1年内有效'
          },
          {
            id: 2,
            content: '自发放日起的1个月内有效'
          },


        ],
        balance_enabled: false,
        taskFormRules: [],
        taskform: {
          name: '',
          point: '',
          min_time: 1,
          calculation_type: 1,
          grant_type: 1,

          expire_type: '',
          grant_total: '',
          real_time_grant: 0,
          grant_date: 1,
        },
        loading: false,
        pageLimit: 10,
        totalCount: 0,
        currentPage: 1,
        tableData: [],
        modelId: 0,
        moneyList: [],
        instantPickerOptions: {
          shortcuts: [{
              text: '本周',
              onClick(picker) {
                const now = new Date(new Date().toLocaleDateString())
                const start =
                  now.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000
                const end = start + 7 * 24 * 60 * 60 * 1000 - 1000
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '上周',
              onClick(picker) {
                const now = new Date(new Date().toLocaleDateString())
                const start =
                  now.getTime() - (now.getDay() + 6) * 24 * 60 * 60 * 1000
                const end = start + 7 * 24 * 60 * 60 * 1000 - 1000
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '本月',
              onClick(picker) {
                const now = new Date()
                const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
                const endDate = new Date(
                  now.getFullYear(),
                  now.getMonth() + 1,
                  0
                )
                picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
              }
            },
            {
              text: '上月',
              onClick(picker) {
                const now = new Date()
                const startDate = new Date(
                  now.getFullYear() - (now.getMonth() > 0 ? 0 : 1),
                  (now.getMonth() + 11) % 12,
                  1
                )
                const endDate = new Date(now.getFullYear(), now.getMonth(), 0)
                picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
              }
            }
          ]
        },
      }
    },
    watch: {
      activeName2(val, old) {
        this.totalCount = 0
        this.currentPage = 1
        this.filter.type = val.split('_')[1]
        this.onFilterChanged()
      },
      department_id(val, old) {
        if (val !== null && val.length != 0) {
          let id = val[val.length - 1]
          this.get_employee_list(id)
        } else {
          this.employeeOptions = JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP'))
        }
      },
      
    },
    filters: {

      dateTimeFormatter: function (cellValue) {
        return moment(cellValue * 1000).format('YYYY-MM-DD HH:mm')
      }
    },
    methods: {
      deductClose(){
        this.getReturn();
      },
      deductDialogC(formName){
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.taskFormLoadj = true
            let data = {
              id:this.recordID,
              rule_id:this.getid,
              time:this.deductTime.time,
              remark:this.deductTime.remark,
            }
            this.$jtoken({
              url: this.serveAd + '/ad/employee_holiday/info/deduct',
              method: 'post',
              data: data,
            }).then((res)=>{
              if(res.data.code == 1){
                this.$message({
                  message: res.data.msg,
                  type: 'success'
                });
                this.balanceList(this.recordID)
                this.deductDialogn(formName)
              }else{
                this.$message.error(res.data.msg);
              }
            }).finally(()=>{
              this.taskFormLoadj = false
            })
          }
        })
      },
      deductDialogn(deductTaskForm){
        this.detainVisible = false;
        this.deductTime.time = 0;
        this.deductTime.remark = '';
        this.$refs.deductTaskForm.resetFields();
      },
      balanceList(id){
        this.recordID = id
        this.outerVisible = true
        this.outerLoad = true
        let params = {
          id:id,
          page:1,
          page_size:2000
        }
        this.$jtoken.get(this.serveAd + '/ad/employee_holiday/info/list', {params:params}).then((res)=>{
          this.outerList = res.data.data.list
          this.outerBalance = res.data.data
        }).finally(()=>{
          this.outerLoad = false
        })
      },
      pastDue1(timestamp){
        if(timestamp){
          let atpresentDate = moment().format('YYYY-MM-DD')
          let date = moment(timestamp).diff(moment(atpresentDate),'days')
          if(date>=0){
            return false
          }else if(date<0){
            return true
          }else{
            return false
          }
        }
      },
      pastDue(timestamp){
        if(timestamp){
          let moment = this.$moment
          let pastdueTime = moment(timestamp.toString().length==10?timestamp*1000:timestamp).format('YYYY-MM-DD HH:mm')
          let atpresentDate = moment().format('YYYY-MM-DD HH:mm')
          let date = moment(pastdueTime).diff(moment(atpresentDate),'minutes')
          // date = 25
          if(date>=0){
            return false
          }else if(date<0){
            return true
          }else{
            return false
          }
        }
      },
      changgeName() {
        if (this.taskform.grant_type == 1) {
          this.nameContent = "按月"
        } else if (this.taskform.grant_type == 2) {
          this.nameContent = "按年"
        } else if (this.taskform.grant_type == 3) {
          this.nameContent = '手工发放'
        } else {
          this.nameContent = '加班转换得到'
        }
      },
      changeBalande() {
        if (this.balance_enabled) {
          this.taskform.balance_enabled = 1
        } else {
          this.taskform.balance_enabled = 0
        }

      },
      dialogChange(newTaskForm) {
        this.showMoeney = false;
        this.newTaskForm.time = 0;
        this.newTaskForm.remark = '';
        this.newTaskForm.type = 1;
        this.$refs.newTaskForm.resetFields();
      },
      ChanfeSend(formName) {
        let params = this.newTaskForm;
        if (params.time && params.time == 0) {
          this.$message({
            type: 'error',
            message: '修改年假时长不能为0'
          })
          return false;
        } else if (params.time == '') {
          this.$message({
            type: 'error',
            message: '请输入修改年假时长'
          })
          return false;
        } else if (params.remark == '') {
          this.$message({
            type: 'error',
            message: '理由不能为空'
          })
          return false;
        }
        this.taskFormLoad = true
        params.rule_id = this.getid;
        params.employee_id = this.employId
        this.$jtoken({
          url: this.serveAd + '/ad/employee_holiday/update',
          method: 'post',
          data: qs.stringify(params),

        }).then(res => {
          if (res.data.code == 1) {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.showMoeney = false;
            this.$refs.newTaskForm.resetFields()
            this.newTaskForm.time = 0;
            this.newTaskForm.remark = '';
            this.newTaskForm.type = 1;
            this.getReturn();

          } else {
            this.$message({
              type: 'error',
              message: res.data.msg
            })
          }
        }).finally(()=>{
          setTimeout(()=>{
            this.taskFormLoad = false
          },200)
        })
      },

      dateFormatter: function (row, column, cellValue) {
        return this.$moment(cellValue * 1000).format('YYYY-MM-DD HH:mm')
      },
      getIdMoney(rows) {
        this.currentPage = 1
        this.getid = rows.name;
        this.holidayName = rows.label;
        this.getReturn();
      },


      getReturn(val) {
        let employId = '';
        if (val == undefined) {
          employId = this.employId;
        } else {
          this.currentPage = 1
          employId = val.id
        }
        const self = this;
        this.activeName2 = 'type_3';
        this.filter.type = 3;
        var params = {
          page: self.currentPage,
          page_size: self.pageLimit,
          rule_id: self.getid,
          employee_id: employId
        }
        this.balanceLoad = true
        this.$jtoken.get(this.serveAd + '/ad/employee_holiday/info', {
            params: params
          })
          .then(res => {
            if (res.data.code == 1) {
              let {
                data = {}
              } = res.data;
              self.img_url = data.employee_info.img_url;
              self.moneyList = data.list;
              self.totalCount = data.total;
              self.nameId = data.employee_info.name; //个人名称
              self.dept_name = data.employee_info.dept_name;
              self.employId = data.employee_info.id;
              self.balance = data.balance;
            } else {
              self.moneyList = [];
              self.totalCount = 0;
            }
          }).finally(()=>{
            this.balanceLoad = false
          })
      },


      // 员工假期余额选择列切换
      getIdClass(val) {
        this.getid = val.name;
        this.holidayName = val.label;
        this.currentPage = 1;
        if (this.filter.type == 2) {
          this.loadMoneey();
        }
        // else if(this.filter.type == 3){
        //   this.getReturn()
        // }

      },


      // 假期列表数据加载
      loadList: function () {
        var self = this;
        self.loading = true
        this.$jtoken.get(this.serveAd + '/ad/holidays_rule', {
            params: {
              page: self.currentPage,
              page_size: self.pageLimit,
              keyword: ''
            }
          })
          .then(res => {
            if (res.data.code == 1) {
              let {
                data = {}
              } = res.data;
              self.tableData = data.list;
              self.totalCount = data.total;
              let newarray = []
              // for(let i in self.tableData){
              //   if(self.tableData[i].balance_enabled == 1){
              //     getid_flag = true
              //   }
              // }
              if (self.tableData.length != 0) {
                for (let i = 0; i < self.tableData.length; i++) {
                  if (self.tableData[i].balance_enabled == 1) {
                    newarray.push(self.tableData[i])
                  }

                }
                self.getid = newarray[0].id.toString();
                self.holidayName = newarray[0].name;
              }
            }
          }).catch((e)=>{}).finally(()=>{self.loading=false})
      },


      // 员工假期余额

      loadMoneey() {
        // loadMoneeyloadMoneey
        var self = this;
        var params = {
          page: self.currentPage,
          page_size: self.pageLimit,
          rule_id: self.getid,
        }
        if (self.department_id.length > 0) {
          params['dept_id'] = self.department_id[self.department_id.length - 1] // 部门id
        }
        if (self.target_id_set.length > 0) {
          // params['employee_id'] = self.target_id_set // 员工id
          params.employee_id = self.target_id_set // 员工id
        }

          self.loading = true
          this.$jtoken.get(this.serveAd + '/ad/employee_holiday', {
            params: params
          })
          .then(res => {
            if (res.data.code == 1) {
              let {
                data = {}
              } = res.data;
              this.typeTData = data.list;
              this.totalCount = data.total;
            } else {
              self.typeTData = [];
              self.totalCount = 0;
            }
          }).catch((e)=>{
            self.$message.error(e.data.msg)
          }).finally(()=>{
            self.loading=false
          })
      },
      changeMoney() {
        this.showMoeney = true;
      },
      get_employee_list(id) {
        let self = this
        self.$http('get','/api/employee/list',{dept_id: id}).then((res) => {
          if (res.data.code == 1) {
            this.employeeOptions = res.data.data.list
          } else {
            self.$message.error(res.data.data.msg)
          }
        }).finally(() => {})
      },
      // 递归判断列表，把最后的children设为undefined
      getTreeData(data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            data[i].children = undefined;
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].children);
          }
        }
        return data;
      },
      handleClickType(val) {
      },
      changeShpw() {
        this.iShow = true;
      },
      changeShow() {
        this.iShow = false;
      },
      addHoliday() {
        this.id = 0;
        this.title = "添加假期"
        this.taskform = {
          name: '',
          point: '',
          min_time: 1,
          calculation_type: 1,
          grant_type: 1,

          expire_type: '',
          grant_total: '',
          real_time_grant: 0,
          grant_date: 1,
        },
        this.balance_enabled = false
        this.ReviewDetailDialogVisible = true;
      },
      fileProview(url, list, key) {
        const $ext_list1 = ['jpg', 'png', 'bmp', 'jpeg', 'JPG', 'PNG']
        const $ext_name1 = url.split('.')[1]
        if ($ext_list1.indexOf($ext_name1) >= 0) {

          let ii = 0
          for (const i in list) {
            if (
              ['jpg', 'png', 'bmp', 'jpeg', 'JPG', 'PNG'].indexOf(list[i].split('.')[1]) >=
              0
            ) {
              if (list[i] == url) {
                this.openPhotoSwipe(
                  ii,
                  document.querySelectorAll('img[preview="' + key + '"]')
                )

                return
              }
              ii++
            }
          }
        }
      },

      get_status_text(status) {
        if (status == 0) {
          return '待审批'
        }
        if (status == -1) {
          return '驳回'
        }
        if (status == 1) {
          return '通过'
        }
      },
      // 编辑
      set_review_status(id) {
        this.id = id;
        if (id != 0) {
          this.$jtoken.get(this.serveAd + '/ad/holidays_rule/info?id=' + this.id)
            .then(res => {
              if (res.data.code == 1) {
                let {
                  data = {}
                } = res.data;
                this.title = "假期修改"
                this.taskform.name = data.name;
                this.taskform.calculation_type = 1;
                this.taskform.grant_type = data.grant_type;
                this.taskform.expire_type = data.expire_type;
                this.taskform.grant_total = data.grant_total;
                this.taskform.point = data.point;
                this.taskform.balance_enabled = data.balance_enabled;
                this.balance_enabled = this.taskform.balance_enabled == 1 ? true : false;
                this.ReviewDetailDialogVisible = true;
              }
            })
        }
      },
      // 删除
      dlete(id) {
        let dleteId = id;
        this.$confirm('确认删除假期此假期规则吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',

        }).then(({
          value
        }) => {

          this.$jtoken.get(this.serveAd + '/ad/holidays_rule/delete?id=' + dleteId)
            .then(res => {
              let msg = res.data.msg
              if (res.data.code == 1) {
                this.$message({
                  type: 'success',
                  message: "删除成功"
                })
                this.loadList();
              } else {
                this.$message({
                  type: 'error',
                  message: msg
                })
              }
            })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '取消输入'
          // });
        });
      },

      // 详情
      exactly(id) {
        let valueId = id;
        this.$jtoken.get(this.serveAd + '/ad/holidays_rule/info?id=' + valueId)
          .then(res => {
            if (res.data.code == 1) {
              this.ExactlyOpen = true;
              let {
                data = {}
              } = res.data;
              this.taskform.name = data.name;
              this.taskform.calculation_type = data.calculation_type;
              this.taskform.grant_type = data.grant_type;
              this.taskform.expire_type = data.expire_type;
              this.taskform.grant_total = data.grant_total;
              this.taskform.point = data.point;
              this.taskform.balance_enabled = data.balance_enabled;
              this.balance_enabled = this.taskform.balance_enabled == 1 ? true : false;
            }
          })
      },
      openClose() {
        this.ReviewDetailDialogVisible = false;
        this.$refs.newTaskForm.resetFields()
      },
      // 取消
      dialogTaskClose(newTaskForm) {

        this.ReviewDetailDialogVisible = false;
        this.$refs.newTaskForm.resetFields();
        this.taskform.point = '';
        this.balance_enabled = false;
      },
      dialogTaskSend() {
        let url = '';
        if (this.id == 0) {
          url = '/ad/holidays_rule/add';
        } else {
          url = '/ad/holidays_rule/update?id=' + this.id;
        }
        var params = this.taskform;
        if (params.name == '') {
          this.$message({
            type: 'error',
            message: '请输入假期名称'
          })
          return;
        } else if (params.name.length > 20) {
          this.$message({
            type: 'error',
            message: '假期名称长度不能超过20个字符'
          })
          return;
        } else if (params.calculation_type == '') {
          this.$message({
            type: 'error',
            message: '请选择假时长核算方式'
          })
          return;
        } else if (params.grant_type == '' && this.balance_enabled == true) {
          this.$message({
            type: 'error',
            message: '请选择假余额发放方式'
          })
          return;
        } else if (params.grant_total == '' && this.balance_enabled == true) {
          this.$message({
            type: 'error',
            message: '请输入额度'
          })
          return;
        } else if (params.expire_type === '' && this.balance_enabled == true) {
          this.$message({
            type: 'error',
            message: '请选择有效期'
          })
          return;
        } else {
          this.$jtoken.post(this.serveAd + url, qs.stringify(params))
            .then(res => {
              let msg = res.data.msg;
              if (res.data.code == 1) {
                this.loadList();
                this.ReviewDetailDialogVisible = false;
                this.$message({
                  type: 'success',
                  message: msg
                })
                this.$refs.newTaskForm.resetFields();
                this.taskform.point = '';
                this.balance_enabled = false;
              } else {
                this.$message({
                  type: 'error',
                  message: msg
                })
              }
            })
        }
      },
      dateTimeFormatter: function (row, column, cellValue) {
        return cellValue ?
          this.$moment(cellValue * 1000).format('YYYY-MM-DD HH:mm') :
          ''
      },
      handleSizeChange(val) {
        this.pageLimit = val
        this.onFilterChanged()
      },
      handleClick(tab, event) {
      },
      onFilterChanged: function () {
        this.$refs.dept1.dropDownVisible = false;
        this.currentPage = 1
        if (this.filter.type == 1) {
          this.loadList()
        } else if (this.filter.type == 2) {
          this.loadMoneey()
        }else if(this.filter.type == 4){
          this.loadList()
        }
        // else if (this.filter.type == 3){
        //   this.getReturn()
        // }

      },


      changePage: function (current) {
        if (isNaN(current) || current < 1) {
          return false
        } else {
          this.currentPage = current
        if (this.filter.type == 1) {
          this.loadList()
        } else if (this.filter.type == 4) {
            this.loadList()
          } else if (this.filter.type == 2) {
            this.loadMoneey()
          }else if (this.filter.type == 3){
            this.getReturn()
          }
        }



      }
    },
    mounted() {
      this.employeeOptions = JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP'))
      this.loadList()
    },
    created() {
      this.dept_tree = this.getTreeData(JSON.parse(localStorage.getItem('dept_tree')))
    }
  }
</script>

<style scoped>
  /deep/ .el-input__inner {}

  /deep/ .el-select .el-input {}

  /deep/ .el-form-item__label {
    font-weight: normal;
    color: #606266;
    font-size: 14px;
  }

  /deep/ .exactly {
    margin-right: 128px;
  }

  /deep/ .oneYear .el-input {
    width: 48px;
  }

  /deep/ .oneYear {
    margin-bottom: 9px;
  }

  /deep/ .twoYear {
    margin-bottom: 9px;
  }

  /deep/ .oneYear .el-input__inner {
    width: 48px;
    padding: 0px;
    margin: 0 4px;
  }

  /deep/ .exactlY .el-form-item__label {
    margin-right: 10px;
  }

  /deep/.exactlY .el-form-item {

    margin-bottom: 12px;
  }

  .typeThree {
    background: #fff;
    ;

  }

  /deep/ .typeThree .el-tabs__item {
    /* width: 15%;
  text-align: center; */
  }

  .picture {
    display: flex;
    align-items: center;
  }

  .pictureOne {
    margin-left: 15px;
  }

  .gap-right-8 {}

  .inline-block-btn-list {
    margin-bottom: 15px;
  }

  /* .inline-block-btn-list > *, .inline-block-btn-list > .el-button + .el-button {
    margin-left: 0;
    margin-right: 10px;
    margin-bottom: 10px;
} */
  /deep/ .holiday {
    width: 100px !important;
  }

  /deep/ .el-cascader .el-input__inner {
    width: 120px;
  }

  /deep/ .active2 .el-tabs__item {
    text-align: center;

  }

  /deep/ .el-tabs__content {
    background: #fff;
  }

  /deep/ .newform .el-input {
    width: 100px;
  }

  /deep/ .newform .el-input__inner {
    width: 100px;
  }

  /deep/ .gap-right-8 {
    /* width: 120px!important; */
  }

  /* /deep/ .el-textarea {
    width: 200px;
    height: 117px;
  } */

  /* /deep/ .el-textarea .el-textarea__inner {
    width: 200px;
    height: 117px;
  } */

  /deep/ .oneYear .el-input__inner {
    padding: 0 10px;
  }
  .balanceStatement /deep/ .el-dialog__body{
    padding: 10px 20px 30px;
  }
  .balanceLists{
    max-height:250px;
    overflow: auto;
  }
  
  /*滚动条的宽度*/

  .balanceLists::-webkit-scrollbar {
    width:6px;
    height:5px;
  }

  /*外层轨道。可以用display:none让其不显示，也可以添加背景图片，颜色改变显示效果*/

  .balanceLists::-webkit-scrollbar-track {
    width: 6px;
    background-color:#fff0;
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius:2em;
  }

  /*滚动条的设置*/

  .balanceLists::-webkit-scrollbar-thumb {
    background-color:#fff0;
    background-clip:padding-box;
    min-height:28px;
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius:2em;
  }
  /*滚动条移上去的背景*/

  .balanceLists:hover::-webkit-scrollbar-thumb{
    background-color:rgba(111, 115, 124, 0.3);
  }
</style>