<template lang="pug">
  <div class='m_i_dialog'>
    <el-dialog :title="title" width="1500px" :close-on-click-modal='false' :visible.sync='visible' :modal-append-to-body='false'>
      <el-container>
        <el-aside>
            <el-card>
              <div class="patrol_line_left_top">
                <div class="patrol_line_left_topL">
                  <div :class="[activeName==1?'on':'']">巡查线路</div>
                </div>
              </div>
              <div class="left_list">
                <div :class="{ 'left_list_row_on': item.on, 'left_list_row': true }" v-for="(item, index) in leftListData" @click="leftListRowClick(item,index)">
                  <div class="left_list_row_name">{{item.name}}</div>
                  <div class="left_list_row_size">

                  </div>
                </div>
              </div>
            </el-card>
        </el-aside>

        <el-main style="padding:0px;" onselectstart="return false;">
          <el-card>
            <div class="patrol_line_right_button">
              <el-row style="padding-bottom:15px;" :span="24">
                  <el-col :md='18' :sm="5" class='tier-btn'>
                      <el-button type="primary" size="small" plain :class="[checkedData.tierId===item.id?'active-tier':'']" style="float:left;margin-left:10px;" v-for="item in mapList" :key='item.id' @click="changeMap(item)">{{item.name}}</el-button>
                  </el-col>
              </el-row>
            </div>
            <el-row style="padding-bottom:15px;" :span="24">
              <el-col class="resource-container" ref="drag">
                <!-- <el-image :src="stationMap.readPath" fit='scale-down'></el-image> -->
                <img src="@/assets/images/back.png" ></img>
                <span v-for="item in list">
                  <span class="span-box" :class="[item.active?'el-icon-wq-qiangji1':'el-icon-wq-qiangji']"  :id='item.id' :title="item.name" :dataKey="item.key" :key="item.key" :style="{'left':item.coordinateX?item.coordinateX+'px':0,'top':item.coordinateY?item.coordinateY+'px':0,cursor:'pointer'}" style="position: absolute;line-height:130px;text-align:center" >{{item.name}}</span>
                </span>
              </el-col>
            </el-row>
          </el-card>
        </el-main>
      </el-container>
      <el-row style="padding:15px 0 15px;">
        <el-col ref="drag" :span="6">
          <el-form :model='dataForm' :rules='dataRule'  ref='dataForm' :inline='true'  label-width="100px">
            <el-form-item label='计划名称:' prop='name'>
              <el-input v-model='dataForm.name' ></el-input>
            </el-form-item>
            <el-form-item label='巡查员:' prop='patrollerName'>
              <el-autocomplete class="inline-input" :disabled="cloneStatus" v-model="dataForm.patrollerName" :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect"></el-autocomplete>
            </el-form-item>
            <el-form-item label="开始时间:" prop='startTime'>
              <el-date-picker type="datetime" :disabled="cloneStatus" class="inputWidth" style="width:175px;" v-model="dataForm.startTime" placeholder="选择日期时间" clearable></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop='endTime'>
              <el-date-picker type="datetime" :disabled="cloneStatus" class="inputWidth" style="width:175px;" v-model="dataForm.endTime" placeholder="选择日期时间" clearable></el-date-picker>
            </el-form-item>
            <el-form-item label='巡查周期:' prop='circle' required>
              <el-select v-model="dataForm.circle+''" :disabled="cloneStatus" placeholder="请选择" >
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label='备注:' prop='remark'>
              <el-input v-model='dataForm.remark' :disabled="cloneStatus" type="textarea" placeholder="请输入内容" maxlength="100" show-word-limit></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col ref="drag" :span="18">
          <el-table :data="dataList" style="width: 100%;">
            <el-table-column type="index" header-align="center" align="center" width='80' label="序号"></el-table-column>
            <el-table-column prop="pointName" header-align="center" align="center" label="巡查点"></el-table-column>
            <el-table-column header-align="center" align="center" :label="'到达时间(按时间排序,实际到达允许'+waveTime+'分钟时间波动)'">
              <template slot-scope="scope">
                <el-time-picker v-model="scope.row.time" :disabled="!editStatus" @change="timeChange(scope.row)" placeholder="任意时间点"></el-time-picker>
              </template>
            </el-table-column>
            <el-table-column header-align="center" align="center" label="操作">
              <template slot-scope="scope">
                <el-button  @click="deleData(scope.row,scope.$index)" :disabled="!editStatus" type="text">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <span class="dialog-footer" slot='footer'>
        <el-button type="primary" @click='sevaClick'>保存</el-button>
        <el-button @click='visible = false'>关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import Vue from 'vue'
