<template>
  <div style=" background-color: #fff; padding:15px;">
    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">



      <div class="gap-right-8" style="display:inline-block; width:310px;">
        <el-input
          placeholder="输入关键词查找"
          ref="search-bar"
          v-model="filter.keywords"
          class="input-with-select"
          width="200px"
          @keyup.enter.native="onFilterChanged"
        >
          <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
        </el-input>
      </div>

      <el-button
        type="primary"
        plain
        @click="checkInMechShow"
        class="first-element-btn"
      >创建考勤机</el-button>


      <el-button
        v-if="profile.is_creator==1 && false"
        type="primary"
        plain
        @click="setCheckInType"
        class="first-element-btn"
      >设置打卡方式</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="name" label="名称"></el-table-column>
      <el-table-column prop="ip" label="IP"></el-table-column>
      <el-table-column prop="port" label="端口号"></el-table-column>
      <el-table-column prop="sn" label="序列号"></el-table-column>


      <el-table-column label="操作">
        <template slot-scope="scope">
          <div>
            <el-button
              type="text"
              @click="confirmDelete(scope.row.id)"
              v-show="profile.is_creator || profile.id==scope.row.creator_id"
            >删除</el-button>
            <el-button
              type="text"
              @click="checkinMechShow(scope.row)"
              v-show="profile.is_creator || profile.id==scope.row.creator_id"
            >修改</el-button>

            <el-button
              type="text"
              @click="checkinEmployeeShow(scope.row)"
              v-show="profile.is_creator || profile.id==scope.row.creator_id"
            >员工设置</el-button>



          </div>
        </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="checkinMechForm.id?'修改考勤机':'增加考勤机'"
      :visible.sync="checkin_mech_add"
      width="730px"
      top="50px"

      @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="sn">
            <el-input type="text" v-model="checkinMechForm.sn"></el-input>
          </el-form-item>

          <el-form-item label="关联考勤组" label-width="100px" prop="config_ids">
            <el-select v-model="checkinMechForm.group_id">
              <el-option v-for="(item,index) in group_list" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </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
      title="员工设置"
      :visible.sync="setEmployeeShow"
      width="400px"
      top="50px"
      :close-on-click-modal="false"
    >
      <el-input
        placeholder="输入关键词查找"
        ref="search-bar"
        v-model="employee_name_set"
        class="input-with-select"
        width="200px"
        @keyup.enter.native="loadEmployee"
      >
        <el-button slot="append" icon="el-icon-search" @click="loadEmployee"></el-button>
      </el-input>
      <el-scrollbar
        wrap-class="column-wrapper scrollable-items-container check-item-box dept_tree"
        :native="false"
        style="height: 400px;"
      >

      <el-table
        stripe
        ref="multipleTable"
        :data="employee_name_set_list"


        style="width: 100%"
      >



        <el-table-column prop="name" label="姓名"></el-table-column>

        <el-table-column prop="" label="员工ID（考勤机）">
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.user_id"></el-input>
          </template>
        </el-table-column>





      </el-table>
