<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:220px;">
      <el-input
        placeholder="输入关键词查找"
        ref="search-bar"
        v-model="filter.keywords"
        class="input-with-select"
        @keyup.enter.native="onFilterChanged"
      >
        <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
      </el-input>
    </div>

    </div>
    
        <!-- <el-table
          ref="multipleTable"
          max-height="410"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="thePerformanceLoad"
          @select-all="handleSelectionSelect"
          @cell-click="handleSelectionClick"
        > -->
    <el-table
      @row-click="rowClick"
      max-height="520"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      :border="false"
      tooltip-effect="dark"
      style="width: 100%;"
    >
      <el-table-column
        type="selection"
        width="42"

      ></el-table-column>

      <el-table-column prop="name" label="名称" :filterMultiple="false"></el-table-column>


      <el-table-column label="规则">
        <template slot-scope="scope">

          <div>每天打卡次数：{{scope.row.config.split(',').length*2}}次</div>
          <div style="border:none; display: table;">

                <div style="vertical-align: top; display: table-cell;">
                <div v-for="item in scope.row.config.split(',')">
                   <div style="vertical-align: top; display: table-cell;">{{item.split('-')[0]}}-{{item.split('-')[3]}}打卡时段</div>
                  <div>{{item.split('-')[0]}}最早打卡时间 {{item.split('-')[3]}} 最晚打卡时间  </div>


                   <div>{{item.split('-')[1]}} 上班打卡时间 {{item.split('-')[2]}}下班打卡时间</div>
                 </div>
                 </div>

          </div>
          <div v-if="scope.row.config.length == 1">休息时间：{{scope.row.break_time}}</div>
        </template>
      </el-table-column>



    </el-table>
    <el-pagination
    style="margin-top:15px;"
      background
      layout="total,sizes, prev, pager, next"
      :page-size="pageLimit"
      :page-sizes="[10, 20, 50, 100]"
      :total="totalCount"
      @size-change="handleSizeChange"
      :current-page.sync="currentPage"
      @current-change="changePage"
    ></el-pagination>
  </div>
