<!--车辆进出列表-->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--人员出入次数-->
      <el-col :span="12">
        <el-form ref="selectForm" :inline="true" :model="personQuery" class="form-container">
          <el-row>
            <el-col :span="8">
              <el-form-item class="selectForm-container-item">
                <el-select v-model="personQuery.areaId" placeholder="请选择营门" clearable @change="fetchPersonData">
                  <el-option v-for="item in doorList" :key="item.value" :label="item.name" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item class="selectForm-container-item">
                <el-date-picker
                  v-model="personTimeRange"
                  :picker-options="pickerOptions"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 人员出入次数图表 -->
        <ve-line :data="personData" :title="personTitle" :settings="personSettings"/>
      </el-col>

      <!--车辆出入次数-->
      <el-col :span="12">
        <el-form ref="selectForm" :inline="true" :model="carQuery" class="form-container">
          <el-row>
            <el-col :span="8">
              <el-form-item class="selectForm-container-item">
                <el-select v-model="carQuery.areaId" placeholder="请选择营门" clearable @change="fetchCarData">
                  <el-option v-for="item in doorList" :key="item.value" :label="item.name" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item class="selectForm-container-item">
                <el-date-picker
                  v-model="carTimeRange"
                  :picker-options="pickerOptions"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 车辆出入次数图表 -->
        <ve-line :data="carData" :title="carTitle" :settings="carSettings"/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { formatToString, parseToDate, oneDayTime } from '@/utils/calendarUtil'
import { personInOutCount, carInOutCount } from '@/api/statistics'
import { getAreaNameList, getAreaTypeBySubSystem } from '@/api/area'

const now = new Date()

