<template>
  <div style=" background-color: #fff; padding:15px; min-height: calc(100vh - 160px);">


    <el-alert style="margin-bottom:15px;background:#fdf6ec!important;color:#E6A23C!important;border:1px solid #e9a846;padding:20px 16px;" title="温馨提示：" type="warning" v-show="tips_show" @close="tips_close" description>
      <p class="diy-tip"  style="color:#E6A23C!important;font-size:14px;margin:0 !important;padding:0;">1、系统默认统计本月数据，您可以自定义时间段统计；</p>
    </el-alert>

    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">


      <el-date-picker
        class="first-element-btn"
        v-model="filter.time_range"
        type="daterange"
        value-format="timestamp"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="instantPickerOptions"
        @change="onFilterChanged"
      ></el-date-picker>


<!--
      <el-cascader
        clearable
        :options="dept_tree"
        change-on-select
        :required="true"
        v-model="department_id"
        @change="onFilterChanged"
        placeholder="选择部门"
        style="width:120px"

      ></el-cascader> -->
        <el-cascader
        clearable
        :options="dept_tree"
        ref="dept1"
        change-on-select
        :required="true"
        v-model="category_id"
        style="width: 120px;margin-left:10px;"

        @change="onFilterChanged()"
        placeholder="选择部门"
      ></el-cascader>


            <!-- <el-cascader
              clearable
              :options="categoryTree"
              change-on-select
              :required="true"
              v-model="taskForm.category_id"
              style="width: 150px;"
              :disabled="(edit_flag.category==true&&edit_flag.item==true || twAgree && source == 20 || isFirst && source ==10 )"
              @change="loadAvailableRuleItems(taskForm)"
              placeholder="选择积分分类"
            ></el-cascader> -->



      <el-select
        v-show="profile.manager_type > 0"
        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>






      <el-button style="margin-left:10px;"
        type="primary"
        @click="exporExcelJump"
      >{{create_file_text}}</el-button>