export default {
  computed: {
    ...mapState('d2admin/user', [
      'info'
    ])
  },
  data () {
    return {
      waveTime: '0',
      editStatus: true,
      cloneStatus: false,
      leftListData: [],
      leftListOnData: null,
      spotData: [],
      spotDataList: [],
      spotOnData: [],
      visible: false,
      dataForm: {
        name: '',
        patrollerName: '',
        startTime: '',
        endTime: '',
        circle: '1',
        remark: '',
        patrollerId: ''
      },
      activeName: '1',
      title: '新增',
      restaurants: [],
      dataRule: {
        name: { required: true, message: '请输入计划名称', trigger: 'change' },
        patrollerName: { required: true, message: '请选择检察员', trigger: 'change' },
        startTime: { required: true, message: '请选择开始时间', trigger: 'change' },
        endTime: { required: true, message: '请选择结束时间', trigger: 'change' }
      },
      list: [],
      mapList: [],
      nodeKey: 'id',
      defaultExpandedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        level1: 'level'
      },
      treeData: [],
      dataList: [],
      dataAllList: [],
      checkedData: {
        tierId: '',
        tierName: '',
        sId: '',
        subCode: '02'
      },
      options: [{
        value: '1',
        label: '一天'
      }, {
        value: '7',
        label: '一周'
      }, {
        value: '30',
        label: '一月'
      }]
    }
  },
  created() {
    this.getStationList()
    this.getFluctuationTime()
  },
  methods: {
    init (sId, res, title) {
      this.visible = true
      this.checkedData.sId = sId
      this.initTreeStationMap()
      if (title) {
        this.dataForm = res
        this.title = title
        if (title == '复制') {
          this.cloneStatus = true
        }
        this.editStatus = false
      } else {
        this.title = '新增'
        this.editStatus = true
        this.cloneStatus = false
        this.$refs.dataForm.resetFields()
      }
    },
    getFluctuationTime() {
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolPlan/getFluctuationTime'),
        method: 'get'
      }).then(data => {
        this.waveTime = data.time
      })
    },
    initTreeStationMap() {
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolLine/list'),
        method: 'post',
        data: {
          stationId: this.checkedData.sId
        }
      }).then(data => {
        if (data && data.code === 0) {
          this.leftListData = data.nodes
          if (this.editStatus) {
            this.leftListOnData = this.leftListData[0]
            this.leftListData[0].on = true
            if (this.leftListData[0].children) {
              this.leftListData[0].children.forEach(res => {
                this.spotOnData.push(res.id)
              })
            } else {
              this.spotOnData = []
            }
          } else {
            this.leftListData.forEach(res => {
              if (res.id == this.dataForm.lineId) {
                this.leftListOnData = res
                this.getDataList()
                res.on = true
                if (res.children) {
                  res.children.forEach(res => {
                    this.spotOnData.push(res.id)
                  })
                } else {
                  this.spotOnData = []
                }
              }
            })
          }
        }
      }).then(() => {
        this.epPatrolPointList()
      })
    },
    epPatrolPointList() {
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolPoint/list'),
        method: 'post',
        data: {
          stationId: this.checkedData.sId
        }
      }).then(data => {
        if (data && data.code === 0) {
          this.spotDataList = data.nodes
          this.spotData = JSON.parse(JSON.stringify(this.spotDataList))
          this.mapList = data.nodes
          this.checkedData.tierId = this.mapList[0].id
          this.checkedData.tierName = this.mapList[0].name
          this.stationMap = this.mapList[0]
        }
      }).then(() => {
        this.showResourceByMapId()
      })
    },
    showResourceByMapId() {
      this.spotData.forEach(spotRes => {
        if (this.checkedData.tierId == spotRes.id) {
          this.list = spotRes.children || []
        }
      })
      if (this.leftListOnData.children) {
        this.leftListOnData.children.forEach(subSystem => {
          this.list.forEach(listRes => {
            if (subSystem.id == listRes.id) {
              Vue.set(listRes, 'active', true)
            }
          })
        })
      }
    },
    getDataList() {
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolPlan/getId/' + this.dataForm.id),
        method: 'get'
      }).then(data => {
        if (data && data.code === 0) {
          this.dataList = []
          data.bean.pointList.forEach(res => {
            this.dataList.push({
                  pointId: res.pointId,
                  pointName: res.pointName,
                  arrivalTime: res.arrivalTime,
                  time: new Date('2020-07-01 ' + res.arrivalTime) })
          })
        }
      })
    },
    changeMap(map) {
      this.checkedData.tierId = map.id
      this.checkedData.tierName = map.name
      this.stationMap = map
      this.showResourceByMapId()
    },
    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)
      }
    },
    timeChange(row) {
      row.arrivalTime = this.formatTime(row.time, 'hh:mm:ss')
    },
    getStationList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrlEq('/sysUser/getAllSysUser'),
        method: 'get'
      }).then(data => {
        data.users.forEach(res => {
          this.restaurants.push({ value: res.nameMobile, id: res.patrollerId, name: res.patrollerName })
        })
      })
    },
    handleSelect(item) {
      this.dataForm.patrollerName = item.name
      this.dataForm.patrollerId = item.id
    },
    handleNodeClick() {

    },
    deleData(row, $index) {
      this.dataList.splice($index, 1)
    },
    leftListRowClick(item, index) { //任务列表点击任务
      if (!this.editStatus) {
        return false
      }
      this.spotData = JSON.parse(JSON.stringify(this.spotDataList))
      this.leftListData.forEach((res, i) => {
        if (index == i) {
          Vue.set(res, 'on', true)
          this.leftListOnData = res
        } else {
          Vue.set(res, 'on', false)
        }
      })
      this.spotData.forEach(spotRes => {
        if (this.checkedData.tierId == spotRes.id) {
          this.list = spotRes.children || []
        }
      })
      this.dataList = []
      if (this.leftListOnData.children) {
        this.leftListOnData.children.forEach(itemRes => {
          this.list.forEach(listRes => {
            if (itemRes.id == listRes.id) {
              Vue.set(listRes, 'active', true)
            }
          })
          this.dataList.push({
            pointId: itemRes.id,
            pointName: itemRes.name,
            arrivalTime: '',
            time: null
          })
        })
      }
    },
    sevaClick() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (this.dataForm.startTime > this.dataForm.endTime) {
            this.$message.warning('开始时间不能大于结束时间')
            return false
          }
          let num = 0, warn = false
          this.dataList.forEach(res => {
            if (!warn) {
              num++
              if (!res.time) {
                this.$message.warning('请选择巡查时间')
                warn = true
                return false
              }
              if (num == this.dataList.length) {
                this.saveSet()
              }
            }
          })
        }
      })
    },
    saveSet() {
      let url = ''
      if (this.title == '编辑') {
        url = this.$http.adornUrlEq('/epPatrolPlan/update')
      } else {
        url = this.$http.adornUrlEq('/epPatrolPlan/save')
      }
      this.$http({
        url: url,
        method: 'post',
        data: {
          id: this.dataForm.id,
          stationId: this.checkedData.sId,
          lineId: this.leftListOnData.id,
          lineName: this.leftListOnData.name,
          name: this.dataForm.name,
          patrollerName: this.dataForm.patrollerName,
          patrollerId: this.dataForm.patrollerId,
          startTime: this.formatTime(this.dataForm.startTime, 'yyyy-MM-dd hh:mm:ss'),
          endTime: this.formatTime(this.dataForm.endTime, 'yyyy-MM-dd hh:mm:ss'),
          circle: this.dataForm.circle,
          remark: this.dataForm.remark,
          pointList: this.dataList
        }
      }).then(data => {
        if (data && data.code === 0) {
          this.$message.success('保存成功')
          this.visible = false
          this.$emit('closeQ')
        }
      })
    },
    //转化时间
    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' scoped>
.resource-container{
  img{
    width: 100%;
  }
}
.el-card{
  height:99%;
}
.left_list{
    margin-top: 20px;
    .left_list_row_on{
      background-color: #35AFF8 !important;
      color: #fff;
    }
    .left_list_row{
      cursor: pointer;
      width: 90%;
      height: 40px;
      border-radius:20px 0 0 20px;
      background: #fff;
      padding:0 20px;
      margin-bottom: 10px;
      .left_list_row_name{
        float: left;
        widows: 65%;
        line-height: 40px;
      }
      .left_list_row_size{
        float: right;
        widows: 25%;
        padding-top: 7px;
      }
    }
  }
  .span-box{
    height: 60px;
    width: 72px;
  }

</style>
