<template >
    <el-container style="padding:0px;height:77.6vh;">
      <el-header class="el_header-style">
        <span class="title-bold title-left-color">巡查计划</span>
        <el-popover placement="bottom" width="150" >
                <el-button slot="reference" size='mini' type="primary" icon="el-icon-s-tools" style='float:right;transform:translateY(6px)'> 筛选</el-button>
                <el-checkbox-group v-model="checkList">
                    <el-col :span="24">
                        <el-checkbox v-for="(item,index) in tableHeader" :label="item" :key="index"  >
                          {{item.label}}
                        </el-checkbox>
                    </el-col>
                </el-checkbox-group>
          </el-popover>
      </el-header>
      <el-main class="box_main">
        <el-card>
            <el-form :inline="true" size="mini" :model="dataForm">
              <el-form-item label="计划名称:">
                <el-input v-model="dataForm.name" placeholder="请输入内容" ></el-input>
              </el-form-item>
              <el-form-item label="巡查线路:">
                <el-input v-model="dataForm.lineName" placeholder="请输入内容" ></el-input>
              </el-form-item>
              <el-button @click="getDataList()" type="primary"  size="mini" icon="el-icon-search">查询</el-button>
              <el-button @click="reSet()" type="primary"  size="mini" icon="el-icon-refresh-right">重置</el-button>
              <el-button v-if="isAuth('patrol:plan:save')" icon="el-icon-plus" type="primary" @click="addPlan" style="float:right" size="mini">新增</el-button>
            </el-form>
            <!-- <el-table :data="dataList" @sort-change='sortChange' v-loading="dataListLoading" :stripe="true" :header-cell-style="{background:'#EEF8FF',color:'#333333'}" style="width: 100%;">
              <el-table-column type="index" header-align="center" align="center" width='50' label="序号">
                <template scope="scope"><span>{{scope.$index+(pageIndex - 1) * pageSize + 1}} </span></template>
              </el-table-column>
              <el-table-column prop="name" sortable="custom" header-align="center" align="center" label="计划名称"></el-table-column>
              <el-table-column prop="lineName" column-key="line_name" sortable="custom" header-align="center" align="center" label="巡查线路"></el-table-column>
              <el-table-column prop="lineStationName" column-key="line_station_name" sortable="custom" header-align="center" align="center" label="巡查站点"></el-table-column>
              <el-table-column prop="startTime" column-key="start_time" sortable="custom" header-align="center" align="center" label="开始日期"></el-table-column>
              <el-table-column prop="endTime" column-key="end_time" sortable="custom" header-align="center" align="center" label="结束日期"></el-table-column>
              <el-table-column header-align="center" align="center" label="操作" width="230">
                <template slot-scope="scope">
                  <el-button v-if="isAuth('patrol:plan:save')" type="text" size="mini" @click="editPlan(scope.row)">编辑</el-button>
                  <el-button v-if="isAuth('patrol:plan:delete')" type="text" size="mini" @click="deleClick(scope.row)">删除</el-button>
                  <el-button v-if="isAuth('patrol:plan:warn')" type="text" size="mini" @click="sendMail(scope.row)" v-prevent-re-click>提醒</el-button>
                  <el-button v-if="isAuth('patrol:plan:copy')" type="text" size="mini" @click="cloneClick(scope.row)" v-prevent-re-click>复制</el-button>
                </template>
              </el-table-column>
            </el-table> -->
            <drag-table :data="dataList" :header="checkList" :option="tableOption"  @getDataList="getDataList" v-loading="dataListLoading" :operationNum="4"  :isShowOperate="true" >

              <!-- 插槽  -->
              <el-table-column slot="fixed"  fixed  prop=""  label="序号"  width="80"  header-align="center" align="center" >
                  <template slot-scope="scope">
                    <span>{{scope.$index+(pageIndex - 1) * pageSize + 1}}</span>
                  </template>
              </el-table-column>

              <template slot="name" slot-scope="scope">
                  <span :title='scope.row.name'> {{scope.row.name,20 | ellipsis}}</span>
              </template>

              <!-- 操作项 -->
              <template slot-scope="scope">
                <el-button v-if="isAuth('patrol:plan:save')" type="text" size="mini" @click="editPlan(scope.row)">编辑</el-button>
                <el-button v-if="isAuth('patrol:plan:delete')" type="text" size="mini" @click="deleClick(scope.row)">删除</el-button>
                <el-button type="text" size="mini" @click="detailHandle(scope.row)">详情</el-button>
                <el-button v-if="isAuth('patrol:plan:warn')" type="text" size="mini" @click="sendMail(scope.row)" v-prevent-re-click>提醒</el-button>
                <el-button v-if="isAuth('patrol:plan:copy')" type="text" size="mini" @click="cloneClick(scope.row)" v-prevent-re-click>复制</el-button>
              </template>

            </drag-table>
        </el-card>
      <el-dialog  :visible.sync="dialogVisible" width="30%" append-to-body :before-close="handleClose" >
        <span slot='title' class="title-bold">设置提醒</span>
        <el-form :model="dialogData" ref="dialogData" label-width="120px" style="width:80%;margin:0 auto" size="mini">
            <el-form-item label="计划名称：" prop='name'>
              <!-- <el-input v-model="dialogData.name" readonly></el-input> -->
              <font>{{dialogData.name}}</font>
            </el-form-item>
            <el-form-item label="巡查员：" prop='patrollerName'>
              <!-- <el-input v-model="dialogData.patrollerName" readonly></el-input> -->
              <font>{{dialogData.patrollerName}}</font>
            </el-form-item>
            <el-form-item label="开始时间：" prop='startTime'>
              <!-- <el-input v-model="dialogData.startTime" readonly></el-input> -->
              <font>{{dialogData.startTime}}</font>
            </el-form-item>
            <el-form-item label="结束时间：" prop='endTime'>
              <!-- <el-input v-model="dialogData.endTime" readonly></el-input> -->
              <font>{{dialogData.endTime}}</font>
            </el-form-item>
            <el-form-item label="设置提醒时间：" prop='sendTime'  :rules="{ required: true, message: '提醒时间不能为空', trigger: ['blur','change'] }">
              <el-time-picker v-model="dialogData.sendTime" value-format="yyyy-MM-dd HH:mm:ss"></el-time-picker>
            </el-form-item>
        </el-form>
        <div slot="footer" align='center'>
          <!-- <el-button type="primary" @click="cancel">取 消</el-button> -->
          <el-button type="primary" @click="setSendTime" >设置</el-button >
        </div>
      </el-dialog>
      </el-main>
      <el-footer class="box_footer">
        <el-pagination @size-change="sizeChangeHandle" background @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" layout="total, sizes, prev, pager, next, jumper" ></el-pagination>
      </el-footer>
      <query-detail v-if='queryDetailVisible' ref='queryDetail' @closeQ="closeQueryDetailVisible"></query-detail>
      <plan-add-or-update v-if='planAddOrUpdateVisible' ref='planAddOrUpdate' @closeQ="closeQueryDetailVisible"></plan-add-or-update>
    </el-container>

