<template>
  <div style=" background-color: #fff; padding:15px; min-height: calc(100vh - 160px);">
    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
      <el-button class="first-element-btn" v-if="profile.manager_type > 1" :disabled="multipleSelection.length < 1"
        @click="confirmMultipleDelete" type="primary" plain>批量删除</el-button>
      <el-button @click="toDetailPage(0, $event)" type="primary" style="margin-right:10px;">创建班次</el-button>
      <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 @selection-change="handleSelectionChange" v-loading="loading" ref="multipleTable" :data="tableData"
      :border="false" header-row-class-name="newClass" tooltip-effect="dark" style="width: 100%">
      <el-table-column type="selection" width="42" v-if="profile.manager_type > 1"></el-table-column>
      <el-table-column label="名称" :filterMultiple="false">
        <template slot-scope="scope">
          <div style="font-size: 15px;font-weight: bolder;">
            {{scope.row.name}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="规则">
        <template slot-scope="scope">
          <div style="font-size: 15px;font-weight: bolder;">每天打卡次数：<span style="color:#409eff">{{scope.row.config.split(',').length*2}}</span> 次</div>
          <div style="border:none; display: table;">
            <div style="vertical-align: top; display: table-cell;">
              <div v-for="(item,index) in scope.row.config.split(',')" :key="index" style="margin:8px 0;">
                <div style="vertical-align: top; display: table-cell;font-size: 15px;font-weight: bolder;">
                 
                  打卡时段：<span style="color:#409eff">{{item.split('-')[0]}}-{{item.split('-')[3]}}</span> </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.is_break_time > 0">休息时间：{{scope.row.break_time}}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <el-button type="text" @click="toDetailPage(scope.row.id, $event)">修改</el-button>
          <el-button style="color:#f56c6c !important;" type="text" @click="confirmDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <center style="margin: 20px 0">
      <el-pagination background layout="total,sizes, prev, pager, next" :page-size="pageLimit" :total="totalCount" :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange" :current-page.sync="currentPage" @current-change="changePage"></el-pagination>
    </center>


    <el-dialog class="attendance_group" :title="dialog_title" @close="formReset" :visible.sync="RuleDetailDialogVisible"
      width="800px" top="50px">
      <el-scrollbar wrap-class="column-wrapper scrollable-items-container check-item-box dept_tree" :native="false"
        style="height: 500px;margin:30px 0 20px;">
        <div style="padding:0;">
          <el-form ref="formdata" :model="formdata" :rules="formdata_rules" label-width="140px">
            <el-form-item label="班次名称" prop="name">
              <el-input style="width:350px;" v-model="formdata.name"></el-input>
            </el-form-item>
            <el-form-item label="打卡次序" style="width: 730px!important;" :rules="[{ required: true, message: '请填写打卡次序', trigger: 'blur' }]">
              <el-table border :row-class-name="rowIndexName" :data="formdata.time_list">
                <el-table-column width="70" prop="id" label="次数">
                </el-table-column>
                <el-table-column width="110" prop="checkin_time" label="最早打卡时间">
                  <template slot-scope="scope">
                    <el-time-picker prefix-icon="picker-no-icon" class="picker-no-icon-box" value-format="HH:mm"
                      selectableRange="00:00:00-23:59:59" format="HH:mm" v-model="scope.row.checkin_time"
                      placeholder="选择时间" style="width:100%;">
                    </el-time-picker>
                  </template>
                </el-table-column>
                <el-table-column width="110" prop="start_time" label="上班打卡">
                  <template slot-scope="scope">
                    <el-time-picker prefix-icon="picker-no-icon" class="picker-no-icon-box" value-format="HH:mm"
                      selectableRange="00:00:00-23:59:59" format="HH:mm" v-model="scope.row.start_time"
                      placeholder="选择时间" style="width:100%;">
                    </el-time-picker>
                  </template>
                </el-table-column>
                <el-table-column width="110" prop="end_time" label="下班打卡">
                  <template slot-scope="scope">
                    {{time_list_split[scope.$index]}}
                    <el-time-picker prefix-icon="picker-no-icon"
                      :class="{'picker-no-icon-box': true, 'sec_day': time_list_split[scope.$index] != ''}"
                      value-format="HH:mm" selectableRange="00:00:00-23:59:59" format="HH:mm"
                      v-model="scope.row.end_time" placeholder="选择时间" style="width:80px;">
                    </el-time-picker>
                  </template>
                </el-table-column>
                <el-table-column width="110" prop="dinner_time" label="最晚打卡时间">
                  <template slot-scope="scope">
                    <el-time-picker prefix-icon="picker-no-icon" class="picker-no-icon-box" value-format="HH:mm"
                      selectableRange="00:00:00-23:59:59" format="HH:mm" v-model="scope.row.dinner_time"
                      placeholder="选择时间" style="width:100%;">
                    </el-time-picker>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="78">
                  <template slot-scope="scope">
                    <el-button type="text" @click="delete_time_list(scope.$index)">删除</el-button>
                  </template></el-table-column>
              </el-table>
              <div style="height: 15px;"></div>
              <el-button type="primary" @click="add_time_list">增加时段</el-button>
            </el-form-item>
            <el-form-item label="休息时间" v-if="formdata.time_list.length == 1" style="margin:0 0 10px 0 !important;">
              <el-time-picker :disabled="!formdata.is_break_time" value-format="HH:mm"
                selectableRange="00:00:00-23:59:59" style="width:120px;" format="HH:mm" v-model="formdata.break_time[0]"
                placeholder="选择时间">
              </el-time-picker> {{break_time_split}} <el-time-picker :disabled="!formdata.is_break_time"
                value-format="HH:mm" selectableRange="00:00:00-23:59:59" format="HH:mm" v-model="formdata.break_time[1]"
                style="width:120px;" placeholder="选择时间">
              </el-time-picker>
              　<el-checkbox style="margin-left:15px;" v-model="formdata.is_break_time">启用休息时间</el-checkbox>
            </el-form-item>
            <el-form-item label="" style="margin-top:0;">
              <p style="margin:0 0 0px 0 !important;">合计工作时长{{time_long}}</p>
              <el-checkbox v-model="formdata.is_card">下班不用打卡（下班不打卡也不会记为异常）</el-checkbox>
            </el-form-item>
            <el-form-item label="允许迟到分钟数" prop="allowed_late_time">
              <el-input style="width:100px;" type="number" v-model="formdata.allowed_late_time"></el-input>
            </el-form-item>
            <el-form-item label="严重迟到分钟数" prop="serious_late_time">
              <el-input style="width:100px;" type="number" v-model="formdata.serious_late_time"></el-input>
            </el-form-item>
            <el-form-item label="旷工迟到分钟数" prop="absenteeism_late_time">
              <el-input style="width:100px;" type="number" v-model="formdata.absenteeism_late_time"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RuleDetailDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveFormData('formdata')" :loading="save_loading">保 存</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
  import qs from 'qs'
  import moment from 'moment'
  export default {

    watch: {
      'formdata': {
        handler: function (newval, oldVal) {
          this.get_time_long()
        },
        deep: true
      },
      time_list(n, o) {
        console.log(n)
      },
      'formdata.time_list'(val){
        if(val.length > 1){
          this.formdata.is_break_time = false
        }
      },
    },
    data() {
      return {
        config: [],
        save_loading: false,
        break_time_split: '-',
        time_list_split: ['', '', ''],
        dialog_title: "创建班次",
        // time_list:[
        //     {id:0,checkin_time:'8:00', start_time:'8:30',end_time:'18:00', dinner_time:'18.30'},
        // ],
        formdata: {
          name: '',
          config: '',
          break_time: ['12:00', '13:00'],
          is_break_time: false,
          is_card: false,
          allowed_late_time: 30,
          serious_late_time: 30,
          time_list: [{
            id: 0,
            checkin_time: '8:00',
            start_time: '8:30',
            end_time: '18:00',
            dinner_time: '18: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,
        formdata_rules: {
          name: [{ required: true, message: '请输入班次名称', trigger: 'blur' },{max: 6, message: '不能大于6个字符', trigger: 'blur'}],
          allowed_late_time:[{ required: true, message: '请输入正确的数值', trigger: 'blur' },{pattern: new RegExp(/^[1-9]\d*|0$/, "g"),message: '请输入正整数!',trigger: 'blur' }],
          serious_late_time:[{ required: true, message: '请输入正确的数值', trigger: 'blur' },{pattern: new RegExp(/^[1-9]\d*|0$/, "g"),message: '请输入正整数!',trigger: 'blur' }],
          absenteeism_late_time:[{ required: true, message: '请输入正确的数值', trigger: 'blur' },{pattern: new RegExp(/^[1-9]\d*|0$/, "g"),message: '请输入正整数!',trigger: 'blur' }],
        },
        time_long: "0"
      }
    },
    methods: {
      get_time_long() {


        let ret = 0
        let s = 0
        let e = 0
        let s1 = 0
        let e1 = 0

        for (let i in this.formdata.time_list) {
          s = moment('2019-01-01 ' + this.formdata.time_list[i].start_time + ':00').valueOf() / 1000
          e = moment('2019-01-01 ' + this.formdata.time_list[i].end_time + ':00').valueOf() / 1000
          if (e < s) {
            e = moment('2019-01-02 ' + this.formdata.time_list[i].end_time + ':00').valueOf() / 1000
            this.time_list_split[i] = '次日'
          } else {
            this.time_list_split[i] = ''
          }
          ret = ret + (e - s)
        }
        if (this.formdata.time_list.length == 1 && this.formdata.is_break_time) {
          s1 = moment('2019-01-01 ' + this.formdata.time_list[0].start_time + ':00').valueOf() / 1000
          e1 = moment('2019-01-01 ' + this.formdata.time_list[0].end_time + ':00').valueOf() / 1000
          s = moment('2019-01-01 ' + this.formdata.break_time[0] + ':00').valueOf() / 1000
          e = moment('2019-01-01 ' + this.formdata.break_time[1] + ':00').valueOf() / 1000
          if (s > s1 && e < e1) {

            if (e < s) {
              e = moment('2019-01-02 ' + this.formdata.break_time[1] + ':00').valueOf() / 1000
              this.break_time_split = '- 次日'
            } else {
              this.break_time_split = '-'
            }
            ret = ret - (e - s)
          }


        }

        let h = Math.floor(Math.floor(ret / 60) / 60)
        let m = Math.floor((ret / 3600) % 1 * 60)

        this.time_long = h + '小时' + m + '分钟'

      },
      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',
          dinner_time: '18:30'
        })
      },
      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.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
        this.$nextTick(()=>{
            this.$refs['formdata'].clearValidate();
        })

      },

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


      // 获取规则列表
      loadRuleList: function (item) {
        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
        }
        if(item == 1){//删除时执行
          if(self.tableData){
            if(self.tableData.length == 1){//当前页面的是否只剩下一个
              if(params.page!=1){//第一页时不执行
                params.page = this.currentPage-1//删除时，并且只剩下一个，返回上一页
              }
            }
          }
        }
        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 (formName) {
        let self = this
        let send_data = JSON.parse(JSON.stringify(this.formdata))

        let newSrtinf = '';
        for (let t in send_data.time_list) {
          // console.log(send_data.time_list)
          if (t == send_data.time_list.length - 1) {
            newSrtinf = 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[t].dinner_time;
          } else {
            newSrtinf = 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[t].dinner_time + ',';
          }
          send_data.config = send_data.config + newSrtinf;
        }
        send_data.is_break_time = send_data.is_break_time ? 1 : 0
        send_data.break_time = send_data.is_break_time ? send_data.break_time[0]+'-'+send_data.break_time[1] : '';
        if (send_data.is_break_time == 0) {
          delete send_data.break_time;
        }
        send_data.is_card = send_data.is_card ? 1 : 0
        let params = send_data;
        delete params.time_list

        if (params.config.indexOf("null") >= 0) {
          self.$message.error('打卡次序不规范')
          return false
        }
        if (params.is_break_time == 1 && params.break_time.indexOf("null") >= 0) {
          self.$message.error('休息时间不规范')
          return false
        }

        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.save_loading = true
            this.$jtoken({
              url: this.form_api,
              method: 'post',
              data: qs.stringify(params),
              headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function (response) {
              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('网络错误')}).finally(() => {self.save_loading = false})
          }
        });
      },

      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(this.serveAd + '/ad/schedule/delete', {
            params: params
          })
          .then(function (response) {

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

      // 创建修改班次
      toDetailPage: function (id, event) {
        const self = this
        self.formdata = {
          name: '',
          config: '',
          break_time: ['12:00', '13:00'],
          is_break_time: false,
          is_card: false,
          allowed_late_time: 3,
          serious_late_time: 20,
          absenteeism_late_time: 30,
          time_list: [{
            id: 0,
            checkin_time: '8:00',
            start_time: '8:30',
            end_time: '18:00',
            dinner_time: '18:30'
          }, ],
        }

        if (id > 0) {
          // this.form_api = '/integral.php/attendance_group/update_schedule'
          this.form_api = this.serveAd + '/ad/schedule/update'
          this.dialog_title = '修改班次'
          //获取一条记录，用于复原修改界面
          this.$jtoken
            .get(this.serveAd + '/ad/schedule/info', {
              params: {
                id: id
              }
            }).then((res) => {
              if (res.status == 200) {
                self.formdata.name = res.data.data.name

                let time_list = []
                let config = res.data.data.time_list;
                console.log(config);
                for (let t in config) {

                  time_list.push({
                    checkin_time: config[t][0],
                    dinner_time: config[t][3],
                    start_time: config[t][1],
                    end_time: config[t][2]
                  })
                }
                self.formdata.time_list = time_list
                // console.log(time_list)
                // console.log(self.formdata.time_list)
                // console.log("1111")
                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 = this.serveAd + '/ad/schedule/add'
          this.dialog_title = '创建班次'
        }

      },

    },
    created() {
      this.loadRuleList()
    }
  }
</script>
<style scoped>

  .date_tag .el-tag + .el-tag {
    margin: 5px;
  }
  .attendance_group 
  .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;
  }
  .attendance_group /deep/ .el-scrollbar__wrap{
    overflow-x:hidden !important;
  }

  .setMapBaidu .map {
    width: 100%;
    height: 300px;
  }
   /deep/ .el-table .newClass  th> .cell {
    font-size: 16px;
    font-weight: bolder;
  }
 
  /deep/ .el-table__row .cell .el-input--prefix .el-input__inner {
    padding: 0;
    padding-left: 10px;
  }
  .picker-no-icon{display: none !important;}
  .picker-no-icon-box input{padding-left:10px !important;}
  .picker-no-icon-box.sec_day{width:80px;}
  
</style>