</template>
<script>
  import qs from 'qs'
  export default {
    props: {
      select_ids: {
        type: Array,
        default: () => {return []}
      },
      select_list: {
        type: Array,
        default: () => {return []}
      },
      selected: {
        type: Array,
        default: () => {return []}
      },
    },
    watch:{
      time_list(n,o){
        console.log(n)
      }
    },
    data() {
      const validateName = (rule, value, callback) => {
        var validValue = value
          ? value.replace(/\s/g, '').replace(/&nbsp;/gi, '')
          : value
        if (!validValue) {
          return callback(new Error('请填写积分分类名称'))
        } else {
          callback()
        }
      }
      return {
        save_loading:false,
        dialog_title:"创建班次",
        pageSize: 10,
        formdata:{
          name: '',
          time_list:[
            {id:0,checkin_time:'8:00', start_time:'8:30',end_time:'18:00'},
          ],
          break_time:['12:00', '13:00'],
          is_break_time:false,
          is_card:false,
          allowed_late_time:30,
          serious_late_time:30,
          absenteeism_late_time:30,
        },
        multipleSelection: [],
        RuleDetailDialogVisible: false,
        pageLimit: 10,

        profile: this.$store.getters.user_info,
        filter: {
          status: 1,
          keywords: '',
        },
        form_api:'/integral.php/attendance_group/create_schedule',
        loading: false,
        totalCount: 0,
        currentPage: 1,
        tableData: null,
        rules: {
          name: [{ validator: validateName, trigger: 'blur' }]
        }

      }
    },
    methods: {
      rowClick(row, event, column) {
        this.$refs['multipleTable'].toggleRowSelection(row)
      },
      rowIndexName({row, rowIndex}) {
        row.id = '第'+(rowIndex+1)+'次'
      },
      add_time_list(){
        if(this.formdata.time_list.length == 3){
          this.$message.error('最多只能添加3个时段')
          return false
        }
        this.formdata.time_list.push({id:0,checkin_time:'00:00', start_time:'8:30',end_time:'18:00'})
      },
      delete_time_list(id){
        if(this.formdata.time_list.length == 1){
          this.$message.error('不能删除，最少需要一个时段')
          return false
        }
        this.formdata.time_list.splice(id,1)
      },
      handleSelectionChange: function(val) {
        this.$emit("update:select_list", val)
        //console.log(val)
        this.multipleSelection = val
      },

      confirmMultipleDelete() {
        if (this.multipleSelection.length < 1) {
          return false
        }
        this.$confirm('确定要删除选中的考勤组吗?', '批量删除考勤组', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            const targetArr = []
            for (const index in this.multipleSelection) {
              targetArr.push(this.multipleSelection[index].id)
            }
            const targetIds = targetArr.join(',')
            this.deleteRule(targetIds, true)
          })
          .catch(() => {
            // console.log('已取消删除');
          })
      },


      handleSizeChange(val) {
        this.pageLimit = val
        this.onFilterChanged()
      },

      formReset() {
        const _this = this


      },

      onFilterChanged: function() {
        this.currentPage = 1
        this.loadRuleList()
      },


      //
      loadRuleList: function() {
        var self = this
        self.loading = true
        var params = {
          site_id: this.profile.site_id,
          page: this.currentPage,
          page_size: this.pageLimit,
          keyword: self.filter.keywords
        }

        this.$jtoken
          .get(this.serveAd +'/ad/schedule', {
            params: 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.list
              } catch (err) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      changePage: function(current) {
        if (isNaN(current) || current < 1) {
          return false
        }
        this.loadRuleList()
      },
      saveFormData: function() {
        this.save_loading = true
        var self = this
        let send_data = JSON.parse(JSON.stringify(this.formdata))

        /*name: '',
          time_list:[
          {id:0,checkin_time:'8:00', start_time:'8:30',end_time:'18:00'},
        ],
          break_time:['12:00', '13:00'],
          is_break_time:false,
          is_card:false,
          allowed_late:30,
          serious_late_time:30,
          absenteeism_late_time:30,*/
        let time_list = []
        for(let t in send_data.time_list){
          time_list.push(send_data.time_list[t].checkin_time+'-'+send_data.time_list[t].start_time+'-'+send_data.time_list[t].end_time)
        }
        send_data.time_list = time_list
        send_data.break_time = send_data.break_time.join('-')
        send_data.is_break_time = send_data.is_break_time ? 1:0
        send_data.is_card = send_data.is_card ? 1:0


        this.$jtoken({
          url: this.form_api,
          method: 'post',
          data: qs.stringify(send_data),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
          .then(function(response) {
            self.save_loading = false
            if(response.status == 200){
              console.log(response.data)
              if(response.data.code == 1){
                self.RuleDetailDialogVisible = false
                self.onFilterChanged()
                self.$message.success(response.data.msg)
              }else{
                self.$message.error(response.data.msg)
              }

            }else{
              self.$message.error('网络错误')
            }
          })
          .catch(function(error) {
            self.$message.error('网络错误')
          })
      },

      confirmDelete: function(ruleId) {
        this.$confirm(
          '确定要删除此考勤组吗？',
          '删除积分规则',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(() => {
            this.deleteRule(ruleId)
          })
          .catch(() => {
            // console.log('已取消删除');
          })
      },
      deleteRule: function(ruleId) {
        if (!ruleId) {
          return false
        }
        const params = {
          id: ruleId
        }
        var self = this
        this.$jtoken
          .get('/integral.php/attendance_group/delete_schedule', {
            params: params
          })
          .then(function(response) {

            if (response.status == 200 && response.data.code == 1) {
              self.$message.success(response.data.msg)
              self.loadRuleList()
            } else {
              self.$message.error('网络错误')
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },

      toDetailPage: function(id, event) {
        const self = this

        self.formdata = {
          name: '',
          time_list:[
            {id:0,checkin_time:'8:00', start_time:'8:30',end_time:'18:00'},
          ],
          break_time:['12:00', '13:00'],
          is_break_time:false,
          is_card:false,
          allowed_late_time:30,
          serious_late_time:30,
          absenteeism_late_time:30,
        }




        if(id > 0){
          this.form_api = '/integral.php/attendance_group/update_schedule'
          this.dialog_title = '修改班次'
          //获取一条记录，用于复原修改界面
          this.$jtoken
            .get('/integral.php/attendance_group/get_schedule_list', {
              params: {id:id}
            }).then((res) => {
            if(res.status == 200){
              self.formdata.name = res.data.data.name
              let time_list = []
              for(let t in res.data.data.config){
                time_list.push({checkin_time: res.data.data.config[t].split('-')[0],start_time: res.data.data.config[t].split('-')[1],end_time: res.data.data.config[t].split('-')[2]})
              }
              self.formdata.time_list = time_list
              //console.log(res.data.data.break_time)
              self.formdata.break_time = res.data.data.break_time.split('-')
              self.formdata.id = res.data.data.id
              self.formdata.is_break_time = res.data.data.is_break_time == 1
              self.formdata.is_card = res.data.data.is_card == 1
              self.formdata.allowed_late_time = res.data.data.allowed_late_time
              self.formdata.serious_late_time = res.data.data.serious_late_time
              self.formdata.absenteeism_late_time = res.data.data.absenteeism_late_time

              self.RuleDetailDialogVisible = true
            }else{
              self.$message.error('网络错误')
            }
          })
        }else{
          this.RuleDetailDialogVisible = true
          this.form_api = '/integral.php/attendance_group/create_schedule'
          this.dialog_title = '创建班次'
        }

      },

    },
    created() {
      console.log(this.selected)
      this.loadRuleList()
    }
  }
</script>
<style  lang="scss" scoped="scoped">
  /deep/ .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  /deep/ .el-table__body-wrapper::-webkit-scrollbar-track {
    width: 6px;
    background-color: #fff0;
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius: 2em;
  }
  /*滚动条的设置*/
  /deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #fff0;
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius: 2em;
  }
  /*滚动条移上去的背景*/
  /deep/ .el-table__body-wrapper:hover::-webkit-scrollbar-thumb {
    background-color: rgba(144, 147, 153, 0.3);
  }
  
  .date_tag .el-tag + .el-tag {
    margin: 5px;
  }

  .attendance_group .el-card__body {
    padding: 15px;
  }
  .attendance_group .el-tag + .el-tag {
    margin-left: 10px;
  }
  .attendance_group .el-tag + .el-button {
    margin-left: 10px;
  }

  .setMapBaidu .map {
    width: 100%;
    height: 300px;
  }
</style>
