<template>
  <div style=" position: relative;" class="">
    <el-tabs v-model="activeName2" type="card">
      <el-tab-pane label="请假" name="type_4">

      </el-tab-pane>
      <el-tab-pane label="出差" name="type_2">

      </el-tab-pane>

      <el-tab-pane label="外出" name="type_3">

      </el-tab-pane>
      <el-tab-pane label="补卡" name="type_0">

      </el-tab-pane>
      <el-tab-pane label="加班" name="type_1">

      </el-tab-pane>

    </el-tabs>




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

        <el-select v-model="filter.status" placeholder="请选择" @change="onFilterChanged" class="first-element-btn">

          <el-option label="全部" :value="10"></el-option>
          <el-option label="已通过" :value="1"></el-option>
          <el-option label="待审批" :value="0"></el-option>
          <el-option label="已驳回" :value="-1"></el-option>
        </el-select>
        <el-date-picker

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

        <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>

      </div>




      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        :border="false"
        tooltip-effect="dark"
        style="width: 100%"
      >


        <el-table-column prop="employee_name" label="申请人" width="120"></el-table-column>
        <el-table-column v-if="filter.type == 4" label="类型">
          <template slot-scope="scope"><span v-if="scope.row.ask_for_leave_type == 1">事假</span>
            <span v-if="scope.row.ask_for_leave_type == 2">病假</span>
             <span v-if="scope.row.ask_for_leave_type == 0">年假</span>

             <span v-if="scope.row.ask_for_leave_type == 3">调休</span>
             <span v-if="scope.row.ask_for_leave_type == 4">产假</span>
             <span v-if="scope.row.ask_for_leave_type == 5">婚假</span>
             <span v-if="scope.row.ask_for_leave_type == 6">例假</span>
             <span v-if="scope.row.ask_for_leave_type == 7">丧假</span>
             <span v-if="scope.row.ask_for_leave_type == 8">陪产假</span>
          </template>
        </el-table-column>

        <el-table-column label="行程" v-if="filter.type == 2">
          <template slot-scope="scope">

            <div v-for="(item,index) in JSON.parse(scope.row.travel_list)" :key="index">{{item.address}}：{{item.startTime}} — {{item.endTime}}</div>


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

        <el-table-column label="时间" v-if="filter.type != 2">

          <template slot-scope="scope">

            <span>{{dateTimeFormatter('','',scope.row.start_time)}}</span>


            <span v-if="scope.row.type > 0">-{{dateTimeFormatter('','',scope.row.end_time)}}</span>
<div v-if="scope.row.type != 0">时长：{{(scope.row.duration/3600).toFixed(1)}}小时</div>
          </template>

        </el-table-column>

        <el-table-column label="附件">
          <template slot-scope="scope">
            <div>
              <a style="margin:5px;"
                v-for="(item,idx) in scope.row.file_list"
                :key="idx"
                @click="fileProview(item, scope.row.file_list, scope.row.id)"
              >

                <img width="50" height="50" v-if="item != ''"
                  :src="item"
                >

              </a>
            </div>

            <div style="display:none;">
              <img
                v-for="(item,index) in scope.row.file_list"
                :key="index"
                v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(item.split('.')[1]) >= 0"
                :src="item"
                :preview="scope.row.id"
                :preview-text="item"
              >
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" >
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">待审批</span>
            <span v-if="scope.row.status == 1">通过</span>
            <span v-if="scope.row.status == -1">驳回</span>
          </template>

        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>


        <el-table-column label="操作">
          <template slot-scope="scope">

            <el-button
              v-if="scope.row.status == 0"
              type="text"
              @click="set_review_status(1,scope.row.id)"
            >通过
            </el-button>

            <el-button
              v-if="scope.row.status != 0"
              type="text"
              @click="set_review_status(0,scope.row.id)"
            >撤销
            </el-button>


            <el-button
              type="text"
              @click="get_review_info(scope.row.id)"
            >查看
            </el-button>


            <el-button
              v-if="scope.row.status == 0"
              type="text"
              @click="set_review_status(-1,scope.row.id)"
            >驳回
            </el-button>


          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        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>




    <el-dialog
      class="attendance_group"
      title="审批详情"
      :visible.sync="ReviewDetailDialogVisible"
      width="600px"
      top="50px"
    >
      <el-scrollbar
        wrap-class="column-wrapper scrollable-items-container check-item-box dept_tree"
        :native="false"
        style="height: 400px;"
      >