</el-scrollbar>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setEmployeeShow = false">关 闭</el-button>

        <el-button type="primary" @click="dialogEmployeeSetSend" :loading="save_employee_set_loading">保 存</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"
            label="API密码"
            label-width="100px"
            prop="checkin_dingtalk_appkey"
            style="margin-bottom: 5px;"
          >
            <el-input type="text" readonly v-model="checkin_sys_secret"></el-input>
            <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>


  </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)
      }
    },
    data() {
      // let validateTimeS = (rule, value, callback)=>{
      //   let validValue = value
      //   console.log('value-----data------?//')
      //   console.log(value)
      //    if (!validValue) {
      //     return callback(new Error(" 请选择上班时间"));
      //   }
      // }
      return {
        save_employee_set_loading:false,

        checkinSettingForm: {
          checkinMech: []
        },
        checkinSettingFormRules: {
          checkinMech: [{ required: true, message: '请输入考勤机名称', trigger: 'change' }]
        },
        employeeSelectorIds: [],
        workScheduleApi: '/integral.php/attendance/setting_add',
        checkinMechApi: '/integral.php/attendance/set_attendance_config',
        checkinMechForm: {
          name: '',
          ip: '',
          port: '',
          machine_id: '',
          group_id: '',
          sn: ''
        },
        checkinMechFormRules: {
          name: [{ required: true, message: '请输入考勤机名称', trigger: 'blur' }],
          ip: [{ required: true, message: '请输入考勤机连接ip', trigger: 'blur' }],
          machine_id: [{ required: true, message: '请输入考勤机机器号', trigger: 'blur' }],
          sn: [{ required: true, message: '请输入考勤机序列号', trigger: 'blur' }],
          group_id: [{ required: true, message: '请选择关联的考勤组', trigger: 'change' }]
        },
        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,
        setpIndex: 0,
        Xtoken: { 'X-Token': getToken() },
        files: [],

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

        setEmployeeShow: false,
        employee_name_set: '',
        employee_name_set_list: '',
        machine_set_id: 0,
        edit_row: null,
      }
    },
    methods: {
      loadEmployee(){
        let self = this
        this.$http('get','/integral.php/attendance/get_machine_employee',{
            mid: self.edit_row.id,
            keywords: this.employee_name_set
          }).then(res => {
          console.log(res.data)
          for(let i in res.data){
            if(res.data[i].user_id == null){
              res.data[i].user_id = res.data[i].employee_id
            }
          }
          self.employee_name_set_list = res.data

        })
      },
      checkinEmployeeShow(row){
        this.edit_row = row
        this.loadEmployee()
        this.machine_set_id = row.id
        this.setEmployeeShow = true
      },





      checkinMechCloseHandle() {
        this.checkinMechApi = '/integral.php/attendance/set_attendance_config' // 默认添加考勤机
        this.$refs.checkinMechForm.resetFields()
        this.checkinMechForm = {
          name: '',
          ip: '',
          port: '',
          machine_id: '',
          config_ids: [],
          group_id: '',
          sn: ''
        }
        this.get_group_list()
        return true
      },
      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.$http('get','/integral.php/attendance/get_attendance_machine_setting',{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
          }
        })
      },
      get_group_list() {
        this.$http('get','/integral.php/attendance_group/get_attendance_group',{interval: 1000}).then(res => {
          if (res.status == 200) {
            this.group_list = res.data.data.list
          }
        })
      },
      delWorkScheduleById(id) {
        this.$http('get','/integral.php/attendance/delete_attendance_config',{id}).then(res => {
          if (res.status == 200) {
            this.$message({
              message: res.data.message,
              type: 'success'
            })
            this.getAttendanceMech()
          }
        })
      },
      checkinMechShow(item) {
        this.checkinMechApi = '/integral.php/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.checkinMechForm.group_id = item.group_id
        this.checkinMechForm.sn = item.sn
        this.get_group_list()
        this.getWorkScheduleById(item.id)
      },
      checkinMechSave() {


        this.checkinMechForm.kq_site_id = this.profile.company_info.id
        this.$refs['checkinMechForm'].validate((valid) => {
          if (valid) {
            this.$http('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.loadTaskList()
                //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.$http('get','/integral.php/attendance/get_setting_by_id',{ 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.$http('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()
        this.get_group_list()
      },
      getWorkScheduleList() {
        this.$http('get','/integral.php/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, 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) {
          console.log(
            'https://view.officeapps.live.com/op/view.aspx?src=' +
            this.serverdomain +
            url
          )
          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) {
          console.log(this.serverdomain + url)

          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) {
                console.log(ii)
                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.$http('get','/integral.php/ajax_request_common/load_target_range',{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() {},
      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.$http('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.$http('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.$http('get','/integral.php/attendance/get_info',{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)
          })
      },

      dialogEmployeeSetSend(){
        const self = this
        self.save_employee_set_loading = true
        this.$http('post','/integral.php/attendance/save_machine_employee',qs.stringify({mid:self.machine_set_id, data: JSON.stringify(self.employee_name_set_list)}),
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded'
          // }
        )
          .then(function(res) {
            if(res.data.code == 1){
              //self.setEmployeeShow = false
              self.$message.success(res.data.msg)
            }else{
              self.$message.error(res.data.msg)
            }
            self.save_employee_set_loading = false
          })
          .catch(function(err) {
            self.$message.error(res.data.err)
            self.save_employee_set_loading = false
          })
      },
      dialogSettingSend() {

        const self = this
        this.$http('post','/integral.php/attendance/save_corpsecret',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
            }
          }),
          // 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.$http('get','/integral.php/attendance/attendance_config_auth_select',{kq_site_id: this.profile.company_info.id})
          .then(res => {
            if (res.status == 200) {
              this.checkin_sys_secret = res.data.data.auth
            }
          })
      },

      getAttendanceAuthAgain() {
        this.$http('get','/integral.php/attendance/attendance_config_auth',{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.$http('get','/integral.php/attendance/select_attendance_config',{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.$http('post',self.taskFormApi,qs.stringify({ row: this.taskForm }),
              // 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.currentPage = 1
        this.loadTaskList()
      },
      dateTimeFormatter: function(row, column, cellValue) {
        return cellValue
          ? this.$moment(cellValue * 1000).format('MM-DD HH:mm')
          : ''
      },
      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
      },
      loadTaskList: function() {
        this.loading = true
        var self = this
        var params = {
          site_id: this.profile.site_id,
          keywords: this.keywords,
          page: this.currentPage,
          offset:
          (this.currentPage == 1 ? 0 : this.currentPage - 1) * this.pageLimit,
          limit: this.pageLimit
        }
        for (const item in this.filter) {
          const value = this.filter[item]
          if (item == 'status') {
            if (!value || value.length == 0) {
              continue
            }
            params[item] = value
          } else {
            if (value != null) {
              const valueStr = value.toString()
              if (valueStr && valueStr.length > 0) {
                params[item] = valueStr
              }
            }
          }
        }
        console.log(params)
        this.$http('get','/integral.php/attendance/select_attendance_config', params)
          .then(function(response) {
            if (response.status == 200) {
              self.loading = false
              var jsonData = response.data
              try {
                self.totalCount = jsonData.data.total
                self.tableData = jsonData.data
              } catch (err) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(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: []
        }
      },
      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.$http('get','/integral.php/attendance/get_attendance',params,'','',
         {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.message

              if (data.status == 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.$http('post','/integral.php/attendance/delete_attendance_config',params,'','',
          {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.message

              if (data.status == 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.$http.post('/integral.php/attendance/update',{})
      // },
      loadRuleDetail: function(ruleId) {
        const params = {
          id: ruleId
        }
        var self = this
        this.$http('get','/integral.php/ajax_request_common/get_rule_info',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.$http.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);
      //   });
      // },
    },
    created() {
      this.loadTaskList()
      this.load_attendance_setting_info()
      this.loadTargetRange()
      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();
      }
    }
  }
</script>
<style>
  .el-pagination {
    text-align: center;
    margin-top: 15px;
  }

  .dialog_box .el-dialog__header {
    display: none;
  }
</style>