</template>

<script>
import QueryDetail from './query-detail'
import PlanAddOrUpdate from './plan-add-or-update'
import dragTable from '../../components/tab'
export default {
  filters: {
    ellipsis(value, len) {
      if (!value) return ''
      if (value.length > len) {
        return value.slice(0, len) + '...'
      }
      return value
    }
  },
  data() {
    return {
      dialogData: { name: '', patrollerName: '', startTime: '', endTime: '', sendTime: '' },
      dialogVisible: false,
      queryDetailVisible: false,
      planAddOrUpdateVisible: false,
      dataForm: {
        stationId: localStorage.getItem('stationId'),
        subCode: '01',
        name: '',
        lineName: ''
      },
      dialogDataForm: {
        operation: '1'
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      state1: '',
      restaurants: [],
      sort: '',
      order: '',
      checkList: [], //筛选数据
      tableHeader: [
        { label: '计划名称', prop: 'name', slot: true }, //是否插槽
        { label: '巡查线路', prop: 'lineName' },
        { label: '巡查站点', prop: 'lineStationName' },
        { label: '开始日期', prop: 'startTime' },
        { label: '结束日期', prop: 'endTime' }
        // {label:'操作',prop:''},
      ],
      tableOption: {
        border: false, //是否边框
        maxHeight: 500 //高度
      }
    }
  },
  components: {
    QueryDetail,
    PlanAddOrUpdate,
    dragTable
  },
  watch: {
    totalPage() { //注意这个函数的名字必须和你监听data中的属性的名字一样，这样才能当你data中的属性发生变化时，触发这个函数
      let pages = Math.ceil(this.totalPage / this.pageSize)//新数据总页数
      //总页数小于当前页数则重新加载列表数据
      if (pages < this.pageIndex) {
          this.pageIndex = pages || 1
          this.getDataList()//获取表格数据的方法
      }
    }
  },
  created() {
    this.checkList = [...this.tableHeader]
    this.pageIndex = 1
    this.getDataList()
  },
  methods: {
    //重置
    reSet() {
      this.dataForm = {
        stationId: localStorage.getItem('stationId'),
        subCode: '01',
        name: '',
        lineName: ''
      }
      this.pageIndex = 1
      this.getDataList()
    },
    tabRowClick(res) {},
    querySearch(queryString, cb) {
      let restaurants = this.restaurants
      let results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        )
      }
    },
    sortChange(column) {
      if (column.order === 'descending') {
        this.order = 'desc'
      } else {
        this.order = 'asc'
      }
      if (column.column.columnKey) {
        this.sort = column.column.columnKey
      } else {
        this.sort = column.prop
      }
      this.getDataList()
    },
    handleSelect() {},
    // 获取数据列表
    getDataList(sort, order) {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolPlan/list'),
        method: 'post',
        data: {
          stationId: this.dataForm.stationId,
          page: this.pageIndex,
          rows: this.pageSize,
          name: this.dataForm.name,
          lineName: this.dataForm.lineName,
          sort: sort,
          order: order
        }
      }).then((data) => {
        // console.log('data', data)
        if (data && data.code === 0) {
          this.dataList = data.page.rows
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    editPlan(res) {
      // console.log(res.lineId, '编辑', res)
      // 测试是否能被修改
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolPlan/checkToUpdate'),
        method: 'get',
        params: {
          id: res.id,
          stationId: res.stationId
        }
      }).then((data) => {
        if (data && data.code === 0) {
          this.planAddOrUpdateVisible = true
          this.$nextTick(() => {
            this.$refs.planAddOrUpdate.init(this.dataForm.stationId, JSON.parse(JSON.stringify(res)), '编辑')
          })
        }
      })
    },
    detailHandle(res) {
      this.queryDetailVisible = true
      this.$nextTick(() => {
        this.$refs.queryDetail.init(this.dataForm.stationId, JSON.parse(JSON.stringify(res)), '详情')
      })
    },
    cloneClick(res) {
      this.planAddOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.planAddOrUpdate.init(this.dataForm.stationId, JSON.parse(JSON.stringify(res)), '复制')
      })
    },
    addPlan() {
      this.planAddOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.planAddOrUpdate.init(this.dataForm.stationId)
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    dialogFormVisible() {},
    closeQueryDetailVisible() {
      this.getDataList()
    },
    deleClick(row) {
      this.$confirm(`确认删除该巡查计划?`, '删除巡查计划', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        this.$http({
          url: this.$http.adornUrlEq('/epPatrolPlan/delete'),
          method: 'get',
          params: {
            id: row.id,
            stationId: row.stationId
          }
        }).then((data) => {
          if (data && data.code === 0) {
            this.$message.success('删除成功')
            this.getDataList()
          }
        })
      })
    },
    sendMail(row) {
      this.dialogData = { ...row }
      this.dialogVisible = true
    },
    // 关闭前
    handleClose() {
      this.$refs.dialogData.resetFields()
      this.dialogVisible = false
    },
    // 设置发送时间
    setSendTime() {
      this.$refs.dialogData.validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrlEq('/epPatrolPlan/sendMail'),
            method: 'post',
            params: this.dialogData
          }).then((data) => {
            if (data && data.code === 0) {
              this.$message.success('设置提醒成功')
              this.handleClose()
            }
          })
        }
      })
    },
    //取消
    cancel() {
      this.$confirm('确认取消?', '巡查计划', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.handleClose()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出'
          })
        })
    },
    //转化时间
    formatTime(date, format) {
      if (date) {
        date = new Date(date)
        var o = {
          'M+': date.getMonth() + 1, //月份
          'd+': date.getDate(), //日
          'h+': date.getHours(), //小时
          'm+': date.getMinutes(), //分
          's+': date.getSeconds(), //秒
          'q+': Math.floor((date.getMonth() + 3) / 3), //季度
          S: date.getMilliseconds() //毫秒
        }
        var fmt = format || 'yyyy-MM-dd hh:mm'
        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + '').substr(4 - RegExp.$1.length)
          )
        }
        for (var k in o) {
          if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                ? o[k]
                : ('00' + o[k]).substr(('' + o[k]).length)
            )
          }
        }
        return fmt
      } else {
        return ''
      }
    }
  }
}
</script>
<style lang="scss">
.inputWidth {
  width: 130px;
}
.instuctions_header {
  height: 42px;
  background: #edeef1;
  border: 1px solid rgba(195, 195, 195, 1);
  h1 {
    font-size: 16px;
    line-height: 42px;
    height: 42px;
    margin: 0;
    font-family: Adobe Heiti Std;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    float: left;
  }
  span {
    width: 5px;
    height: 16px;
    background: rgba(33, 172, 252, 1);
    float: left;
    margin: 13px 10px 0 20px;
  }
}
.instuctions_content {
  padding: 20px;
  background: #fff;
  table {
    th {
      background: #eef8ff !important;
      color: #333333 !important;
    }
  }
}
</style>