<!--
      <el-button
        type="primary"
        plain
        @click="reflush_data"
        :loading="create_file_loading1"
        class="first-element-btn"
      >刷新报表</el-button> -->


    </div>

    <el-table
      border
      stripe
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      @filter-change="filterHandler"
    >
      <el-table-column prop="name" label="姓名" fixed align="center"></el-table-column>
      <el-table-column prop="company_id" label="工号" align="center"></el-table-column>
      <el-table-column prop="job_name" label="职位" align="center"></el-table-column>
      <el-table-column prop="work_days_count" label="出勤天数" align="center"></el-table-column>
      <el-table-column prop="off_days_count" label="休息天数" align="center"></el-table-column>
      <el-table-column prop="duration" :formatter="time_convert" align="center" label="工作时长(小时)" width="120"></el-table-column>
      <el-table-column prop="late_count" label="迟到次数" align="center">

        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="_late_list_show(scope.row, 1)" style="text-decoration: underline;">{{scope.row.late_count}}</a>
        </template>

      </el-table-column>
      <el-table-column prop="late_time_sum" label="迟到时长(小时)" align="center" :formatter="time_convert" width="120">
        <template slot-scope="scope" >
        <a href="javascript:void(0);" @click="_late_list_show(scope.row, 1)" style="text-decoration: underline;">{{time_convert(null, null, scope.row.late_time_sum)}}</a>
        </template>
      </el-table-column>
      <el-table-column prop="serious_late_count" label="严重迟到次数" align="center" width="110">

        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="_late_list_show(scope.row, 2)" style="text-decoration: underline;">{{scope.row.serious_late_count}}</a>
        </template>

      </el-table-column>
      <el-table-column prop="serious_late_time_sum" label="严重迟到时长(小时)" align="center" :formatter="time_convert" width="150">

        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="_late_list_show(scope.row, 2)" style="text-decoration: underline;">{{time_convert(null, null, scope.row.serious_late_time_sum)}}</a>
        </template>

      </el-table-column>
      <el-table-column prop="late2_days_count" label="旷工迟到天数" align="center" width="110">


        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="_late_list_show(scope.row, 3)" style="text-decoration: underline;">{{scope.row.late2_days_count}}</a>
        </template>

      </el-table-column>
      <el-table-column prop="leave_time_count" label="早退次数" align="center">

        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="_leave_list_show(scope.row)" style="text-decoration: underline;">{{scope.row.leave_time_count}}</a>
        </template>

      </el-table-column>
      <el-table-column prop="leave_time_sum" label="早退时长(小时)" align="center" width="120" :formatter="time_convert">

        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="_leave_list_show(scope.row)" style="text-decoration: underline;">{{time_convert(null, null, scope.row.leave_time_sum)}}</a>
        </template>
      </el-table-column>
      <el-table-column prop="no_checkin_count" label="上班缺卡次数" align="center" width="120">

        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="_go_lack_detail_show(scope.row, 1)" style="text-decoration: underline;">{{scope.row.no_checkin_count}}</a>
        </template>

      </el-table-column>
      <el-table-column prop="no_checkout_count" label="下班缺卡次数" align="center" width="120">

        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="_go_lack_detail_show(scope.row, 2)" style="text-decoration: underline;">{{scope.row.no_checkout_count}}</a>
        </template>

      </el-table-column>
      <el-table-column prop="no_work_days_count" label="旷工天数" align="center">

        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="_go_lack_detail_show(scope.row, 3)" style="text-decoration: underlinen;">{{scope.row.no_work_days_count}}</a>
        </template>

      </el-table-column>
      <el-table-column prop="business_trip_time_sum" label="出差时长(小时)" align="center" width="120" :formatter="time_convert"></el-table-column>
      <el-table-column prop="out_time_sum" label="外出时长(小时)" width="120" align="center" :formatter="time_convert"></el-table-column>


      <el-table-column label="请假(小时)"  align="center"   width="90">
        
         <el-table-column  v-for="(item,index) in tableDataList" :key="index" :label="item.name" align="center" width="90" >
                 <template slot-scope="scope" >
                   <!-- <div v-for="(item,index) in tableDataList" :key="index" > -->
                    <div v-for="(items, key) in scope.row.ask_for_leave" :key="key">
                      <!-- <span v-if="item.id == items.id"> {{items.total}}</span> -->
                      <span v-if="tableDataList[index].id == items.id">{{items.total}}</span>
                    </div>
                   <!-- </div> -->
                </template>
        </el-table-column>
     </el-table-column>


        <el-table-column prop="overtime_review_count" label="加班-审批单统计" align="center"></el-table-column>


      <el-table-column label="加班计为加班费" align="center">
 <!-- :formatter="time_convert" -->
      <el-table-column prop="workday_overtime_sum" label="工作日(小时)" align="center" width="120"></el-table-column>
      <el-table-column prop="offday_overtime_sum" label="休息日(小时)" align="center" width="120"></el-table-column>
      <el-table-column prop="holiday_overtime_sum" label="节假日(小时)" align="center" width="120"></el-table-column>

      </el-table-column>
      <el-table-column label="加班时长转为调休" align="center">
      <el-table-column prop="workday_overtime_convert_sum" align="center" label="工作日(小时)" width="120"></el-table-column>
      <el-table-column prop="offday_overtime_convert_sum" align="center" label="休息日(小时)" width="120"></el-table-column>
      <el-table-column prop="holiday_overtime_convert_sum" align="center" label="节假日(小时)" width="120"></el-table-column>
      </el-table-column>


      <el-table-column header-align="center" :label="item.slice(5,7) + '-'+item.slice(8,) " v-for="(item, index) in table_header" :key="index" width="80px'" align="center">

        <template slot-scope="scope" >
          <a href="javascript:void(0);" @click="set_attendance_show(item, scope.row)">{{scope.row.days_data[item]}}</a>
        </template>

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







    <el-dialog
      title="考勤详情"
      :visible.sync="attendance_show"
      top="50px"
      width="500px"
      :close-on-click-modal="false"
    >
      <div v-for="(item, index) in attendance_info" :key="index" style="line-height: 2">
        <div>

        {{item.name}}({{$moment(item.checkin_base_time * 1000).format('HH:mm')}})：

        <span v-if="item.checkin_time > 0">打卡时间{{$moment(item.checkin_time * 1000).format('HH:mm')}}</span>

        <span v-if="item.checkin_status == -1">缺卡</span>
        <span v-if="item.checkin_status == 0">未打卡</span>
        <span v-if="item.checkin_status == 1">准时打卡</span>
        <span v-if="item.checkin_status == 2">迟到</span>
        <span v-if="item.checkin_status == 3">已补卡</span>

        </div>
        <div>
         {{item.name}}({{$moment(item.checkout_base_time * 1000).format('HH:mm')}})：

        <span v-if="item.checkout_time > 0">打卡时间{{$moment(item.checkout_time * 1000).format('HH:mm')}}</span>

        <span v-if="item.checkout_status == -1">缺卡</span>
        <span v-if="item.checkout_status == 0">未打卡</span>
        <span v-if="item.checkout_status == 1">准时打卡</span>
        <span v-if="item.checkout_status == 2">早退</span>
        <span v-if="item.checkout_status == 3">已补卡</span>
        </div>
      </div>

      <div v-if="attendance_info.length==0" style="text-align: center;">暂无数据</div>
    </el-dialog>

    <el-dialog
      :title="late_list_title"
      :visible.sync="late_list_show"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-table
        border
        stripe
        height="300"

        v-loading="late_list_loading"
        :data="late_list_tableData"
        tooltip-effect="dark"
      >
        <el-table-column prop="name" label="班次" fixed align="center">

        </el-table-column>
        <el-table-column prop="checkin_base_time" label="上班时间" fixed align="center">
            <template slot-scope="scope">
            {{$moment(scope.row.checkin_base_time * 1000).format('MM-DD HH:mm')}}
          </template>
        </el-table-column>
        <el-table-column prop="checkin_time" label="实际打卡时间" fixed align="center">
           <template slot-scope="scope">
            {{$moment(scope.row.checkin_time * 1000).format('MM-DD HH:mm')}}
          </template>
        </el-table-column>
        <el-table-column prop="late_time" label="迟到时长" fixed align="center">
           <template slot-scope="scope">
            {{(scope.row.late_time/3600).toFixed(2)}}
          </template>
        </el-table-column>

      </el-table>
    </el-dialog>



    <el-dialog
      :title="leave_list_title"
      :visible.sync="leave_list_show"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-table
        border
        stripe
        height="300"

        v-loading="leave_list_loading"
        :data="leave_list_tableData"
        tooltip-effect="dark"
      >
        <el-table-column prop="name" label="班次" fixed align="center"></el-table-column>
        <el-table-column prop="checkout_base_time" label="下班时间" fixed align="center">
           <template slot-scope="scope">
            {{$moment(scope.row.checkout_base_time * 1000).format('MM-DD HH:mm')}}
          </template>

        </el-table-column>
        <el-table-column prop="checkout_time" label="实际打卡时间" fixed align="center">
            <template slot-scope="scope">
            {{$moment(scope.row.checkout_time * 1000).format('MM-DD HH:mm')}}
          </template>

        </el-table-column>
        <el-table-column prop="leave_time" label="早退时长" fixed align="center">

            <template slot-scope="scope">
                {{(scope.row.leave_time/3600).toFixed(2)}}

          </template>


        </el-table-column>

      </el-table>
    </el-dialog>


    <el-dialog
      :title="go_lack_detail_title"
      :visible.sync="go_lack_detail_show"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-table
        border
        stripe
        height="300"

        v-loading="go_lack_detail_loading"
        :data="go_lack_detail_tableData"
        tooltip-effect="dark"
      >
        <el-table-column prop="name" label="班次" fixed align="center"></el-table-column>
        <el-table-column prop="checkout_base_time" label="下班时间" fixed align="center">
          <template  slot-scope="scope"  >

          <!-- </template> -->
          {{$moment(scope.row.checkout_base_time * 1000).format('MM-DD HH:mm')}}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

   <el-dialog
      title="导出考勤统计数据"
      custom-class="downlowd"
      :visible.sync="dialogVisible"
      width="40%"

    >
     <div class="color: #303133;font-size: 12px;text-align: left;">
       <div class="alignColor">温馨提示</div>
       <div class="alignColor">1, 导入前请点击"下载模版"按钮下载模版文件</div>
       <div  class="alignColor">2, 填写规则到Excel表中</div>
       <div  class="alignColor">3,点击"Excel文件导入"上传填写好的电子表</div>
    </div>
      <!-- <span style="color: #5b8bf7;cursor: pointer;" @click="openDalod">点击下载考勤数据</span> -->
      <div style=" margin-top:30px;">
        <el-button type="primary"  @click="openDalod">导出考勤统计数据</el-button>
      </div>

    </el-dialog>





  </div>
</template>
<script>
import qs from 'qs'
import { getToken } from '@/utils/auth'
import EmployeeSelector from '@/views/integral/EmployeeSelector'
import Vue from 'vue'
import preview from 'vue-photo-preview'
import moment from 'moment'
import 'vue-photo-preview/dist/skin.css'
import clip from '@/utils/clipboard' // use clipboard directly