export default {
  name: 'DoorCount',
  data() {
    return {
      personQuery: {
        areaId: '', // 营门（区域）id
        beginDate: '', // 开始事件
        endDate: '' // 结束事件
      }, // 人员筛选条件
      carQuery: {
        areaId: '', // 营门（区域）id
        beginDate: '', // 开始事件
        endDate: '' // 结束事件
      }, // 人员筛选条件
      doorList: [], // 营门（区域）列表
      personTimeRange: [],
      carTimeRange: [],
      listLoading: false, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      dialogFormVisible: false,
      areaType: '', // 区域类别
      personTitle: {
        text: '营门人员出入次数统计'
      },
      personSettings: {
        labelMap: {
          'staff': '内部人员',
          'visitor': '来访人员'
        },
        xAxisType: 'time',
        max: [4],
        area: true,
        metrics: ['staff', 'visitor'],
        dimension: ['date'],
        loading: this.listLoading
      },
      personData: {
        columns: ['date', 'staff', 'visitor'],
        rows: []
      },
      carTitle: {
        text: '营门车辆出入次数统计'
      },
      carSettings: {
        labelMap: {
          'staff': '内部车辆',
          'visitor': '来访车辆'
        },
        xAxisType: 'time',
        max: [4],
        area: true,
        metrics: ['staff', 'visitor'],
        dimension: ['date'],
        loading: this.listLoading
      },
      carData: {
        columns: ['date', 'staff', 'visitor'],
        rows: []
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近七日',
          onClick(picker) {
            const end = now
            const start = new Date()
            start.setTime(start.getTime() - oneDayTime * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近十日',
          onClick(picker) {
            const end = now
            const start = new Date()
            start.setTime(start.getTime() - oneDayTime * 10)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三十日',
          onClick(picker) {
            const end = now
            const start = new Date()
            start.setTime(start.getTime() - oneDayTime * 30)
            picker.$emit('pick', [start, end])
          }
        }],
        disabledDate(time) {
          const oneMonthLater = new Date(now.getTime() - (oneDayTime * 31))
          return time.getTime() < oneMonthLater
        }
      }
    }
  },
  watch: {
    personTimeRange: function(newV) {
      if (newV) {
        this.personQuery.beginDate = formatToString(newV[0], 'DATE')
        this.personQuery.endDate = formatToString(newV[1], 'DATE')
      } else {
        this.personQuery.beginDate = ''
        this.personQuery.endDate = ''
      }
      this.fetchPersonData()
    },
    carTimeRange: function(newV) {
      if (newV) {
        this.carQuery.beginDate = formatToString(newV[0], 'DATE')
        this.carQuery.endDate = formatToString(newV[1], 'DATE')
      } else {
        this.carQuery.beginDate = ''
        this.carQuery.endDate = ''
      }
      this.fetchCarData()
    }
  },
  created() {
    this.initAreaType()
    this.fetchAreaNames()
  },
  activated() {
    this.fetchPersonData()// 获取数据
    this.fetchCarData() // 获取数据
  },
  methods: {
    // 查询数据
    initAreaType() {
      this.areaType = getAreaTypeBySubSystem(this.$store.getters.currentSystem.code)
    },
    fetchAreaNames() {
      getAreaNameList({ areaType: this.areaType }).then(response => {
        this.doorList = response.data
      })
    },
    // 获取列表
    fetchPersonData() {
      this.listLoading = true
      personInOutCount(this.personQuery).then(response => {
        if (response.code === 200) {
          const chartData = this.parseStatisticsData(response.data, 'person')
          this.personData.rows = chartData.rowDatas
          this.personSettings.max = [chartData.maxCount]

          this.listLoading = false
        } else {
          this.$message.error(response.message)
        }
        this.listLoading = false
      })
    },
    // 获取列表
    fetchCarData() {
      this.listLoading = true
      carInOutCount(this.carQuery).then(response => {
        if (response.code === 200) {
          const chartData = this.parseStatisticsData(response.data, 'car')
          this.carData.rows = chartData.rowDatas
          this.carSettings.max = [chartData.maxCount]

          this.listLoading = false
        } else {
          this.$message.error(response.message)
        }
        this.listLoading = false
      })
    },
    indexMethod(index) {
      return this.listQuery.limit * (this.listQuery.offset - 1) + index + 1
    },
    // 改变页容量
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.listQuery.offset = val
      this.fetchData()
    },
    parseStatisticsData(obj, type) {
      let staffList = []
      let visitorList = []
      if (type === 'person') {
        staffList = obj.person
        visitorList = obj.visitorPerson
      } else if (type === 'car') {
        staffList = obj.car
        visitorList = obj.visitorCar
      } else {
        return []
      }

      const rowDatas = [] // 返回的数据
      let maxCount = 4 // 返回的最大的计数值
      let indexS = 0
      let indexV = 0
      // 遍历内部人员（车辆）和来访人员（车辆），生成图表所需要的数据格式
      while (indexS < staffList.length || indexV < visitorList.length) {
        let staff = {}
        let visitor = {}

        // 获取内部人员（车辆）对象
        if (indexS < staffList.length) {
          staff = staffList[indexS]
        } else {
          staff = {}
        }

        // 获取来访人员（车辆）对象
        if (indexV < visitorList.length) {
          visitor = visitorList[indexV]
        } else {
          visitor = {}
        }

        // 如果内部人员（车辆）的队列已经取完则直接添加来访人员（车辆）
        if (typeof staff.date === 'undefined') {
          rowDatas.push({ date: visitor.date, visitor: visitor.count })
          indexV++
          maxCount = Math.max(maxCount, visitor.count)
          continue
        }

        // 如果来访人员（车辆）的队列已经取完则直接添加内部人员（车辆）
        if (typeof visitor.date === 'undefined') {
          rowDatas.push({ date: staff.date, staff: staff.count })
          indexS++
          maxCount = Math.max(maxCount, staff.count)
          continue
        }

        // 队列都还没有处理完成则比较日期的大小
        const visitorVal = parseToDate(visitor.date, 'DATE').valueOf()
        const staffVal = parseToDate(staff.date, 'DATE').valueOf()
        if (staffVal < visitorVal) {
          // 人员列表的日期比较小
          rowDatas.push({ date: staff.date, staff: staff.count })
          indexS++
          maxCount = Math.max(maxCount, staff.count)
        } else if (staffVal > visitorVal) {
          // 访客列表的日期比较小
          rowDatas.push({ date: visitor.date, visitor: visitor.count })
          indexV++
          maxCount = Math.max(maxCount, visitor.count)
        } else {
          rowDatas.push({ date: staff.date, staff: staff.count, visitor: visitor.count })
          indexS++
          indexV++
          maxCount = Math.max(maxCount, staff.count, visitor.count)
        }
      }
      // 设置最大值用以不显示小数
      maxCount = Math.ceil(maxCount * 1.1)

      // 返回生成好的图表数据
      return {
        rowDatas: rowDatas,
        maxCount: maxCount
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  $tableTitleHeight:46px;
  .app-container{
    margin-bottom:20px
  }
  .table{
    margin-bottom: 20px;
  }
  .pagination-container{
    margin-bottom: 50px;
  }
  .table-title{
    background-color:rgba(243, 243, 243, 1);
    height: $tableTitleHeight;
    .title-header{
      line-height:$tableTitleHeight;
      color: #606266;
      font-size: 15px;
      i{
        margin-left: 5px;
        margin-right: 5px;
      }
    }
  }
  .edit_btns{
    .edit_btn{
      float:right;
      margin:7px 3px;//为了需要居中显示margin-top和bottom要用$tableTitleHeight减去按钮原高度除以2
    }
  }
</style>
