<template>
  <div v-loading="downloadLoading" class="app-container">
    <addModal ref="exceptionInfoModel" />
    <!--搜索区-->
    <!--    <div style="margin-left: 10px">-->
    <el-input
      v-model="form.name"
      placeholder="请输入姓名"
      class="margin-left input"
    />
    <el-input
      v-model="form.phone"
      placeholder="请输入手机号"
      class="margin-left input"
    />
    <el-input
      v-model="form.idNumber"
      placeholder="请输入身份证号"
      class="margin-left input"
    />
    <el-input
      v-model="form.cardIdEx"
      placeholder="请输入卡号"
      class="margin-left input"
    />
    <el-select
      v-model="form.peopleType"
      class="margin-left input"
      filterable
      clearable
      placeholder="请选择人员类型"
    >
      <el-option
        v-for="item in userTypeList"
        :key="item.code"
        :label="item.desc"
        :value="item.code"
      />
    </el-select>
    <el-select
      v-model="form.status"
      class="margin-left input"
      filterable
      clearable
      placeholder="请选择在离场"
    >
      <el-option
        v-for="item in statusList"
        :key="item.code"
        :label="item.desc"
        :value="item.code"
      />
    </el-select>
    <el-date-picker
      v-model="form.startTimeToEndTime"
      type="datetimerange"
      class="margin-left"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
    />
    <el-select
      v-model="form.sn"
      filterable
      clearable
      placeholder="请选择设备编号"
      class="margin-left input"
    >
      <el-option
        v-for="(item, index) in machineList"
        :key="index"
        :label="item.sn"
        :value="item.sn"
      />
    </el-select>
    <el-select
      v-model="form.sn"
      filterable
      clearable
      placeholder="请选择设备地点"
      class="margin-left input"
    >
      <el-option
        v-for="(item, index) in machineList"
        :key="index"
        :label="item.name"
        :value="item.sn"
      />
    </el-select>
    <el-button
      type="primary"
      icon="el-icon-search"
      class="margin-left"
      @click="query"
    >搜索</el-button>
    <el-tooltip
      class="item"
      effect="dark"
      content="最大支持导出50000条数据！"
      placement="top-start"
    >
      <el-button
        type="primary"
        icon="el-icon-download"
        class="margin-left"
        @click="download"
      >导出记录</el-button>
    </el-tooltip>
    <!--    </div>-->
    <!--主表格-->
    <div v-if="tableData.length>0" class="card-content">
      <div v-for="(item, index) in tableData" :key="index" class="card-content_item">
        <div :class="['corner_markers' , `${item.status == 2?'gray_mark' :'blue_mark'} `]">
          <el-tag
            effect="dark"
            style="border: 1px solid rgba(255, 255, 255, 0.3);background: transparent;color: #fff;"
          >
            {{ item.status == 2 ? '离场' : '在场' }}
          </el-tag>
          <span style="color: rgba(238, 246, 255, 1);font-size: 14px;margin-left: 5px">停留时长：{{ item.countDown }}<!--00:00:00--></span>
        </div>
        <div class="title_item">
          <span class="title">{{ item.name | matchNull }}</span>
          <el-tag
            v-if="item.peopleType == 1"
            effect="dark"
            style="border: 1px solid rgba(194, 231, 176, 1);background: transparent;color: rgba(103, 194, 58, 1);"
          >
            员工
          </el-tag>
          <el-tag
            v-else-if="item.peopleType == 2"
            effect="dark"
            style="border: 1px solid rgba(86, 172, 255, 0.42);background: transparent;color: rgba(64, 158, 255, 1)"
          >
            访客
          </el-tag>
        </div>
        <div class="id_area_item">
          <div class="area_item">
            <span>证件号</span>
            <span>{{ item.idNumber | matchNull }}</span>
          </div>
          <div class="area_item">
            <span>手机号</span>
            <span>{{ item.phone | matchNull }}</span>
          </div>
          <div class="area_item">
            <span>卡号</span>
            <span>{{ item.cardIdEx | matchNull }}</span>
          </div>
        </div>
        <div class="access_record_item">
          <div
            class="item_filed"
            :style="[{ cursor : item.inList.length > 0 && !item.inList[0].status?'pointer' : 'default'}]"
            @click="onViewExceptionInformation('inList',item)"
          >
            <div class="filed_value">
              时间(进)：{{ (item.inList.length>0 ? item.inList[0].passTime :'') | matchNull }}
              <el-tag
                v-if="item.inList.length>0 && !item.inList[0].status"
                effect="dark"
                style="border: 1px solid rgba(255, 228, 232, 1);background: rgba(255, 228, 232, 1);color: rgba(255, 66, 75, 1);margin-left: 10px"
              >
                异常
              </el-tag>
            </div>
            <div class="filed_value">设备(进)：{{ (item.inList.length>0 ? item.inList[0].sn :'') | matchNull }}</div>
            <div class="filed_value">地点(进)：{{ (item.inList.length>0 ? item.inList[0].snName :'') | matchNull }}</div>
          </div>
          <div class="item_img">
            <el-image
              style="width: 62px; height: 62px"
              fit="cover"
              :src="item.inList.length>0 ? item.inList[0].photo :''"
              :preview-src-list="[item.inList.length>0 ? item.inList[0].photo :'']"
            >
              <div slot="error" style="width: 62px;height: 62px;display: flex;justify-content: center;align-items: center;color:#C0C4CC;background-color: #F5F7FA;font-size: 14px">暂无照片</div>
            </el-image>
          </div>
        </div>
        <div class="access_record_item">
          <div
            class="item_filed"
            :style="[{ cursor : item.outList.length > 0 && !item.outList[0].status?'pointer' : 'default'}]"
            @click="onViewExceptionInformation('outList',item)"
          >
            <div class="filed_value">
              时间(出)：{{ (item.outList.length>0 ? item.outList[0].passTime :'') | matchNull }}
              <el-tag
                v-if="item.outList.length>0 && !item.outList[0].status"
                effect="dark"
                style="border: 1px solid rgba(255, 228, 232, 1);background: rgba(255, 228, 232, 1);color: rgba(255, 66, 75, 1);margin-left: 10px"
              >
                异常
              </el-tag>
            </div>
            <div class="filed_value">设备(出)：{{ (item.outList.length>0 ? item.outList[0].sn :'') | matchNull }}</div>
            <div class="filed_value">地点(出)：{{ (item.outList.length>0 ? item.outList[0].snName :'') | matchNull }}</div>
          </div>
          <div class="item_img">
            <el-image
              style="width: 62px; height: 62px"
              fit="cover"
              :src="item.outList.length>0 ? item.outList[0].photo :''"
              :preview-src-list="[item.outList.length>0 ? item.outList[0].photo :'']"
            >
              <div slot="error" style="width: 62px;height: 62px;display: flex;justify-content: center;align-items: center;color:#C0C4CC;background-color: #F5F7FA;font-size: 14px">暂无照片</div>
            </el-image>
          </div>
        </div>
      </div>
    </div>
    <div v-else>
      <el-empty description="暂无数据" />
    </div>
    <!--分页栏-->
    <pagination
      :total="pagination.total"
      :page.sync="pagination.current"
      :limit.sync="pagination.pageSize"
      :page-sizes="pagination.pageSizeOptions"
      :layout="pagination.layout"
      @pagination="handleSizeChange"
    />
  </div>