Vue.use(preview, {
  tapToClose: false
})
export default {
  components: {
    EmployeeSelector
  },
  watch: {
    department_id(val, old) {
      // this.loadWidgetData()
    },
    // category_id(val){
    //   let dept_list
    //   for(let i in val){
    //     dept_list = val[i]
    //   }
    //   this.category_id_BL = dept_list
    //   console.log(val)
    // }
  },
  data() {
    const now = new Date()
    const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
    const endDate = new Date(
      now.getFullYear(),
      now.getMonth() + 1,
      0
    )
    let time_range = JSON.parse(JSON.stringify([moment(startDate).valueOf(), moment(endDate).valueOf()]))
    return {
      category_id_BL: '',//部门id
      tips_show: false,

      category_id:'',
      dialogVisible: false,
      late_list_tableData:[],
      late_list_loading:false,
      late_list_show:false,
      late_list_title:'',

      leave_list_tableData:[],
      leave_list_loading:false,
      leave_list_show:false,
      leave_list_title:'',

      go_lack_detail_tableData:[],
      go_lack_detail_loading:false,
      go_lack_detail_show:false,
      go_lack_detail_title:'',


      attendance_info:[],
      attendance_show:false,
      table_header:[],
      department_id:[],
      file_url:'',
      target_id_set:[],
      create_file_loading:false,
      create_file_loading1:false,
      tableDataList:[],
      create_file_text:'下载月报表',
      checkinSettingForm: {
        checkinMech: []
      },
      checkinSettingFormRules: {
        checkinMech: [{ required: true, message: '请输入考勤机名称', trigger: 'change' }]
      },
      employeeSelectorIds: [],
      workScheduleApi: '/integral.php/attendance/setting_add',
      checkinMechApi: '/integral/attendance/set_attendance_config',
      checkinMechForm: {
        name: '',
        ip: '',
        port: '',
        machine_id: '',
        config_ids: []
      },
      checkinMechFormRules: {
        name: [{ required: true, message: '请输入考勤机名称', trigger: 'blur' }],
        ip: [{ required: true, message: '请输入考勤机连接ip', trigger: 'blur' }],
        machine_id: [{ required: true, message: '请输入考勤机机器号', trigger: 'blur' }],
        config_ids: [{ required: true, message: '请先添加排班', trigger: 'change' }]
      },
      dept_tree:[],
      workScheduleList: [],
      attendanceMechList: [],
      workScheduleForm: {
        name: '',
        starttime: '',
        endtime: '',
        send_time: {
          starttime: '',
          endtime: ''
        },
        employee_ids: [],
        job_time: [
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' }
        ]
      },
      workScheduleFormRules: {
        name: [{ required: true, message: '请输入排班名称', trigger: 'blur' }],
        starttime: [
          { required: true, message: '请选择上班时间', trigger: 'blur' }
        ],
        endtime: [
          { required: true, message: '请选择下班时间', trigger: 'blur' }
        ]
      },
      // mechForm: {
      //   target_id_set: []
      // },
      value2: '',
      activeIndex: 0,
      work_schedule_add: false,
      value4: '',
      value5: '',
      checkin_mech_add: false,
      checkin_dingtalk_appkey: '',
      checkin_dingtalk_secret: '',
      checkin_sys_secret: '',
      checkin_wexin_secret: '',
      checkin_type: 1,
      // value2:'',
      // value1:'',
      setpIndex: 0,
      Xtoken: { 'X-Token': getToken() },
      files: [],

      setting_show: false,
      profile: this.$store.getters.user_info,
      filter: {
        status: [],
        keywords: '',
        // time_range: time_range
        time_range: ''
      },
      employeeOptions: [],
      loading: false,
      // 0事假，1病假，2婚假，3丧假，4产假，5其它
      type_list: [],
      dialogTaskVisible: false,
      dialogTaskTitle: '记录考勤',
      totalCount: 0,
      currentPage: 1,
      pageLimit: 10,
      tableData: null,
      dialogCreateCategoryVisible: false,
      dialogEditCategoryVisible: false,
      taskFormApi: '/integral.php/attendance/add',
      isRequest: false,
      employee_list: [],
      downurl:'',
      // mechFormRules: {},
      taskForm: {
        // labelPosition: 'right',
        employee_id: '',
        duration: 0,
        item_id: '',
        remark: '',
        // time_range: [-1,-1],
        value1: '',
        value2: '',
        starttime: '',
        endtime: '',
        file_list: [],
        point: 0
      },
      taskFormRules: {
        item_id: [{ required: true, message: '请选择类型', trigger: 'change' }],
        // time_range: [
        //   { required: true, message: "请选择时间", trigger: "blur" }
        // ],
        // value1: [
        //   { type: "datetime", required: true, trigger: "blur",validator: validateTimeS }
        // ],
        // time_star: [
        //   { required: true, trigger: "blur",validator: validateTimeS }
        // ],
        starttime: [
          { required: true, message: '请选择上班时间', trigger: 'blur' }
        ],
        endtime: [
          { required: true, message: '请选择下班时间', trigger: 'blur' }
        ],
        employee_id: [
          { required: true, message: '请选择员工', trigger: 'blur' }
        ]
      },
      accessEnabled: {
        add: 0,
        delete: 0,
        edit: 0
      },
      get_file_info_timer:null,
      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()])
            }
          }
        ]
      }
    }
  },
  beforeRouteLeave (to, from, next) {
    clearTimeout(this.get_file_info_timer)
    next()
  },
  filters:{
    get_status_text(list){
      if(typeof(list) == 'undefined'){
        return ''
      }
      if(list.length == 0){
        return '休息'
      }
      for(let i in list){
        if(list[i].result_code == 9){
          return '';
        }
        if(list[i].result_code == 6){
          return list[i].result_text
        }
        if(list[i].result_code != 0 && list[i].result_code != 9){
          return '异常'
        }
      }
      return '正常'
    },
  },
  methods: {
    tips_close() {
      localStorage.getItem('attendance_statisticnew_tips', 'true')
      this.tips_show = false
    },

   dateTimeFormatter_go: function(row, column, cellValue) {
      return cellValue
        ? this.$moment(cellValue * 1000).format('YYYY-MM-DD')
        : row.go_checkin_str
    },

    // 迟到
    _late_list_show(row, type){
      this.late_list_show = true
      let url = '/ad/attendance_data/late_detail'
      let late_text = '迟到';
      if(type == 2){
        late_text = '严重迟到'

      }
      if(type == 3){
        late_text = '旷工迟到'

      }
       let self = this;
        let time_range = JSON.parse(JSON.stringify(self.filter.time_range))


        if (time_range.length > 0) {
            time_range[0] = time_range[0] * 1 / 1000
            time_range[1] = (time_range[1]*1/1000) + 24*3600-1
        }else {
            let newarray = [];
            const current = new Date();
            const year = current.getFullYear();   // 得到年份z
            let month = current.getMonth() + 1;       // 得到月份
            let date = current.getDate();         // 得到日期
            let day = current.getDay();           // 得到周几
            let first = year+'/' + month +'/' + '/' + '01'
            let late = year+'/' + month +'/' + date
            const timestamp= (new Date(first))/1000
            const late2 = (new Date(late))/1000
            newarray[0] = timestamp*1
            newarray[1] = (late2*1) + 24*3600-1
            time_range = newarray
        }

     //{{$moment(item.checkin_time * 1000).format('HH:mm')}}
     // this.late_list_title = row.name +'  '+ moment(time_range[0]).format('YYYY-MM-DD')+'~'+moment(time_range[1]).format('YYYY-MM-DD') + '  '+late_text
     this.late_list_title = row.name +'  '+ moment(time_range[0] * 1000).format('YYYY-MM-DD')+'~'+moment(time_range[1] * 1000).format('YYYY-MM-DD') + '  '+late_text
        // startDate: moment(self.filter.time_range[0]).format('YYYY-MM-DD'),
          // endDate: moment(self.filter.time_range[1]).format('YYYY-MM-DD'),
      this.$jtoken.get(this.serveAd + url,{
        params: {

          time_range: time_range.toString(),
          employee_id: row.employee_id,
          page: 1,
          page_size: 100
        }
      }).then((res) => {

        if(res.data.code == 1){
           self.late_list_tableData = res.data.data.list
        }
      })
    },



    // 早退  /ad/attendance_data/leave_detail
    _leave_list_show(row){
      this.leave_list_show = true
      let self = this;
        let time_range = JSON.parse(JSON.stringify(self.filter.time_range))


        if (time_range.length > 0) {
            time_range[0] = time_range[0] * 1 / 1000
            time_range[1] = (time_range[1]*1/1000) + 24*3600-1
        }else {
            let newarray = [];
            const current = new Date();
            const year = current.getFullYear();   // 得到年份
            let month = current.getMonth() + 1;       // 得到月份
            let date = current.getDate();         // 得到日期
            let day = current.getDay();           // 得到周几
            let first = year+'/' + month +'/' + '/' + '01'
            let late = year+'/' + month +'/' + date
            const timestamp= (new Date(first))/1000
            const late2 = (new Date(late))/1000
            newarray[0] = timestamp*1
            newarray[1] = (late2*1) + 24*3600-1
            time_range = newarray
        }

        var  params = {
              // startDate: moment(self.filter.time_range[0]).format('YYYY-MM-DD'),
              // endDate: moment(self.filter.time_range[1]).format('YYYY-MM-DD'),
              time_range: time_range.toString(),
              employee_id: row.employee_id,
              page: 1,
              page_size: 100
            }
     // this.leave_list_title = row.name +'  '+ moment(this.filter.time_range[0]).format('YYYY-MM-DD')+'~'+moment(this.filter.time_range[1]).format('YYYY-MM-DD') + '  早退'
      this.leave_list_title = row.name +'  '+ moment(time_range[0] * 1000).format('YYYY-MM-DD')+'~'+moment(time_range[1] * 1000).format('YYYY-MM-DD')+ ' 早退'
      this.$jtoken.get(this.serveAd + '/ad/attendance_data/leave_detail', {
          params: params
        }).then((res) => {
         if(res.data.code == 1){
           self.leave_list_tableData = res.data.data.list
        }

      })
    },

    _go_lack_detail_show(row, type){
      this.go_lack_detail_show = true
      let title_text = '上班缺卡'
      if(type == 2){
        title_text = '下班缺卡'
      }
      if(type == 3){
        title_text = '旷工'
      }
        let self = this;
        let time_range = JSON.parse(JSON.stringify(self.filter.time_range))
        if (time_range.length > 0) {
            time_range[0] = time_range[0] * 1 / 1000
            time_range[1] = (time_range[1]*1/1000) + 24*3600-1
        }else {
            let newarray = [];
            const current = new Date();
            const year = current.getFullYear();   // 得到年份
            let month = current.getMonth() + 1;       // 得到月份
            let date = current.getDate();         // 得到日期
            let day = current.getDay();           // 得到周几
            let first = year+'/' + month +'/' + '/' + '01'
            let late = year+'/' + month +'/' + date
            const timestamp= (new Date(first))/1000
            const late2 = (new Date(late))/1000
            newarray[0] = timestamp*1
            newarray[1] = (late2*1) + 24*3600-1
            time_range = newarray
        }
     this.go_lack_detail_title = row.name +'  '+ moment(time_range[0] * 1000).format('YYYY-MM-DD')+'~'+moment(time_range[1] * 1000).format('YYYY-MM-DD') + '  '+title_text
      let url = '/ad/attendance_data/no_check_in'
      if(type == 2){
        url = '/ad/attendance_data/no_check_out'
      }
      if(type == 3){
        url = '/ad/attendance_data/absenteeism_detail'
      }
      let params = {
          time_range: time_range.toString(),
          employee_id: row.employee_id,
          page: 1,
          page_size:　20
      }

      this.$jtoken.get(this.serveAd + url, {
          params: params
        }).then((res) => {
        if(res.status == 200){
          self.go_lack_detail_tableData = res.data.data.list
        }
      })
    },



  // 显示考勤详情的弹窗
    set_attendance_show(list, status){
      if(list.length == 0){
        return false;
      }
      let newdata = list.replace(/_/g,"/");
      let employee_id = status.employee_id;
      let date = "00:00:00"
      let news = newdata +'/' + date
      let date1 = "23:59:59"
      const timestamp1= (new Date(news))/1000
      let new2 = newdata +'/' + date1
      const timestamp2= (new Date(new2))/1000

      let date3 = timestamp2
      let time_range = [];
      time_range[0] = timestamp1;
      time_range[1] = date3;
      this.$jtoken.get(this.serveAd+'/ad/attendance_data/check_result',
       {
         params: {
           page: 1,
           page_size: 20,
           time_range: time_range.toString(),
           employee_id:employee_id
         }
       }
      )
      .then(res => {
        if(res.data.code == 1) {
          this.attendance_info = res.data.data.list
          this.attendance_show = true;
        }
      })

    },
    reflush_data(){
      let self = this
      this.create_file_loading1 = true
      this.$jtoken.get('/integral.php/attendance_excel/reflush_data.html',{
        params: {
          time_range: self.filter.time_range
        }
      }).then((res) => {
        self.create_file_loading1 = false
        if(res.status == 200){
          if(res.data.code == 1){
            self.$message.success(res.data.msg)
          }else{
            self.$message.error(res.data.msg)
          }
        }
      })
    },

    // create_file(){
    //   let self = this
    //   if(self.file_url != ''){
    //     window.open(self.file_url, '_blank')
    //     return
    //   }
    //   this.create_file_loading = true
    //   this.$jtoken.get('/integral.php/attendance_excel/create_file.html', {
    //     params: {
    //       time_range: self.filter.time_range
    //     }
    //   }).then((res) => {
    //     self.create_file_loading = false

    //     if(res.status == 200){
    //       if(res.data.code == 1){
    //         self.$message.success(res.data.msg)
    //       }else{
    //         self.$message.error(res.data.msg)
    //       }
    //     }else{

    //     }
    //   })
    // },



    checkinMechCloseHandle() {
      this.checkinMechApi = '/integral/attendance/set_attendance_config' // 默认添加考勤机
      this.$refs.checkinMechForm.resetFields()
      this.checkinMechForm = {
        name: '',
        ip: '',
        port: '',
        machine_id: '',
        config_ids: []
      }
    },

    workScheduleCloseHandle() {
      this.$refs.workScheduleForm.resetFields()
      this.activeIndex = 0
      this.workScheduleForm = {
        name: '',
        starttime: '',
        endtime: '',
        send_time: {
          starttime: '',
          endtime: ''
        },
        employee_ids: [],
        job_time: [
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' },
          { starttime: '', endtime: '' }
        ]
      }
    },
    getWorkScheduleById(id) {
      this.$jtoken.get('/integral/attendance/get_attendance_machine_setting', {
        params: {
          id
        }
      }).then(res => {
        if (res.status == 200) {
          this.workScheduleList = res.data.data
        }
      })
    },
    delWorkScheduleById(id) {
      this.$jtoken.get('/integral/attendance/delete_attendance_config', {
        params: {
          id
        }
      }).then(res => {
        if (res.status == 200) {
          this.$message({
            message: res.data.message,
            type: 'success'
          })
          this.getAttendanceMech()
        }
      })
    },
    checkinMechShow(item) {
      this.checkinMechApi = '/integral/attendance/update_attendance_config'
      this.checkinMechForm['id'] = item.id
      this.checkin_mech_add = true
      this.checkinMechForm.name = item.name
      this.checkinMechForm.ip = item.ip
      this.checkinMechForm.port = item.port
      this.checkinMechForm.machine_id = item.machine_id
      this.getWorkScheduleById(item.id)
    },
    checkinMechSave() {
      if (this.workScheduleList.length === 0) {
        this.$message({
          message: '请先设置排班',
          type: 'error'
        })
        return false
      }
      this.checkinMechForm.config_ids = []
      this.workScheduleList.forEach(item => {
        this.checkinMechForm.config_ids.push(item.id)
      })
      this.checkinMechForm.kq_site_id = this.profile.company_info.id
      this.$refs['checkinMechForm'].validate((valid) => {
        if (valid) {
          this.$jtoken.post(this.checkinMechApi,
            this.checkinMechForm
          ).then(res => {
            if (res.data.status === 1) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.checkin_mech_add = false
              this.$refs['checkinMechForm'].resetFields()
              this.getAttendanceMech()
            }
          })
        } else {
          return false
        }
      })
    },
    // 字符串时间格式转换为时间格式
    // stringToDate(hour, minutes) {
    //   const date = new Date()
    //   return new Date(date.getFullYear(), date.getMonth(), date.getDate(), hour, minutes)
    // },
    delWorkScheduleItem(id) {
      this.workScheduleList.forEach((item, i) => {
        if (item.id == id) {
          this.workScheduleList.splice(i, 1)
        }
      })
    },
    eidtWorkScheduleShow(id) {
      this.workScheduleApi = '/integral.php/attendance/setting_update'
      this.$jtoken.get('/integral.php/attendance/get_setting_by_id', {
        params: { id }
      }).then(res => {
        if (res.data.code === 1) {
          this.workScheduleForm['id'] = res.data.data.config.id
          this.workScheduleForm.name = res.data.data.config.name
          this.workScheduleForm.send_time = res.data.data.config.send_time
          this.workScheduleForm.starttime = res.data.data.config.send_time.starttime
          this.workScheduleForm.endtime = res.data.data.config.send_time.endtime
          this.workScheduleForm.employee_ids = res.data.data.config.employee_ids
          this.workScheduleForm.job_time = res.data.data.config.job_time
          // res.data.data.config.job_time.forEach((item, i) => {
          //   if (item.starttime && item.endtime) {
          //     this.workScheduleForm.job_time[i].starttime = this.stringToDate(item.starttime.split(':')[0], item.starttime.split(':')[1])
          //     this.workScheduleForm.job_time[i].endtime = this.stringToDate(item.endtime.split(':')[0], item.endtime.split(':')[1])
          //   }
          // })
          // this.workScheduleForm.starttime = this.stringToDate(res.data.data.config.send_time.starttime.split(':')[0], res.data.data.config.send_time.starttime.split(':')[1])
          // this.workScheduleForm.endtime = this.stringToDate(res.data.data.config.send_time.endtime.split(':')[0], res.data.data.config.send_time.endtime.split(':')[1])
          this.employeeSelectorIds = res.data.data.config.employee_ids.map(item => {
            return parseInt(item)
          })
        }
      })
      this.work_schedule_add = true
      // get_setting_by_id
    },
    // editworkSchedule() {

    // },
    workScheduleSave() {
      if (this.workScheduleForm.employee_ids.length === 0) {
        this.$message({
          message: '请选择奖扣积分对象',
          type: 'error'
        })
        return false
      }

      // 删除多余参数
      delete this.workScheduleForm.starttime
      delete this.workScheduleForm.endtime
      // 转换时间格式
      // this.workScheduleForm.job_time.forEach((item, i) => {
      //   if (item.starttime && item.endtime) {
      //     this.workScheduleForm.job_time[i].starttime = this.$moment(this.workScheduleForm.job_time[i].starttime.valueOf()).format('HH:mm')
      //     this.workScheduleForm.job_time[i].endtime = this.$moment(this.workScheduleForm.job_time[i].endtime.valueOf()).format('HH:mm')
      //   }
      // })
      this.$jtoken.post(this.workScheduleApi, {
        row: this.workScheduleForm
      }).then((res) => {
        if (res.data.code == 1) {
          this.$message({
            message: res.data.msg,
            type: 'success'
          })
          this.work_schedule_add = false
          this.getWorkScheduleList()
        }
      }).catch((e) => {})
    },
    checkInMechShow() {
      this.checkin_mech_add = true
      this.getWorkScheduleList()
    },
    getWorkScheduleList() {
      this.$jtoken.get('/integral/attendance/get_setting_list').then(res => {
        if (res.status == 200) {
          this.workScheduleList = res.data.data.list
        }
      })
    },
    handleCopy(text, event) {
      clip(text, event)
    },
    // clipboardSuccess() {
    //   this.$message({
    //     message: 'Copy successfully',
    //     type: 'success',
    //     duration: 1500
    //   })
    // },
    setCheckInType() {
      this.setting_show = true
      // 获取系统打卡API密码
      this.getAttendanceAuth()
      // 获取考勤机配置列表
      this.getAttendanceMech()
    },
    set_target_ids(data) {
      const self = this
      self.workScheduleForm.employee_ids = []
      for (const i in data) {
        self.workScheduleForm.employee_ids.push(data[i].id)
      }
    },
    activeIndexPrev() {
      this.activeIndex--
    },
    activeIndexNext() {
      if (this.activeIndex == 0) {
        var isSchedule = false
        this.workScheduleForm.job_time.forEach((item, i) => {
          if (item.starttime && item.endtime) {
            isSchedule = true
          }
        })
        if (!isSchedule) {
          this.$message({
            message: '请设置排班时间',
            type: 'error'
          })
          return false
        }
      }
      if (this.activeIndex == 1) {
        var isValid = true
        this.$refs.workScheduleForm.validate(valid => {
          isValid = valid
        })
        if (!isValid) {
          return false
        }
        this.workScheduleForm.send_time.starttime = this.workScheduleForm.starttime
        this.workScheduleForm.send_time.endtime = this.workScheduleForm.endtime
      }
      this.activeIndex++
    },
    cancelHandle() {
      this.work_schedule_add = false
      // this.resetCreateDialog()
      this.activeIndex = 0
    },

    fileProview(url, list, key) {
      const $ext_list = ['doc', 'docx', 'pptx', 'xls', 'xlsx', 'ppt', 'txt']
      const $ext_name = url.split('.')[1]
      if ($ext_list.indexOf($ext_name) >= 0) {
        window.open(
          'https://view.officeapps.live.com/op/view.aspx?src=' +
            this.serverdomain +
            url,
          '_blank'
        )
      }
      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].url.split('.')[1]) >=
            0
          ) {
            if (list[i].url == url) {
              this.openPhotoSwipe(
                ii,
                document.querySelectorAll('img[preview="' + key + '"]')
              )

              return
            }
            ii++
          }
        }
      }
    },
    time_star_change(val) {
      this.taskForm.value1 = val
      this.taskForm.starttime = val

      if (this.taskForm.value2 == '' || this.taskForm.value1 == '') {
        this.taskForm.duration = 0
      } else {
        if (typeof this.taskForm.value2 === 'string') {
          const timestamp = this.transDate(this.taskForm.value2)
          const newDate = new Date()
          this.taskForm.value2 = newDate.setTime(timestamp * 1000)
        }
        this.taskForm.duration = (
          (this.taskForm.value2 - this.taskForm.value1) /
          3600 /
          1000
        ).toFixed(1)
      }
    },
    time_end_change(val) {
      this.taskForm.value2 = val
      this.taskForm.endtime = val
      if (this.taskForm.value2 == '' || this.taskForm.value1 == '') {
        this.taskForm.duration = 0
      } else {
        if (typeof this.taskForm.value1 === 'string') {
          const timestamp = this.transDate(this.taskForm.value1)
          const newDate = new Date()
          this.taskForm.value1 = newDate.setTime(timestamp * 1000)
        }
        this.taskForm.duration = (
          (this.taskForm.value2 - this.taskForm.value1) /
          3600 /
          1000
        ).toFixed(1)
      }
    },
    transDate(time) {
      const date = new Date()
      date.setFullYear(time.substring(0, 4))
      date.setMonth(time.substring(5, 7) - 1)
      date.setDate(time.substring(8, 10))
      date.setHours(time.substring(11, 13))
      date.setMinutes(time.substring(14, 16))
      date.setSeconds(time.substring(17, 19))
      return Date.parse(date) / 1000
    },
    dialogNext() {
      if (this.setpIndex == 0 && this.taskForm.employee_ids.length == 0) {
        this.$message.error('请至少选择一个员工')
        return false
      }
      this.setpIndex++
    },

    dialogPrev() {
      this.setpIndex--
    },

    // 获取可录入积分对象的列表
    loadTargetRange: function() {
      var self = this
      this.$jtoken
        .get('/integral.php/ajax_request_common/load_target_range', {
          params: {
            recorder_id: this.profile.id
          }
        })
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.employeeOptions = jsonData
            } catch (err) {
            }
          }
        })
        .catch(function(error) {
        })
    },

    onFilePreView(file) {
      // 点击时查看文件
      const $ext_list = ['doc', 'docx', 'pptx', 'xls', 'xlsx', 'ppt', 'txt']
      const $ext_name = file.name.split('.')[1]
      if ($ext_list.indexOf($ext_name) >= 0) {
        window.open(
          'https://view.officeapps.live.com/op/view.aspx?src=' +
            this.serverdomain +
            file.response.url,
          '_blank'
        )
      }
      // 点击时查看图片
      const $ext_list1 = ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']
      const $ext_name1 = file.name.split('.')[1]
      if ($ext_list1.indexOf($ext_name1) >= 0) {
        let ii = 0
        for (const i in this.taskForm.file_list) {
          if (
            ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG'].indexOf(
              this.taskForm.file_list[i].name.split('.')[1]
            ) >= 0
          ) {
            if (this.taskForm.file_list[i].name == file.name) {
              this.openPhotoSwipe(
                ii,
                document.querySelectorAll('img[preview]')
              )

              return
            }
            ii++
          }
        }
      }
    },

    onFileRemove(file, fileList) {
      this.taskForm.file_list = fileList
    },

    handleFilesSuccess(response, file, fileList) {
      // this.taskForm.file_list = fileList;
      this.$set(this.taskForm, 'file_list', fileList)
    },
    beforeFilesUpload() {},
    handleSizeChange(val) {
      this.pageLimit = val
      this.onFilterChanged()
    },
    filterHandler: function(value) {
      if (typeof value.status !== 'undefined' && value.status.length == 0) {
        this.filter.status = []
      }
      if (typeof value.status !== 'undefined' && value.status.length > 0) {
        this.filter.status = value['status']
      }

      this.onFilterChanged()
    },

    load_attendance_type_list() {
      const self = this
      this.$jtoken
        .get('/integral.php/attendance/get_attendance_type_list')
        .then(ret => {
          const list = ret.data.data
          self.type_list = []
          for (const i in list) {
            self.type_list.push({ value: list[i].id, text: list[i].content })
          }
          // 固定类型，写死先
          self.type_list.push({ value: 0, text: '出勤' })
          // self.type_list = [{value: 0,text: '出勤'}]
        })
    },
    dialogTaskClose: function() {
      const form = this.$refs['newTaskForm']
      form.clearValidate()
      this.dialogTaskVisible = false
    },

    dialogTaskOpen: function(target, id) {
      this.load_attendance_type_list()
      // this.loadRuleList()

      const self = this
      this.setpIndex = 0
      this.dialogTaskTitle = typeof id === 'undefined' ? '记录考勤' : '修改'
      this.dialogTaskVisible = true
      if (typeof id !== 'undefined') {
        // self.taskForm["id"] = id;
        self.taskFormApi = '/integral.php/attendance/update'
        this.loadTaskInfo(id)
      } else {
        this.taskForm = {
          employee_id: '',
          duration: 0,
          item_id: '',
          remark: '',
          // time_range: null,
          file_list: [],
          point: 0
        }
        self.taskFormApi = '/integral.php/attendance/add'
      }
      this.$nextTick(() => {
        const form = this.$refs['newTaskForm']
        if (typeof id === 'undefined') {
          form.resetFields()
          form.clearValidate()
        }
      })
    },

    employee_selected(data) {
      this.taskForm.employee_ids = []
      for (const i in data) {
        this.taskForm.employee_ids.push(data[i].id)
      }
    },

    loadTaskInfo(id) {
      this.$jtoken
        .get('/integral.php/attendance/get_info', {
          params: {
            id: id
          }
        })
        .then(response => {
          if (response.status == 200) {
            var jsonData = response.data.data
            this.taskForm = {
              id: jsonData.id,
              employee_id: jsonData.employee_id,
              duration: jsonData.duration,
              item_id: jsonData.item_id,
              remark: jsonData.remark,
              starttime: this.dateTimeFormatter('', '', jsonData.starttime),
              endtime: this.dateTimeFormatter('', '', jsonData.endtime),
              value1: this.dateTimeFormatter('', '', jsonData.starttime),
              value2: this.dateTimeFormatter('', '', jsonData.endtime),
              // time_range: null,
              file_list: []
              // point: 0
            }
          }
        })
        .catch(error => {
        })
    },

    dialogSettingSend() {
      /*if (this.attendanceMechList.length === 0) {
        this.$message({
          message: '请先添加考勤机',
          type: 'error'
        })
        return false
      }*/
      const self = this
      this.$jtoken({
        url: '/integral.php/attendance/save_corpsecret',
        data: qs.stringify({
          row: {
            checkin_dingtalk_appkey: self.checkin_dingtalk_appkey,
            checkin_dingtalk_secret: self.checkin_dingtalk_secret,
            checkin_wexin_secret: self.checkin_wexin_secret,
            checkin_type: self.checkin_type
          }
        }),
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
        .then(function(res) {
          if (res.data.code == 1) {
            self.setting_show = false
            self.$message.success(res.data.msg)
          } else {
            self.$message.error(res.data.msg)
          }
        })
        .catch(function(err) {})
    },

    getAttendanceAuth() {
      this.$jtoken
        .get('/integral/attendance/attendance_config_auth_select', {
          params: {
            kq_site_id: this.profile.company_info.id
          }
        })
        .then(res => {
          if (res.status == 200) {
            this.checkin_sys_secret = res.data.data.auth
          }
        })
    },

    getAttendanceAuthAgain() {
      this.$jtoken
        .get('/integral/attendance/attendance_config_auth', {
          params: {
            kq_site_id: this.profile.company_info.id
          }
        })
        .then(res => {
          if (res.status == 200) {
            this.$message({
              message: '获取成功',
              type: 'success',
              duration: 1500
            })
            this.checkin_sys_secret = res.data.data.auth
          }
        })
    },
    getAttendanceMech() {
      this.$jtoken
        .get('/integral/attendance/select_attendance_config', {
          params: {
            kq_site_id: this.profile.company_info.id
          }
        })
        .then(res => {
          if (res.status == 200) {
            this.attendanceMechList = res.data.data
          }
        })
    },

    dialogTaskSend: function() {
      const self = this
      if (self.isRequest) {
        return
      }
      const form = this.$refs['newTaskForm']
      delete this.taskForm.value1
      delete this.taskForm.value2
      form.validate(valid => {
        if (valid) {
          this.$jtoken({
            url: self.taskFormApi,
            data: qs.stringify({ row: this.taskForm }),
            method: 'post',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          })
            .then(function(response) {
              setTimeout(function() {
                self.isRequest = false
              }, 200)

              var message = ''
              var status = 0
              if (response.status == 200) {
                var data = response.data

                message = data.msg

                if (data.code == 1) {
                  self.$message({
                    message: message,
                    type: 'success'
                  })
                } else {
                  self.$message({
                    message: message,
                    type: 'error'
                  })
                }
              } else {
                message = '服务器太忙了'
              }
            })
            .catch(function(error) {
            })
        } else {
          return false
        }
      })
    },
    onFilterChanged: function() {
      if(this.filter.time_range == null){
        this.filter.time_range = []
      }
      this.currentPage = 1
      this.$refs.dept1.dropDownVisible = false;
      this.loadTaskList()
      this.get_file_info()
    },
    dateTimeFormatter: function(row, column, cellValue) {
      return cellValue
        ? this.$moment(cellValue * 1000).format('MM-DD HH:mm')
        : '缺卡'
    },

    time_convert: function(row, column, cellValue) {

      return (cellValue/3600).toFixed(2)+''
    },
    formatTime(row, colum, cellValue) {
      return cellValue ? (cellValue / 3600).toFixed(1) + '小时' : '无'
    },
    taskStatusText: function(row, column, cellValue) {
      let text = ''
      switch (cellValue) {
        case 0:
          text = '未领取'
          break
        case 1:
          text = '已领取'
          break
        case 2:
          text = '已完成'
          break
        case -1:
          text = '已取消'
          break
      }
      if (row.expire_text != '') {
        return text + '-' + row.expire_text
      }
      return text
    },

    exporExcelJump() {
      window.open(this.downurl, '_blank')
    },
    get_file_info(){
      // this.dialogVisible = true;
      var self = this
       let time_range = JSON.parse(JSON.stringify(self.filter.time_range))
        if (time_range == null) {
          time_range = []
        }
        if (time_range.length > 0) {
            time_range[0] = time_range[0] * 1 / 1000
             time_range[1] = (time_range[1]*1/1000) + 24*3600-1
        }
         var params = {
            site_id: this.profile.site_id,
            time_range: time_range.toString(),
            page: this.currentPage,
            page_size: this.pageLimit,
            dept_id:　this.category_id_BL
          }
      if(self.department_id.length > 0){
        params['dept_id'] = self.department_id[self.department_id.length - 1]
      }
      if(self.target_id_set.length > 0){
        params['employee_id'] = self.target_id_set
      }
      params['export'] = 1;
      this.$jtoken
        .get(this.serveAd + '/ad/attendance_data/get_code', {
          params: params
        })
        .then(function(response) {
          if (response.data.code == 1) {
            self.downurl = self.serveAd+'/ad/attendance_data/statistic_export?code='+response.data.data.code
          }
        })
        .catch(function(error) {
        })
    },

   openDalod() {
     window.open(this.downurl,'_blank')
     this.dialogVisible = false;
   },

    // 列表接口
    loadTaskList: function() {
      this.loading = true
      var self = this
      if(this.category_id.length == 0){
        this.category_id_BL = 0
      }else{
        for(let i in this.category_id){//遍历出部门id中最后一位
          this.category_id_BL = this.category_id[i]
        }
      }


       let time_range = JSON.parse(JSON.stringify(self.filter.time_range))
        if (time_range.length > 0) {
            time_range[0] = time_range[0] * 1 / 1000
            time_range[1] = (time_range[1]*1/1000) + 24*3600-1
        }else {
            let newarray = [];
            const current = new Date();
            const year = current.getFullYear();   // 得到年份
            let month = current.getMonth() + 1;       // 得到月份
            let date = current.getDate();         // 得到日期
            let day = current.getDay();           // 得到周几
            let first = year+'/' + month +'/' + '/' + '01'
            let late = year+'/' + month +'/' + date
            const timestamp= (new Date(first))/1000
            const late2 = (new Date(late))/1000
            newarray[0] = timestamp*1
            newarray[1] = (late2*1) + 24*3600-1
            time_range = newarray
        }
         var params = {
            site_id: this.profile.site_id,
            time_range: time_range.toString(),
            page: this.currentPage,
            page_size: this.pageLimit,
            dept_id:　this.category_id_BL
          }
          
      if(self.department_id.length > 0){
        params['dept_id'] = self.department_id[self.department_id.length - 1]
      }

      if(self.target_id_set.length > 0){
        params['employee_id'] = self.target_id_set
      }


      this.$jtoken
        .get(this.serveAd + '/ad/attendance_data/monthly_statistic', {
          params: params
        })
        .then(function(response) {
          
          if (response.data.code == 1) {
            self.loading = false
            var jsonData = response.data
            try {
              self.totalCount = jsonData.data.total
              self.tableData = jsonData.data.list
              self.tableDataList =  jsonData.data.holiday_list
              self.table_header = jsonData.data.table_header
            } catch (err) {
            }
          }
        })
        .catch(function(error) {
        })
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false
      }
      this.loadTaskList()
    },
    onDismissCreateCategoryDialog: function() {
      var form = this.$refs['newCategoryForm']
      form.clearValidate()
      this.newCategoryForm = {
        name: '',
        pid: []
      }
    },
    onDismissEditCategoryDialog: function() {
      var form = this.$refs['categoryForm']
      form.clearValidate()
      this.categoryForm = {
        id: '',
        name: '',
        pid: []
      }
    },
    // 递归判断列表，把最后的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;
    },
    submitCreateCategoryForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendCreateCategoryRequest()
          }
        } else {
          return false
        }
      })
    },
    submitEditCategoryForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.submitEditCategoryForm(form)
          }
        } else {
          return false
        }
      })
    },

    confirmDelete: function(taskId) {
      this.$confirm('确定要删除此任务吗？', '删除任务', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteTask(taskId)
        })
        .catch(() => {})
    },
    getTask: function(taskId) {
      if (!taskId) {
        return false
      }
      const params = {
        id: taskId
      }
      var self = this

      this.$jtoken({
        url: '/integral.php/attendance/get_attendance',
        params: params,
        method: 'get',
        transformRequest: [
          data => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(
                encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
              )
            }
            return paramArray.join('&')
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
        .then(function(response) {
          var message = ''
          var status = 0
          if (response.status == 200) {
            var data = response.data

            message = data.msg

            if (data.code == 1) {
              self.$message({
                message: message,
                type: 'success'
              })
              self.loadTaskList()
            } else {
              self.$message({
                message: message,
                type: 'error'
              })
            }
          } else {
            message = '服务器太忙了'
          }
        })
        .catch(function(error) {
        })
    },
    deleteTask: function(taskId) {
      if (!taskId) {
        return false
      }
      const params = {
        id: taskId
      }
      var self = this

      this.$jtoken({
        url: '/integral.php/attendance/delete',
        data: params,
        method: 'post',
        transformRequest: [
          data => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(
                encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
              )
            }
            return paramArray.join('&')
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
        .then(function(response) {
          var message = ''
          var status = 0
          if (response.status == 200) {
            var data = response.data

            message = data.msg

            if (data.code == 1) {
              self.$message({
                message: message,
                type: 'success'
              })
              self.loadTaskList()
            } else {
              self.$message({
                message: message,
                type: 'error'
              })
            }
          } else {
            message = '服务器太忙了'
          }
        })
        .catch(function(error) {
        })
    },
    loadRuleDetail: function(ruleId) {
      const params = {
        id: ruleId
      }
      var self = this
      this.$jtoken
        .get('/integral.php/ajax_request_common/get_rule_info', {
          params: params
        })
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              const detailData = self.processDetailData(jsonData)
              self.detailData.name = detailData.name
              self.detailData.remark = detailData.remark
              self.detailData.category_id = detailData.category_id
              self.detailData.items = detailData.items
              self.detailData.id = detailData.id
            } catch (err) {
            }
          }
        })
        .catch(function(error) {
        })
    }
  },
  mounted(){
    this.loadTaskList()
    this.get_file_info()
    // this.load_attendance_setting_info()
    //this.loadTargetRange()
    // this.loadWidgetData()
    if (this.profile.manager_type == 4) {
      this.accessEnabled = {
        add: 1,
        delete: 1,
        excel_import: 1,
        edit: 1
      }
    } else if (this.profile.manager_type > 1) {
      // this.loadAccessItemFlag();
    }
    if (localStorage.getItem('attendance_statisticnew_tips')) {
      this.tips_show = false
    } else {
      this.tips_show = true
    }
  },
  created() {
    this.dept_tree = this.getTreeData(JSON.parse(localStorage.getItem('dept_tree')))
  }
}
</script>
<style scoped>
.el-pagination {
  text-align: center;
  margin-top: 15px;
}

.dialog_box .el-dialog__header {
  display: none;
}
/deep/ .downlowd .el-dialog__body {
    padding: 30px 20px 60px 20px;
    text-align: center;
}
.alignColor{
  text-align: left;
    padding-left: 20px;
    line-height: 30px;
}
</style>
