<template>
  <div style=" background-color: #fff; padding:15px; min-height: calc(100vh - 160px);" class="attendance-manage">
    <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
        ref="dept1"
        v-model="department_id"
        @change="onFilterChanged"
        placeholder="选择部门"
        style="width:120px;margin-left:10px;"
        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>



      <el-button type="primary" @click="exporExcelJump" style="margin-left:10px;">下载统计数据</el-button>


    </div>

    <el-table
      stripe
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      @filter-change="filterHandler"
      style="width: 100%"
    >
      <el-table-column prop="employee_name" label="姓名" width="80px"></el-table-column>
      <el-table-column prop="employee_number" label="工号" width="80px"></el-table-column>

      <el-table-column label="上班" align="center">
        <el-table-column prop="base_starttime" label="上班时间" align="center" width="100px">

          <template slot-scope="scope">

            <div>{{dateTimeFormatter1('','',scope.row.base_starttime)}}</div>
            <div>{{dateTimeFormatterTime('','',scope.row.base_starttime)}}</div>
          </template>

        </el-table-column>


        <el-table-column label="打卡时间" align="center" width="100px">
          <template slot-scope="scope">

            <div>{{dateTimeFormatter_go(scope.row,'',scope.row.starttime)}}</div>
            <div>{{dateTimeFormatterTime('','',scope.row.starttime)}}</div>
          </template>
        </el-table-column>
        <el-table-column label="积分" prop="start_point" align="center">
          <template slot-scope="scope">
            <el-tooltip v-for="(item,index) in scope.row.start_point" :key="index" v-if="item.point > 0" class="item" effect="dark" :content="item.remark" placement="top-start"><span style="color: #42b983;padding:0 10px;cursor: default;">+{{item.point}}</span></el-tooltip>
            <el-tooltip v-for="(item,index) in scope.row.start_point" :key="index" v-if="item.point < 0"  class="item" effect="dark" :content="item.remark" placement="top-start"><span style="color: #F56C6C; padding:0 10px; cursor: default;">{{item.point}}</span></el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="start_remark" align="center">

          <template slot-scope="scope">
            {{scope.row.start_remark}}
            <div v-for="(item,index) in scope.row.start_result" :key="index">
              <el-tag type="danger" >{{item}}</el-tag>
            </div>

          </template>

        </el-table-column>
        <el-table-column label="是否外勤" prop="start_remark" align="center">
          <template slot-scope="scope">
            <el-popover
              v-if="scope.row.checkin_range_status == 2"
              placement="top"
              title=""
              width="200"
              trigger="click"
              :content="scope.row.checkin_address">
              <!-- <el-button slot="reference">是</el-button> -->
              <span style="cursor:pointer" slot="reference">是</span>
            </el-popover>
            <span v-else></span>
          </template>
        </el-table-column>
        <!--     v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(scope.row.start_filelist.split('.')[1]) >= 0" -->
        <el-table-column label="附件" prop="start_filelist" align="center">
          <template slot-scope="scope">
            <img width="30" height="30"
                 v-if="scope.row.start_filelist"
                 @click="fileProview(scope.row.start_filelist)"
                 :src="scope.row.start_filelist"
            />
          </template>
        </el-table-column>



      </el-table-column>





      <el-table-column label="下班" align="center">


        <el-table-column prop="base_endtime" label="下班时间" align="center"  width="100px">

          <template slot-scope="scope">

            <div>{{dateTimeFormatter1('','',scope.row.base_endtime)}}</div>
            <div>{{dateTimeFormatterTime('','',scope.row.base_endtime)}}</div>
          </template>

        </el-table-column>

        <el-table-column label="打卡时间" align="center"  width="100px">
          <template slot-scope="scope">

            <div>{{dateTimeFormatter_back(scope.row,'',scope.row.endtime)}}</div>
            <div>{{dateTimeFormatterTime('','',scope.row.endtime)}}</div>
          </template>
        </el-table-column>

        <el-table-column prop="end_point" label="积分" align="center">

          <template slot-scope="scope">
            <el-tooltip v-for="(item,index) in scope.row.end_point" :key="index" v-if="item.point > 0" class="item" effect="dark" :content="item.remark" placement="top-start"><span style="color: #42b983;padding:0 10px;cursor: default;">+{{item.point}}</span></el-tooltip>
            <el-tooltip v-for="(item,index) in scope.row.end_point" :key="index" v-if="item.point < 0" class="item" effect="dark" :content="item.remark" placement="top-start"> <span style="color: #F56C6C;padding:0 10px;cursor: default;">{{item.point}}</span></el-tooltip>
          </template>

        </el-table-column>
        <el-table-column label="备注" prop="end_remark" align="center">
          <template slot-scope="scope">
            {{scope.row.end_remark}}

            <div v-for="(item,index) in scope.row.end_result" :key="index">
              <el-tag type="danger" >{{item}}</el-tag>
            </div>


            <!-- <el-tag type="danger" v-if="scope.row.back_range_status == 0">外勤</el-tag> -->
          </template>
        </el-table-column>
        <el-table-column label="是否外勤" prop="start_remark" align="center">
          <template slot-scope="scope">
            <el-popover
              v-if="scope.row.checkout_range_status == 2"
              placement="top"
              title=""
              width="200"
              trigger="click"
              :content="scope.row.checkout_address">
              <span style="cursor:pointer" slot="reference">是</span>
            </el-popover>
            <span v-else></span>
          </template>
        </el-table-column>

        <el-table-column label="附件" prop="end_filelist" align="center">
          <template slot-scope="scope">
            <!-- <img width="30" height="30"
              @click="fileProview(scope.row.back_fileList, scope.row.back_fileList, scope.row.id)"
              :key="scope.row.back_fileList"
              v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(scope.row.back_fileList.split('.')[1]) >= 0"
              :src="serverdomain+scope.row.back_fileList"
              :preview="scope.row.id"
              :preview-text="scope.row.back_fileList"
            > -->

            <img width="30" height="30"
                 v-if="scope.row.end_filelist"
                 @click="fileProview(scope.row.end_filelist)"
                 :src="scope.row.end_filelist"
            />


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

      </el-table-column>

      <el-table-column prop="duration" label="上班时长（小时）" :formatter="formatTime" align="center"></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
      class="dialog_box"
      :title="dialogTaskTitle"
      :visible.sync="dialogTaskVisible"
      width="700px"
      top="50px"
      :close-on-click-modal="false"
    >
      <el-form :model="taskForm" ref="newTaskForm" :rules="taskFormRules" @submit.native.prevent>
        <div class style="padding:50px 90px 0 90px;">
          <el-form-item label="姓名" label-width="75px" prop="employee_id">
            <el-select
              v-model="taskForm.employee_id"
              filterable
              placeholder="选择员工"
              style="width:290px;"
            >
              <el-option
                v-for="item in employeeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="类型" label-width="75px" prop="item_id">
            <el-select v-model="taskForm.item_id" placeholder="请选择请假类型">
              <el-option
                v-for="item in type_list"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="上班时间" prop="starttime" label-width="70px;">
            <el-date-picker
              v-model="taskForm.value1"
              type="datetime"
              @change="time_star_change"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="下班时间" prop="endtime" label-width="70px;">
            <el-date-picker
              v-model="taskForm.value2"
              type="datetime"
              @change="time_end_change"
              placeholder="选择日期时间"
            ></el-date-picker>

          </el-form-item>

          <!-- <div class="block">
              <span class="demonstration">默认</span>
              <el-date-picker
                v-model="value1"
                type="datetime"
                placeholder="选择日期时间">
              </el-date-picker>
          </div>-->
          <!-- <el-form-item label="时间" prop="time_range" label-width="60px">
            <el-date-picker
              v-model="taskForm.time_range"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="time_range_change"
            ></el-date-picker>
          </el-form-item>-->
          <el-form-item label="时长" prop="duration" label-width="75px">
            <el-input-number
              :disabled="true"
              :min="0"
              size="medium"
              :step="0.5"
              v-model="taskForm.duration"
            ></el-input-number>&nbsp;&nbsp;小时
          </el-form-item>

          <el-form-item label="备注" prop="remark" label-width="75px">
            <el-input type="textarea" v-model="taskForm.remark"></el-input>
          </el-form-item>
          <el-form-item label="附件" label-width="75px">
            <el-upload
              :headers="Xtoken"
              class="avatar-uploader"
              :action="serverdomain+'/integral.php/upload'"
              :show-file-list="true"
              :file-list="taskForm.file_list"
              :on-success="handleFilesSuccess"
              :on-preview="onFilePreView"
              :before-upload="beforeFilesUpload"
              :on-remove="onFileRemove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <div style="display:none;">
              <!-- <img
                v-for="(item,index) in taskForm.file_list"
                :key="index"
                v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(item.name.split('.')[1]) >= 0"
                :src="serverdomain+item.response.url"
                :preview="index"
                :preview-text="item.name"
              > -->
            </div>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTaskClose">取 消</el-button>

        <el-button type="primary" @click="dialogTaskSend">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="考勤设置"
      :visible.sync="setting_show"
      width="700px"
      top="50px"
      :close-on-click-modal="false"
    >
      <el-form :model="checkinSettingForm" ref="checkinSettingForm" :rules="checkinSettingFormRules" @submit.native.prevent>
        <div class style="padding:50px 90px 0 90px;">
          <el-form-item label-width="100px">
            <template slot="label">
              打卡途径
              <i class="el-icon-question"></i>
            </template>
            <el-radio v-model="checkin_type" :label="1">企业微信</el-radio>
            <el-radio v-model="checkin_type" :label="2">阿里钉钉</el-radio>
            <el-radio v-model="checkin_type" :label="3">系统自有打卡</el-radio>
          </el-form-item>

          <el-form-item
            v-if="checkin_type == 1"
            label="secret"
            label-width="100px"
            prop="checkin_wexin_secret"
          >
            <el-input type="text" v-model="checkin_wexin_secret"></el-input>
          </el-form-item>

          <el-form-item
            v-if="checkin_type == 2"
            label="secret"
            label-width="100px"
            prop="checkin_dingtalk_secret"
          >
            <el-input type="text" v-model="checkin_dingtalk_secret"></el-input>
          </el-form-item>

          <el-form-item
            v-if="checkin_type == 2"
            label="appkey"
            label-width="100px"
            prop="checkin_dingtalk_appkey"
          >
            <el-input type="text" v-model="checkin_dingtalk_appkey"></el-input>
          </el-form-item>

          <el-form-item
            v-if="checkin_type == 3 && false"
            label="API密码"
            label-width="100px"
            prop="checkin_dingtalk_appkey"
            style="margin-bottom: 5px;"
          >
            <span
              style="width: 150px;overflow: hidden;display: inline-block;text-overflow: ellipsis;"
            >{{checkin_sys_secret}}</span>
            <el-button
              style="vertical-align: top;"
              type="text"
              @click="getAttendanceAuthAgain"
            >重新生成</el-button>
            <!-- <el-button style="vertical-align: top;" type="primary" @click="handleCopy" plain clipboard:copy='checkin_sys_secret' v-clipboard:success='clipboardSuccess'>复制</el-button> -->
            <el-button
              style="vertical-align: top;"
              type="text"
              @click="handleCopy(checkin_sys_secret,$event)"
            >复制</el-button>
          </el-form-item>
          <el-form-item
            v-if="checkin_type == 3 && false"
            label="考勤机"
            label-width="100px"
            prop="checkinMech"
          >
            <el-button @click="checkInMechShow" type="primary" plain>增加考勤机</el-button>
          </el-form-item>

          <el-form-item
            v-if="checkin_type == 3 && attendanceMechList.length != 0"
            label
            label-width="100px"
            prop="checkin_dingtalk_appkey"
          >
            <p
              v-for="item of attendanceMechList"
              :key="item.id"
              style="border: 1px solid #DCDFE6;border-radius: 4px;height: 50px; line-height: 50px;padding-left:15px;display:flex;margin-top: 0;"
            >
              {{item.name}}
              <span @click="delWorkScheduleById(item.id)" style="color:#409EFF;margin-left:auto;cursor:pointer;">删除</span>
              <span @click="checkinMechShow(item)" style="color:#409EFF;margin-left:auto;margin: 0 15px;cursor:pointer;">修改配置</span>
            </p>
            <!-- <p
              style="border: 1px solid #DCDFE6;border-radius: 4px;height: 50px; line-height: 50px;padding-left:15px;display:flex;margin-top: 0;"
            >
              民网考勤机1
              <span style="color:#409EFF;margin-left:auto;cursor:pointer;">删除</span>
              <span style="color:#409EFF;margin-left:auto;margin: 0 15px;cursor:pointer;">修改配置</span>
            </p> -->
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setting_show = false">取 消</el-button>

        <el-button type="primary" @click="dialogSettingSend">保 存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="checkinMechForm.id?'修改考勤机':'增加考勤机'"
      :visible.sync="checkin_mech_add"
      width="730px"
      top="50px"
      :close-on-click-modal="false"
      @close="checkinMechCloseHandle"
    >
      <!-- :close="$ref.checkinMechForm.resetFields()" -->
      <el-form :model="checkinMechForm" ref="checkinMechForm" :rules="checkinMechFormRules" @submit.native.prevent>
        <div class style="padding:50px 90px 0 90px;">
          <el-form-item label="考勤机名称" label-width="100px" prop="name">
            <el-input type="text" v-model="checkinMechForm.name"></el-input>
          </el-form-item>
          <el-form-item label="IP" label-width="100px" prop="ip">
            <el-input type="text" v-model="checkinMechForm.ip"></el-input>
          </el-form-item>

          <el-form-item label="端口号" label-width="100px" prop="port">
            <el-input type="text" v-model="checkinMechForm.port"></el-input>
          </el-form-item>

          <el-form-item label="机器号" label-width="100px" prop="machine_id">
            <el-input type="text" v-model="checkinMechForm.machine_id"></el-input>
          </el-form-item>
          <el-form-item label="排班设置" label-width="100px" prop="config_ids">
            <div
              v-if="workScheduleList.length != 0"
            >
              <!-- style="display:flex;flex-wrap: wrap;justify-content: space-between;" -->
              <!-- <el-input readonly :value="item.name+'  '+item.config.send_time.starttime+'-'+item.config.send_time.endtime" v-for="item of workScheduleList" :key="item.id" style="flex: 0 0 48%;margin-bottom:8px;" type="text" v-model="checkin_dingtalk_appkey"> -->
              <!-- {{item.name+'  '+item.config.send_time.starttime+'-'+item.config.send_time.endtime}} -->
              <!-- </el-input> -->
              <el-card
                style="flex: 0 0 48%;margin-bottom:8px;padding: 0 8px;"
                v-for="item of workScheduleList"
                :key="item.id"
                shadow="never"
                :body-style="{ padding: '0px' }"
              >
                <span>{{item.name}}</span>
                <el-button @click="eidtWorkScheduleShow(item.id)" style="float:right;margin-left: 10px;" type="text" class="button">编辑</el-button>
                <el-button @click="delWorkScheduleItem(item.id)" style="float:right;" type="text" class="button">删除</el-button>
                <span style="float:right;" >{{item.config.send_time.starttime+'-'+item.config.send_time.endtime}}</span>
              </el-card>
            </div>
            <el-button type="primary" @click="work_schedule_add = true" plain>增加排班</el-button>
          </el-form-item>

          <!-- <el-form-item label label-width="100px" prop="checkin_dingtalk_appkey">
            <el-button type="primary" @click="work_schedule_add = true" plain>增加排班</el-button>
            <el-button type="primary" plain>选择已有排班设置</el-button>
          </el-form-item> -->
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="checkin_mech_add = false">取 消</el-button>
        <el-button type="primary" @click="checkinMechSave">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog
      class="dialog_box"
      title="创建排班信息"
      :visible.sync="work_schedule_add"
      top="50px"
      width="1000px"
      :close-on-click-modal="false"
      @close="workScheduleCloseHandle"
    >
      <el-steps :active="activeIndex" finish-status="success" simple style="margin:10px 22px">
        <el-step title="设置排班时间"></el-step>
        <el-step title="创建排班信息"></el-step>
        <el-step title="提交保存"></el-step>
      </el-steps>
      <el-row :gutter="15" style="padding:0px 30px;" v-show="activeIndex == 0">
        <p style="display: flex;justify-content: center;align-items: center;">
          <span style="margin-right:25px;">周一</span>
          <el-time-picker
            style="margin-right:10px;"
            format='HH:mm'
            value-format="HH:mm"
            arrow-control
            v-model="workScheduleForm.job_time[0].starttime"
            placeholder="起始时间点"
          ></el-time-picker>
          <el-time-picker v-model="workScheduleForm.job_time[0].endtime" arrow-control format='HH:mm' value-format="HH:mm" placeholder="结束时间点"></el-time-picker>
        </p>
        <p style="display: flex;justify-content: center;align-items: center;">
          <span style="margin-right:25px;">周二</span>
          <el-time-picker
            style="margin-right:10px;"
            format='HH:mm'
            value-format="HH:mm"
            arrow-control
            v-model="workScheduleForm.job_time[1].starttime"
            placeholder="起始时间点"
          ></el-time-picker>
          <el-time-picker v-model="workScheduleForm.job_time[1].endtime" arrow-control format='HH:mm' value-format="HH:mm" placeholder="结束时间点"></el-time-picker>
        </p>
        <p style="display: flex;justify-content: center;align-items: center;">
          <span style="margin-right:25px;">周三</span>
          <el-time-picker
            style="margin-right:10px;"
            format='HH:mm'
            value-format="HH:mm"
            arrow-control
            v-model="workScheduleForm.job_time[2].starttime"
            placeholder="起始时间点"
          ></el-time-picker>
          <el-time-picker v-model="workScheduleForm.job_time[2].endtime" arrow-control format='HH:mm' value-format="HH:mm" placeholder="结束时间点"></el-time-picker>
        </p>
        <p style="display: flex;justify-content: center;align-items: center;">
          <span style="margin-right:25px;">周四</span>
          <el-time-picker
            style="margin-right:10px;"
            format='HH:mm'
            value-format="HH:mm"
            arrow-control
            v-model="workScheduleForm.job_time[3].starttime"
            placeholder="起始时间点"
          ></el-time-picker>
          <el-time-picker v-model="workScheduleForm.job_time[3].endtime" arrow-control format='HH:mm' value-format="HH:mm" placeholder="结束时间点"></el-time-picker>
        </p>
        <p style="display: flex;justify-content: center;align-items: center;">
          <span style="margin-right:25px;">周五</span>
          <el-time-picker
            style="margin-right:10px;"
            format='HH:mm'
            value-format="HH:mm"
            arrow-control
            v-model="workScheduleForm.job_time[4].starttime"
            placeholder="起始时间点"
          ></el-time-picker>
          <el-time-picker v-model="workScheduleForm.job_time[4].endtime" arrow-control format='HH:mm' value-format="HH:mm" placeholder="结束时间点"></el-time-picker>
        </p>
        <p style="display: flex;justify-content: center;align-items: center;">
          <span style="margin-right:25px;">周六</span>
          <el-time-picker
            style="margin-right:10px;"
            format='HH:mm'
            value-format="HH:mm"
            arrow-control
            v-model="workScheduleForm.job_time[5].starttime"
            placeholder="起始时间点"
          ></el-time-picker>
          <el-time-picker v-model="workScheduleForm.job_time[5].endtime" arrow-control format='HH:mm' value-format="HH:mm" placeholder="结束时间点"></el-time-picker>
        </p>
        <p style="display: flex;justify-content: center;align-items: center;">
          <span style="margin-right:25px;">周日</span>
          <el-time-picker
            style="margin-right:10px;"
            format='HH:mm'
            value-format="HH:mm"
            arrow-control
            v-model="workScheduleForm.job_time[6].starttime"
            placeholder="起始时间点"
          ></el-time-picker>
          <el-time-picker v-model="workScheduleForm.job_time[6].endtime" arrow-control format='HH:mm' value-format="HH:mm" placeholder="结束时间点"></el-time-picker>
        </p>
      </el-row>
      <el-row :gutter="15" style="padding:0px 30px;" v-show="activeIndex == 1">
        <el-form
          :model="workScheduleForm"
          ref="workScheduleForm"
          :rules="workScheduleFormRules"
          @submit.native.prevent
        >
          <div class style="padding:50px 293px 0 293px;">
            <el-form-item label="名称" label-width="110px" prop="name">
              <el-input type="text" v-model="workScheduleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="上班打卡时间" label-width="110px" prop="starttime">
              <el-time-picker v-model="workScheduleForm.starttime" arrow-control format='HH:mm' value-format="HH:mm" placeholder="起始时间点"></el-time-picker>
            </el-form-item>
            <el-form-item label="下班打卡时间" label-width="110px" prop="endtime">
              <el-time-picker v-model="workScheduleForm.endtime" arrow-control format='HH:mm' value-format="HH:mm" placeholder="结束时间点"></el-time-picker>
            </el-form-item>
          </div>
        </el-form>
      </el-row>
      <el-row :gutter="15" style="padding:0px 30px;" v-show="activeIndex == 2">
        <EmployeeSelector ref="EmployeeSelectorComponent" @check="set_target_ids" :employeeSelectorIds="employeeSelectorIds"></EmployeeSelector>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelHandle">取 消</el-button>
        <el-button @click="activeIndexPrev" v-show="activeIndex > 0">上一步</el-button>
        <el-button @click="activeIndexNext" type="primary" v-show="activeIndex < 2">下一步</el-button>
        <el-button type="primary" @click="workScheduleSave" v-show="activeIndex == 2">保 存</el-button>
      </span>
    </el-dialog>


    <!-- <el-dialog
      title="下载"
      :visible.sync="dialogVisible"
      width="30%"
      >
      <span>是否下载Excel</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="Sure()">确 定</el-button>
      </span>
    </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 'vue-photo-preview/dist/skin.css'
  import clip from '@/utils/clipboard' // use clipboard directly
  Vue.use(preview, {
    tapToClose: false
  })
  export default {
    components: {
      EmployeeSelector
    },
    watch: {
      checkin_type(val, old) {
        console.log(val)
      },
      department_id(val, old) {
        // this.loadWidgetData()
      },
    },
    data() {
      // let validateTimeS = (rule, value, callback)=>{
      //   let validValue = value
      //   console.log('value-----data------?//')
      //   console.log(value)
      //    if (!validValue) {
      //     return callback(new Error(" 请选择上班时间"));
      //   }
      // }
      return {
//1迟到，2早退，3当天第一个上班，4当天第二个上班，5当天第三个上班，6准时打卡，7晚下班第一名，8晚下班第二名，9晚下班第三名,10无故缺勤
        point_type_list:{
          '1':'迟到',
          '2':'早退',
          '3':'上班第一名',
          '4':'上班第二名',
          '5':'上班第三名',
          '6':'准时上班',
          '7':'最后下班',
          '8':'晚下班第二名',
          '9':'晚下班第三名',
          '10':'无故缺勤',
          '11': '打卡加班（不需要审批）'
        },
        dialogVisible: false,
        loadurl:'',
        department_id:[],
        file_url:'',
        target_id_set:[],
        create_file_loading:false,
        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,
        export: 0,
        Xtoken: { 'X-Token': getToken() },
        files: [],

        setting_show: false,
        profile: this.$store.getters.user_info,
        filter: {
          status: [],
          keywords: '',
          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: [],
        // 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()])
              }
            }
          ]
        }
      }
    },
    methods: {
      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').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{

          }
        })
      },


      get_file_info(){
        let self = this
        this.$jtoken.get('/integral.php/attendance_excel/get_file_info.html').then((res) => {
          if(res.status == 200){
            if(res.data.code == 1){
              if(res.data.data.status == 1){
                self.create_file_text = '下载报表'
                self.file_url = res.data.data.url
              }else{
                self.create_file_text = '正在生成报表'
                self.file_url = ''
              }

              //self.$message.success(res.data.msg)
            }else{
              self.create_file_text = '导出考勤数据'
              self.file_url = ''
              //self.$message.error(res.data.msg)
            }
            //clearInterval(self.get_file_info_timer)
            self.get_file_info_timer = setTimeout(function () {
              self.get_file_info()
            },5000)
          }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) {
            // console.log('res.data--------??')
            // console.log(res.data)
            // console.log(res.data.data)
            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 {
            console.log('error')
            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)
        }
        // console.log('self.workScheduleForm.employee_ids----------')
        // console.log(self.workScheduleForm.employee_ids)
        // self.target_list = data
      },
      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) {
        window.open(url)
      },
      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) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(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) {
          // console.log(
          //   'https://view.officeapps.live.com/op/view.aspx?src=' +
          //     this.serverdomain +
          //     file.url
          // )
          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) {
          // console.log(this.serverdomain + file.response.url)
          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) {
                console.log(ii)
                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() {},

      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: '出勤'}]
          })
      },
      // load_attendance_setting_info() {
      //   const self = this
      //   this.$jtoken.get('/integral.php/attendance/get_corpsecret').then(ret => {
      //     console.log(ret.data)
      //     self.checkin_dingtalk_appkey = ret.data.data.checkin_dingtalk_appkey
      //     self.checkin_dingtalk_secret = ret.data.data.checkin_dingtalk_secret
      //     self.checkin_wexin_secret = ret.data.data.checkin_wexin_secret
      //     self.checkin_type = ret.data.data.checkin_type
      //   })
      // },
      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'
          console.log('更换更新接口')
          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'
          console.log('更换增加数据接口')
        }
        this.$nextTick(() => {
          const form = this.$refs['newTaskForm']
          console.log(form)
          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 => {
            console.log(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
        console.log(this.taskForm)
        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) {
                console.log(error)
              })
          } else {
            return false
          }
        })
      },
      onFilterChanged: function() {
        this.$refs.dept1.dropDownVisible = false;
        this.currentPage = 1
        this.exporExcel()
        this.loadTaskList()
      },

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


      dateTimeFormatterTime: function(row, column, cellValue) {
        return cellValue
          ? this.$moment(cellValue * 1000).format('HH:mm:ss')
          : ''
      },
      dateTimeFormatter1: function(row, column, cellValue) {
        return cellValue
          ? this.$moment(cellValue * 1000).format('YYYY-MM-DD')
          : ''
      },


      formatTime(row, colum, cellValue) {
        return cellValue ? (cellValue / 3600).toFixed(2) + '' : '无'
      },
      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
      },



      openDalod() {
        window.open(this.loadurl,'_blank')
        this.dialogVisible = false;
      },
      handleSizeChange(val) {
        this.pageLimit = val
        console.log( this.pageLimit )
        this.loadTaskList()
      },
      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: []
        }
      },

      exporExcelJump() {
        window.open(this.loadurl, '_blank')
      },
      // 导出excel
      exporExcel() {
        this.export = 1;
        var self = this
        let time_range = JSON.parse(JSON.stringify(self.filter.time_range))
        if (time_range == null) {
          time_range = []
        }
        console.log(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
        }
        console.log(time_range)
        var params = {
          site_id: this.profile.site_id,
          time_range: time_range,
          page: this.currentPage,
          page_size: this.pageLimit,

        }

        params['time_range'] = time_range;
        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['export'] = 1;
        this.$jtoken
          .get(this.serveAd + '/ad/attendance_data/get_code', {
            params: params
          })
          .then(function(response) {
            if (response.data.code == 1) {
              self.loadurl =  self.serveAd+'/ad/attendance_data/log_export?code='+response.data.data.code
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },



      loadTaskList: function() {
        this.loading = 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
          //  time_range[1] = (time_range[1] *1/1000) + 1
        }
        var params = {
          site_id: this.profile.site_id,
          time_range: time_range.toString(),
          page: this.currentPage,
          page_size: this.pageLimit,

        }

        // params['time_range'] = time_range;


        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
        }

        this.$jtoken
          .get(this.serveAd + '/ad/attendance_data/attendance_log', {
            params: params
          })
          .then(function(response) {
            if (response.data.code == 1) {
              self.loading = false
              var jsonData = response.data
              try {

                self.tableData = jsonData.data.list
                console.log(jsonData.data.list)
                self.totalCount = jsonData.data.total
                self.export = 0;
              } catch (err) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          }).finally(()=>{
            this.loading = false
          })
      },
      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: []
        }
      },


      // 员工下拉
      // loadWidgetData: function() {
      //   var self = this
      //   this.$http
      //     .get('/integral.php/ajax_request_common/prepare_integral_options', {
      //       params: {
      //         id: this.profile.id,
      //         category_tree: 1,
      //         employee_list: 1,
      //         dept_tree: 1,
      //         dept_id: self.department_id[self.department_id.length - 1]
      //       }
      //     })
      //     .then(function(response) {
      //       if (response.status == 200) {
      //         var jsonData = response.data
      //         try {
      //           self.employeeOptions = jsonData.employee_list
      //           self.dept_tree = jsonData.dept_tree
      //         } catch (err) {
      //           console.log(err)
      //         }
      //       }
      //     })
      //     .catch(function(error) {
      //       console.log(error)
      //     })
      // },


      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) {
            console.log(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) {
            console.log(error)
          })
      },
      // confirmUpdata(){

      //   // console.log('row')
      //   // console.log(row)
      //   // console.log(this.taskForm)
      //   this.$jtoken.post('/integral.php/attendance/update',{})
      // },
      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) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      }
      // 获取规则列表
      // loadRuleList: function () {
      //   var self = this;
      //   self.loading = true
      //   var params = {
      //     site_id: this.profile.site_id,
      //     page: this.currentPage,
      //     interval:this.pageLimit,
      //     keywords:'考勤'
      //   };
      //   for (let item in this.filter) {
      //     let value = this.filter[item];
      //     if (item == "category_id") {
      //       if (!value || value.length == 0) {
      //         continue;
      //       }
      //       params[item] = value[value.length - 1];
      //     } else {
      //       let valueStr = value.toString();
      //       if (valueStr && valueStr.length > 0) {
      //         params[item] = valueStr;
      //       }
      //     }
      //   }
      //   this.$jtoken.get('/integral.php/ajax_request_common/get_integral_rules', {
      //     params: params
      //   }).then(function (response) {
      //     if (response.status == 200) {
      //       self.loading = false
      //       var jsonData = response.data;
      //       try {
      //         // self.status_list= jsonData.filter_list.category;
      //         // self.totalCount = jsonData.total_count;
      //         self.type_list = jsonData.list_data;
      //       } catch (err) {
      //         console.log(err);
      //       }
      //     }
      //   }).catch(function (error) {
      //     console.log(error);
      //   });
      // },
    },
    mounted(){
      this.loadTaskList()
      this.exporExcel()
      // 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();
      }
    },
    created() {
      this.employeeOptions = JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP'))
      this.dept_tree = JSON.parse(localStorage.getItem('dept_tree'))
    }
  }
</script>
<style scoped>
  .el-pagination {
    text-align: center;
    margin-top: 15px;
  }
  .attendance-manage .el-tag+.el-tag {
    margin-left: 10px;
  }
  .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>