<div style="padding:0 50px;">


        <div class="text_item" v-if="review_info.type == 4">申请类型：{{review_info.typeContent}}</div>
        <div class="text_item" v-if="review_info.type == 0">申请类型：补卡</div>
        <div class="text_item" v-if="review_info.type == 1">申请类型：加班</div>
        <div class="text_item" v-if="review_info.type == 2">申请类型：出差</div>
        <div class="text_item" v-if="review_info.type == 3">申请类型：外出</div>
<div　 class="text_item" v-if="review_info.type == 2">
  <div  v-for="(item,index) in (review_info.travelList)" :key="index">行程：{{item.address}}　{{item.startTime}} — {{item.endTime}}</div>

</div>
        <div class="text_item" v-if="review_info.type == 2">共计：{{(review_info.duration/3600).toFixed(2)}}小时</div>


        <div v-if="review_info.type == 1 || review_info.type == 3 || review_info.type == 4" class="text_item">时间：{{review_info.startTime}} 至 {{review_info.endTime}} 共计：{{(review_info.duration/3600).toFixed(2)}}小时</div>


  <div v-if="review_info.type == 0" class="text_item">补卡班次：{{review_info.startTime}}</div>

        <div class="text_item">备注：{{review_info.remark}}</div>
        <div class="text_item" v-if="review_info.noticePeopleList&&review_info.noticePeopleList.length > 0">抄送人：<el-tag style="margin:0 5px;" v-for="(item,index) in review_info.noticePeopleList" :key="index">{{item.name}}</el-tag></div>




        <div class="text_item">附件：
          <a style="margin:5px;"
             v-for="(item,idx) in review_info.fileList"
             :key="idx"
             @click="fileProview(item, review_info.fileList, review_info.id)"
          >

            <img style="border:1px solid #eee; padding:2px;" width="50" height="50" v-if="item != ''"
                 :src="item"
            >

          </a>
        </div>




<h4>审批流程</h4>
        <div class="text_item"></div>




        <el-timeline>
          <el-timeline-item
            :key="100"
            :timestamp="review_info.createtime">
            <div>申请人：{{review_info.name}}</div>
            <div style="line-height: 1.5">{{review_info.remark}}</div>
          </el-timeline-item>


          <el-timeline-item
            v-for="(activity, index) in review_list"
            :key="index"
            :icon="activity.icon"
            :type="activity.type"
            :color="activity.color"
            :size="activity.size"
            :timestamp="activity.timestamp">
            <div>{{activity.content}}</div>
            <div style="line-height: 1.5">{{activity.comment}}</div>
          </el-timeline-item>
        </el-timeline>





  <el-input
    type="textarea"
    :rows="3"
    placeholder="审批意见"
    v-model="formdata.remark">
  </el-input>
</div>




      </el-scrollbar>

      <span slot="footer" class="dialog-footer">



        <el-button type="primary" @click="set_review_status(0)" v-if="review_info.status == 1">撤销</el-button>
        <el-button type="primary" @click="set_review_status(1)" v-if="review_info.status == 0">通过</el-button>
<el-button type="danger" plain @click="set_review_status(-1)" v-if="review_info.status == 0">驳回</el-button>

      </span>

    </el-dialog>


  </div>
</template>