</template>

<script>
import tableMixins from '@/mixins/tableMixins'
import Pagination from '@/components/Pagination'
import AddModal from './modal/AddModal.vue'
import { parseTime } from '@/utils'
import moment from 'moment'
import { getEntryAndExitStatisticsLogExcel, getEntryAndExitStatisticsPageList } from '@/api/screen_statistics'
import { getFaceDeviceList } from '@/api/old_api_pengwenbing'
moment.locale('zh-cn')

export default {
  components: { Pagination, AddModal },
  filters: {
    matchNull(str) {
      if (!str) {
        return '-'
      } else {
        return str
      }
    }
  },
  mixins: [tableMixins],
  data() {
    return {
      form: {
        'cardIdEx': null,
        'endTime': null,
        'idNumber': null,
        'name': null,
        'peopleType': null,
        'phone': null,
        'sn': null,
        'startTime': null,
        'status': null,
        startTimeToEndTime: null
      },
      areaPreviewList: [],

      machineList: [], // 设备列表下拉
      userTypeList: [
        {
          code: 1,
          desc: '员工'
        },
        {
          code: 2,
          desc: '访客'
        },
        {
          code: 3,
          desc: '其他'
        }
      ], // 人员类型下拉
      statusList: [
        {
          code: 1,
          desc: '在场'
        },
        {
          code: 2,
          desc: '离场'
        }
      ], // 人员类型下拉
      showSearch: false,
      snList: [],
      timer: null,
      downloadLoading: false, // 导出加载
      resultFiled: 'records'
    }
  },
  // 在mounted中调用开启
  mounted() {
    this.getFaceDeviceList()
  },
  // 页面销毁的时候清除定时器
  beforeDestroy() {
    // 清除倒计时
    clearTimeout(this.timer)
    this.timer = null
  },
  methods: {
    initData() {
      this.getTableList()
    },
    // 导出记录
    download() {
      this.$prompt('请输入导出密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false
      })
        .then(async({ value }) => {
          if (value == 'Nqj##361') {
            this.$message({
              type: 'success',
              message: '密码正确,正在下载...'
            })
            this.listLoading = true
            await getEntryAndExitStatisticsLogExcel(this.form).then((res) => {
              var eleLink = document.createElement('a')
              eleLink.style.display = 'none'
              // 字符内容转变成blob地址
              var blob = new Blob([res])
              eleLink.href = URL.createObjectURL(blob)
              eleLink.setAttribute('download', '人员进出统计数据.xlsx')
              // 自动触发点击
              document.body.appendChild(eleLink)
              eleLink.click()
              // 然后移除
              document.body.removeChild(eleLink)
              this.listLoading = false
            })
          } else {
            this.$message({
              type: 'error',
              message: '您输入的密码不正确'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消导出'
          })
        })
    },
    // 获取设备列表-搜索
    getFaceDeviceList() {
      getFaceDeviceList().then((res) => {
        this.machineList = res.data
      })
    },
    // 查看异常情况
    onViewExceptionInformation(typeField, row) {
      if (!row[typeField][0].status) {
        this.$refs.exceptionInfoModel.open(Object.assign({}, { typeField, row }))
      }
    },
    // 获取表格数据
    async getTableList() {
      this.tableLoading = true
      try {
        const result = await getEntryAndExitStatisticsPageList(this.getFilterParams())
        this.setDataList(result.data)
        for (const key in this.tableData) {
          // 开始时间
          const tableItem = this.tableData[key]
          const originalEndTime = tableItem.outList.length > 0 ? moment(tableItem.outList[0].passTime) : ''
          const startTime = tableItem.inList.length > 0 ? moment(tableItem.inList[0].passTime) : ''
          const endTime = originalEndTime || moment()
          if (startTime && startTime !== '') {
            if (moment(startTime).isBefore(endTime)) {
              if (moment().isBefore(endTime)) {
                // 没到截止日期
                this.tableData[key]['countDown'] = this.showTime(moment().diff(startTime, 'seconds'))
              } else {
                // 到截止日期了
                this.tableData[key]['countDown'] = this.showTime(moment(endTime).diff(startTime, 'seconds'))
              }
            } else {
              this.tableData[key]['countDown'] = '-'
            }
          } else {
            this.tableData[key]['countDown'] = '-'
          }
          // 输出结果
          // console.log(`时间差：`, this.tableData[key]['countDown'])
        }
        // 实现倒计时
        this.someEventHandler()
      } catch (e) {
        console.log(e)
      } finally {
        this.tableLoading = false
      }
    },
    // 时间日期转换，将秒数转换成02:20:22形式
    showTime(val) {
      if (val < 60) {
        return '00:' + '00:' + val
      } else {
        const min_total = Math.floor(val / 60) // 分钟
        const sec =
          Math.floor(val % 60) > 9
            ? Math.floor(val % 60)
            : '0' + Math.floor(val % 60) // 余秒
        if (min_total < 60) {
          return '00:' + min_total + ':' + sec
        } else {
          const hour_total =
            Math.floor(min_total / 60) > 9
              ? Math.floor(min_total / 60)
              : '0' + Math.floor(min_total / 60) // 小时数
          const min =
            Math.floor(min_total % 60) > 9
              ? Math.floor(min_total % 60)
              : '0' + Math.floor(min_total % 60) // 余分钟
          return hour_total + ':' + min + ':' + sec
        }
      }
    },
    // 获取筛选信息
    query() {
      this.form.startTime = null
      this.form.endTime = null
      if (this.form.startTimeToEndTime && this.form.startTimeToEndTime.length > 0) {
        this.form.startTime = parseTime(this.form.startTimeToEndTime[0], '{y}-{m}-{d} {h}:{i}:{s}')
        this.form.endTime = parseTime(this.form.startTimeToEndTime[1], '{y}-{m}-{d} {h}:{i}:{s}')
      }
      this.clearPageParams()
      this.getTableList()
    },
    // 增加筛选条件
    transformFilterForm() {
      return this.form
    },
    handleCreate() {
      this.$refs.exceptionInfoModel.open()
    },
    handleUpdate(row) {
      console.log(row)
      this.$refs.exceptionInfoModel.open(Object.assign({}, row))
    },
    startCountDown() {
      // 定义一个倒计时setInterval
      this.timer = setInterval(() => {
        // finishedCount 计算页面倒计时有几个结束了
        let finishedCount = 0
        for (const key in this.tableData) {
          // 开始时间
          const tableItem = this.tableData[key]
          const originalEndTime = tableItem.outList.length > 0 ? moment(tableItem.outList[0].passTime) : ''
          const startTime = tableItem.inList.length > 0 ? moment(tableItem.inList[0].passTime) : ''
          const endTime = originalEndTime || moment()
          // 开始时间和结束时间都有不需要继续计时
          if (startTime && startTime !== '' && originalEndTime && originalEndTime !== '') {
            finishedCount++
          }
          if (startTime && startTime !== '') {
            // 开始时间在结束时间之前
            if (moment(startTime).isBefore(endTime)) {
              if (moment().isBefore(endTime)) {
              // 没到截止日期
                this.tableData[key]['countDown'] = this.showTime(moment().diff(startTime, 'seconds'))
              } else {
              // 到截止日期了
                this.tableData[key]['countDown'] = this.showTime(moment(endTime).diff(startTime, 'seconds'))
              }
            } else {
              // 开始时间在结束时间之后 有问题 不需要继续计时
              finishedCount++
              this.tableData[key]['countDown'] = '-'
            }
          } else {
            // 开始时间没有 有问题 不需要继续计时
            finishedCount++
            this.tableData[key]['countDown'] = '-'
          }
          // 输出结果
          // console.log(`时间差：`, this.tableData[key]['countDown'])
        }
        // console.log(finishedCount)
        this.$forceUpdate()
        if (finishedCount === this.tableData.length) { // 如果所有计时器都完成了，则清除定时器
          clearInterval(this.timer)
        }
      }, 1000)
    },

    someEventHandler() {
      // 清除旧的定时器
      clearInterval(this.timer)
      // 开启新的倒计时
      this.startCountDown()
    }
  }
}
</script>
<style lang="scss" >
.card-content {
  .el-tag {
    height: 26px !important;
    line-height: 26px !important;
  }
}
</style>
<style lang="scss" scoped>
.card-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
  margin-left: -10px;
  &_item {
    width: 390px;
    min-height: 290px;
    border: 1px solid rgba(227, 233, 248, 1);
    border-radius: 6px;
    margin: 10px;
    padding-bottom: 10px;
    position: relative;
    .corner_markers {
      width: 186px;
      height: 50px;
      position: absolute;
      background-size: 100% 100%;
      background-repeat: no-repeat;
      background-position: center bottom;
      top: -4px;
      right: -4px;
      padding: 5px;
    }
    .gray_mark {
      background-image: url("../../assets/gray_bg.png");
    }
    .blue_mark {
      background-image: url("../../assets/blue_bg.png");
    }

    .title_item {
      display: flex;
      align-items: center;
      padding-top: 16px;
      padding-left: 20px;
      box-sizing: content-box;
      .title {
        font-size: 20px;
        font-weight: bold;
        line-height: 30px;
        text-align: left;
        color: rgba(51, 51, 51, 1);
        padding-right: 10px;
      }
    }

    .id_area_item {
      margin: 12px 20px;
      width: calc(100% - 40px);
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;

      .area_item {
        color: rgba(51, 51, 51, 1);
        font-size: 14px;
        font-weight: 400;
        line-height: 20px;
        height: 20px;
        text-align: left;
        span:first-child {
          min-width: 44px;
          text-align-last: justify;
          display: inline-block;
          margin-right: 10px;
        }
        &:nth-child(odd) {
          width: 200px;
        }
        &:nth-child(even) {
          width: 140px;
        }
      }

    }

    .access_record_item {
      margin: 0px 20px;
      padding: 0 10px;
      width: calc(100% - 40px);
      border: 1px solid rgba(227, 241, 255, 1);
      background: rgba(227, 238, 255, 0.34);
      height: 80px;
      border-radius: 6px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;

      .item_filed {
        font-size: 14px;
        .filed_value {
          height: 20px;
          line-height: 20px;
          font-weight: 400;
          color: rgba(118, 140, 186, 1);
          &:first-child {
            font-weight: 500;
            color: rgba(28, 149, 255, 1);
          }
        }
      }

      .item_img {

      }

      &:last-child {
        margin-top: 5px;
      }
    }
  }
}
.margin-left {
  margin: 10px 0 0 10px;
}
.input {
  width: 200px;
}
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
  background-color: #f1f2f5;
}

::-webkit-scrollbar-thumb {
  background-color: #bfc6d4;
  border-radius: 10px;
}
::-webkit-scrollbar-track {
  background-color: transparent;
}
.el-icon-s-platform,
.el-icon-search {
  font-weight: 600;
}
</style>