<script>
  import moment from 'moment'
  import qs from 'qs'
  import Vue from 'vue'
  import preview from 'vue-photo-preview'
  import 'vue-photo-preview/dist/skin.css'
  Vue.use(preview, {
    tapToClose: false
  })
  export default {

    data() {
      return {
        ReviewDetailDialogVisible: false,
        activeName2: 'type_4',
        filter: {
          type: 4,
          time_range: [],
          status: 0,
          keywords: ''
        },
        formdata: {
          id: 0,
          status: 0,
          remark: ''
        },
        profile: this.$store.getters.user_info,
        review_list: [{
          content: '支持使用图标',
          timestamp: '2018-04-12 20:46',
          size: 'large',
          type: 'primary',
          icon: 'el-icon-more'
        }],
        review_info: {
          'name': '',
          'department': '',
          'img_url': '',
          'reviewerName': '',
          'startTime': '',
          'endTime': '',
          'duration': 3,
          'status': 0,
          'applyTime': '',
          'reviewTime': '',
          'typeContent': '',
          'fileList': [],
          'remark': '',
          'travelList': []

        },
        loading: false,
        pageLimit: 10,
        totalCount: 0,
        currentPage: 1,
        tableData: 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()])
              }
            }
          ]
        }
      }
  },
    watch: {
      activeName2(val, old) {
        this.filter.type = val.split('_')[1]
        this.onFilterChanged()
      }
    },
    filters: {
      dateTimeFormatter: function(cellValue) {
        return moment(cellValue * 1000).format('YYYY-MM-DD HH:mm')
      }
    },
    methods: {

      fileProview(url, list, key) {
        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].split('.')[1]) >=
              0
            ) {
              if (list[i] == url) {
                console.log(ii)
                this.openPhotoSwipe(
                  ii,
                  document.querySelectorAll('img[preview="' + key + '"]')
                )

                return
              }
              ii++
            }
          }
        }
      },

      get_status_text(status) {
        if (status == 0) {
          return '待审批'
        }
        if (status == -1) {
          return '驳回'
        }
        if (status == 1) {
          return '通过'
        }
      },

      set_review_status(status, id) {
        const self = this
        if (typeof (id) !== 'undefined') {
          self.formdata.id = id
        }
        self.formdata.status = status
        this.$http('post','/integral.php/attendance_review/review',qs.stringify(self.formdata),
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded'
          // }
        ).then(function(res) {
          self.ReviewDetailDialogVisible = false
          self.loadList()
          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) {})
      },

      get_review_info(id) {
        const self = this
        this.$http('get','/integral.php/attendance_review/get_a_history_apply_for',{id: id}).then(response => {
            if (response.status == 200) {
              var jsonData = response.data.data

              self.review_info = jsonData[0]
              const review_list = []
              // self.formdata.id = jsonData
              for (const i in jsonData) {
                if (jsonData[i].reviewer_id == self.profile.id) {
                  self.formdata.id = jsonData[i].id
                }
                review_list.push({
                  content: jsonData[i].reviewerName + '(' + self.get_status_text(jsonData[i].status) + ')',
                  timestamp: jsonData[i].reviewTime,
                  size: 'large',
                  type: 'primary',
                  comment: jsonData[i].comment
                })
              }
              self.review_list = review_list
            }
          })
          .catch(error => {
            console.log(error)
          })

        this.ReviewDetailDialogVisible = true
      },
      dateTimeFormatter: function(row, column, cellValue) {
        return cellValue
          ? this.$moment(cellValue * 1000).format('MM-DD HH:mm')
          : ''
      },
      handleSizeChange(val) {
        this.pageLimit = val
        this.onFilterChanged()
      },
      handleClick(tab, event) {
        console.log(tab, event)
      },
      onFilterChanged: function() {
        this.currentPage = 1
        this.loadList()
      },
      loadList: function() {
        var self = this
        self.loading = true
        let time_range = JSON.parse(JSON.stringify(self.filter.time_range))
        if (time_range == null) {
          time_range = []
        }
        if (time_range.length > 0) {
          time_range[0] = time_range[0] * 1 / 1000
           time_range[1] = (time_range[1]*1/1000) + 24*3600-1
        }

        var params = {
          page: this.currentPage,
          interval: this.pageLimit,
          keywords: self.filter.keywords,
          status: self.filter.status,
          type: self.filter.type,
          time_range: time_range.toString()
        }
        if (self.filter.status == 10) {
          params.status = '0,1,-1'
        }

        this.$http('get','/integral.php/attendance_review/get_history_apply_for',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.data
              } catch (err) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      changePage: function(current) {
        if (isNaN(current) || current < 1) {
          return false
        }
        this.loadList()
      }
    },
    created() {
      this.loadList()
    }
  }
</script>

<style>


  .paiming .el-tabs__content {
    overflow: visible;
  }

  .paiming .el-tabs__nav-wrap {
    background-color: #5B8BF7;
    padding: 3px 3px 0 3px;
    border-radius: 3px 3px 0 0;
  }

  .paiming .el-tabs__item {
    color: #fff;
    border: none;
    font-weight: normal;
  }

  .paiming .el-tabs--card > .el-tabs__header .el-tabs__nav {
    border: none;
  }

  .paiming .el-tabs--card > .el-tabs__header .el-tabs__item {
    border: none;
  }

  .paiming .is-active {
    background-color: #fff;
    color: rgba(96, 98, 102, 1);
    border-radius: 3px 3px 0 0;
  }

  .paiming .el-tabs__item.is-active {
    color: rgba(96, 98, 102, 1);
  }
  .text_item{line-height: 2;}
</style>
