<template>
  <div v-loading="downloadLoading" class="app-container">
    <!--搜索区-->
    <el-input
      v-model="page.data.name"
      placeholder="请输入姓名"
      class="margin-left input"
    />
    <el-input
      v-model="page.data.phone"
      placeholder="请输入手机号"
      class="margin-left input"
    />
    <el-input
      v-model="page.data.idNumber"
      placeholder="请输入身份证号"
      class="margin-left input"
    />
    <el-select
      v-if="!checkRole([99])"
      v-model="page.data.username"
      filterable
      clearable
      placeholder="请选择账号"
      class="margin-left input"
    >
      <el-option
        v-for="item in user_list"
        :key="item.id"
        :label="item.username"
        :value="item.username"
      />
    </el-select>
    <el-select
      v-model="page.data.deviceSn"
      filterable
      clearable
      placeholder="请选择设备编号"
      class="margin-left input"
    >
      <el-option
        v-for="item in machine_list"
        :key="item.sn"
        :label="item.sn"
        :value="item.sn"
      />
    </el-select>
    <el-select
      v-model="page.data.deviceSn"
      filterable
      clearable
      placeholder="请选择设备地点"
      class="margin-left input"
    >
      <el-option
        v-for="item in machine_list"
        :key="item.sn"
        :label="item.name"
        :value="item.sn"
      />
    </el-select>
    <el-select
      v-if="checkRole([1, 2])"
      v-model="page.data.faceDeviceTypeId"
      filterable
      clearable
      placeholder="请选择设备类型"
      class="margin-left input"
    >
      <el-option
        v-for="item in machine_type_list"
        :key="item.faceDeviceTypeId"
        :label="item.name"
        :value="item.faceDeviceTypeId"
      />
    </el-select>
    <el-select
      v-if="!checkRole([99])"
      v-model="page.data.provinceId"
      filterable
      clearable
      placeholder="请选择省份"
      class="margin-left input"
      :disabled="checkRole([2, 3, 4, 5])"
      @change="chooseProvinceSearch"
    >
      <el-option
        v-for="item in province_list_search"
        :key="item.areaCodeId"
        :label="item.name"
        :value="item.areaCodeId"
      />
    </el-select>
    <el-select
      v-if="!checkRole([99])"
      v-model="page.data.cityId"
      filterable
      clearable
      placeholder="请选择城市"
      class="margin-left input"
      :disabled="checkRole([4, 5])"
      @change="chooseCitySearch"
    >
      <el-option
        v-for="item in city_list_search"
        :key="item.areaCodeId"
        :label="item.name"
        :value="item.areaCodeId"
      />
    </el-select>
    <el-select
      v-if="!checkRole([99])"
      v-model="page.data.areaId"
      filterable
      clearable
      placeholder="请选择区域"
      class="margin-left input"
      :disabled="checkRole([5])"
    >
      <el-option
        v-for="item in area_list_search"
        :key="item.areaCodeId"
        :label="item.name"
        :value="item.areaCodeId"
      />
    </el-select>
    <el-select
      v-model="page.data.twStatus"
      filterable
      clearable
      placeholder="请选择体温是否异常"
      class="margin-left input"
    >
      <el-option
        v-for="item in tw_list"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      />
    </el-select>
    <el-select
      v-model="page.data.pass"
      filterable
      clearable
      placeholder="请选择进出门"
      class="margin-left input"
    >
      <el-option
        v-for="item in into_door_list"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      />
    </el-select>
    <el-select
      v-model="page.data.verifyType"
      filterable
      clearable
      placeholder="请选择验证类型"
      class="margin-left input"
    >
      <el-option
        v-for="item in authentication_type_list"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      />
    </el-select>
    <el-select
      v-model="page.data.rightno"
      filterable
      clearable
      placeholder="请选择人员类型"
      class="margin-left input"
    >
      <el-option
        v-for="item in Personnel_type_list"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      />
    </el-select>
    <el-input
      v-model="page.data.xcInfo"
      placeholder="请输入行程信息"
      class="margin-left input"
    />

    <el-date-picker
      v-model="page.data.startTime"
      type="datetime"
      placeholder="选择通行开始时间"
      value-format="yyyy-MM-dd HH:mm:ss"
      class="margin-left"
    />
    <el-date-picker
      v-model="page.data.endTime"
      type="datetime"
      placeholder="选择通行结束时间"
      value-format="yyyy-MM-dd HH:mm:ss"
      class="margin-left"
    />
    <el-select
      v-model="page.data.status"
      filterable
      clearable
      placeholder="请选择状态"
      class="margin-left input"
    >
      <el-option label="有效" :value="true" />
      <el-option label="失效" :value="false" />
    </el-select>
    <el-select
      v-model="page.data.reasonType"
      filterable
      clearable
      placeholder="请选择原因"
      class="margin-left input"
    >
      <el-option
        v-for="item in reasonType_list"
        :key="item.code"
        :label="item.desc"
        :value="item.code"
      />
    </el-select>
    <template v-if="checkRole([5])">
      <span v-for="(item, index) in page.data.contents" :key="index">
        <el-date-picker
          v-if="item.customType === '日期'"
          v-model="item.customNameVal"
          type="datetime"
          class="margin-left input"
          :placeholder="item.prompt"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        />
        <el-time-picker
          v-if="item.customType === '时间'"
          v-model="item.customNameVal"
          class="margin-left input"
          :picker-options="{
            selectableRange: '00:00:00 - 23:59:59',
          }"
          :placeholder="item.prompt"
          value-format="HH:mm"
          format="HH:mm"
        />
        <el-select
          v-if="item.customType === '下拉选择'"
          v-model="item.customNameVal"
          class="margin-left input"
          filterable
          clearable
          :placeholder="item.prompt"
        >
          <el-option
            v-for="item in item.configurationOption"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
        <el-input
          v-if="item.customType === '文本'"
          v-model="item.customNameVal"
          class="margin-left input"
          :placeholder="item.prompt"
        />
      </span>
    </template>
    <el-button
      type="primary"
      icon="el-icon-search"
      class="margin-left"
      @click="fetchData"
    >搜索</el-button>
    <el-tooltip
      class="item"
      effect="dark"
      content="最大支持导出50000条数据！"
      placement="top-start"
    >
      <el-button
        v-if="isOut === 1"
        type="primary"
        icon="el-icon-download"
        class="margin-left"
        @click="download"
      >导出记录</el-button>
    </el-tooltip>

    <el-tooltip
      class="item"
      effect="dark"
      content="最大支持导出500条数据！"
      placement="top-start"
    >
      <el-button
        v-if="isOut === 1"
        type="primary"
        icon="el-icon-download"
        class="margin-left"
        @click="steakPhoto(500)"
      >导出照片</el-button>
    </el-tooltip>

    <el-button
      type="primary"
      :icon="!isUpdate ? 'el-icon-refresh-left' : 'el-icon-loading'"
      class="margin-left"
      @click="isUpdate ? stopUpdate() : autoUpdate()"
    >{{ !isUpdate ? "打开自动刷新" : "关闭自动刷新" }}</el-button>
    <!--主表格-->
    <el-table
      ref="table_form"
      v-loading="listLoading"
      class="table"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="序号" align="center" width="80px">
        <template slot-scope="scope">
          {{ indexMethod(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column label="设备编号" align="center">
        <template slot-scope="scope">
          {{ scope.row.deviceSn | matchNull }}
        </template>
      </el-table-column>
      <el-table-column v-if="checkRole([1, 2])" label="所属账号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备地点" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deviceName | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.faceDeviceTypeName | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="checkRole([1, 2])"
        label="设备品牌名称"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.thirdPartyName | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" align="center">
        <template slot-scope="scope">
          {{ scope.row.name | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="现场照片" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            fit="cover"
            :src="scope.row.photo"
            :preview-src-list="[scope.row.photo]"
          >
            <div slot="error" style="width: 100px;height: 100px;display: flex;justify-content: center;align-items: center;color:#C0C4CC;background-color: #F5F7FA;">加载失败</div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="证件号" align="center">
        <template slot-scope="scope">
          {{ scope.row.cardid }}
        </template>
      </el-table-column>
      <el-table-column label="卡号" align="center">
        <template slot-scope="scope">
          {{ scope.row.cardidex }}
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="进/出" align="center">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.outType === 0"
            type="success"
            effect="light"
          >通用</el-tag>
          <el-tag
            v-else-if="scope.row.outType === 1"
            type="primary"
            effect="plain"
          >进门</el-tag>
          <el-tag
            v-else-if="scope.row.outType === 2"
            type="primary"
            effect="dark"
          >出门</el-tag>
          <el-tag v-else>其它</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="验证类型" align="center">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.verifyType === 0"
            type="primary"
            plain
          >人脸</el-tag>
          <el-tag
            v-else-if="scope.row.verifyType === 1"
            type="primary"
            plain
          >IC卡</el-tag>
          <el-tag
            v-else-if="scope.row.verifyType === 2"
            type="primary"
            plain
          >身份证</el-tag>
          <el-tag
            v-else-if="scope.row.verifyType === 3"
            type="primary"
            plain
          >二维码</el-tag>
          <el-tag
            v-else-if="scope.row.verifyType === 4"
            type="primary"
            plain
          >远程</el-tag>
          <el-tag
            v-else-if="scope.row.verifyType === 6"
            type="primary"
            plain
          >IC卡+人脸</el-tag>
          <el-tag v-else>其它</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="人员类型" align="center">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.rightno === 104"
            type=""
            effect="plain"
          >访客</el-tag>
          <el-tag
            v-else-if="scope.row.rightno === 105"
            type="success"
            effect="plain"
          >员工</el-tag>
          <el-tag
            v-else-if="scope.row.rightno === 101"
            type="info"
            effect="plain"
          >黑名单</el-tag>
          <el-tag v-else type="info" effect="plain">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="通行时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.faceTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.status"
            effect="dark"
            style="border: 1px solid #409EFF;background: #fff;color: #409EFF;"
          >
            有效
          </el-tag>
          <el-tag
            v-else
            effect="dark"
            style="border: 1px solid #E7EBF4;background: #fff;color: #A8AEBC;"
          >
            失效
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="原因" align="center">
        <template slot-scope="scope">
          {{ getReasonName(scope.row.reasonType) }}
        </template>
      </el-table-column>
      <!-- 自定义字段 -->
      <template v-if="addCustomList.length > 0">
        <el-table-column
          v-for="(item, index) in addCustomList"
          :key="index"
          align="center"
          :label="item.customName"
        >
          <template slot-scope="scope">
            <el-image
              v-if="item.customType === '图片'"
              style="width: 70px; height: 70px"
              fit="cover"
              :src="
                scope.row.contents.length > 0
                  ? scope.row.contents[index].customNameVal
                  : ''
              "
              :preview-src-list="[
                scope.row.contents.length > 0
                  ? scope.row.contents[index].customNameVal
                  : '',
              ]"
            >
              <div slot="error" class="image-slot">暂无照片</div>
            </el-image>
            <span v-else>{{
              scope.row.contents.length > 0
                ? scope.row.contents[index].customNameVal
                : ""
            }}</span>
          </template>
        </el-table-column>
      </template>

      <el-table-column
        label="操作区"
        align="center"
        fixed="right"
        width="100px"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="searchDetails(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页栏-->
    <pagination
      :total="total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="fetchData"
    />
    <!-- 详情对话框 -->
    <detailsDialog
      :dialog-table-visible="dialogTableVisible"
      type="pass_records"
      :visit-to-jet-list="visitToJetList"
      :row="row"
      @dialog="dialogTableVisible = false"
    />
  </div>
</template>

<script>
import detailsDialog from '@/components/DialogDetails/index.vue'

import {
  doGetFaceServerLog,
  downloadFaceLog,
  getFaceDeviceList, getFaceLogStatusEnumSearch,
  getMachineCompanyListSearch,
  getMachineTypeListSearch
} from '@/api/old_api_pengwenbing'
import Pagination from '@/components/Pagination'
import { checkRole } from '@/utils/checkRole'
import {
  getArea,
  getCity,
  getProvince,
  getUserListSearch,
  getContext,
  getContextByFaceLog,
  getUserListFrom,
  getContextById
} from '@/api/user_manage'
import { parseTime } from '@/utils'
import { downloadPhotosPassRecords } from '@/utils/steakPhoto' // secondary package based on el-pagination

export default {
  components: { Pagination, detailsDialog },
  filters: {
    matchNull(str) {
      if (!str) {
        return '-'
      } else {
        return str
      }
    },
    aAecimal(str) {
      return (str = str.slice(0, 4))
    }
  },
  data() {
    return {
      // 主表格&主表格加载状态
      list: [],
      listLoading: true,
      downloadLoading: false, // 导出加载
      // 分页参数
      page: {
        data: {
          username: null,
          name: null,
          idNumber: null,
          phone: null,
          deviceSn: null,
          startTime: '',
          endTime: '',
          provinceId: null,
          cityId: null,
          areaId: null,
          hsStatus: null,
          status: true, // 状态
          reasonType: null, // 原因
          faceDeviceTypeId: null,
          pass: null,
          verifyType: null,
          rightno: null,
          contents: null // 自定义字段
        },
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      // 原因下拉
      reasonType_list: [],
      // 账号列表_搜索
      user_list: [],
      // 设备列表_搜索
      machine_list: [],
      // 设备品牌列表_搜索
      machine_company_list: [],
      // 设备类型列表_搜索
      machine_type_list: [],
      // 体温结果列表_搜索
      tw_list: [
        { id: '1', name: '正常' },
        { id: '2', name: '异常' },
        { id: '3', name: '未知' }
      ],
      // 进出门_搜索
      into_door_list: [
        { id: 0, name: '不限' },
        { id: 1, name: '进门' },
        { id: 2, name: '出门' }
      ],
      // 验证类型
      authentication_type_list: [
        { id: 0, name: '人脸' },
        // { id: "1", name: "IC卡" },
        { id: 2, name: '身份证' },
        { id: '3', name: '二维码' }
      ],
      // 人员类型
      Personnel_type_list: [
        { id: 104, name: '访客' },
        { id: 105, name: '员工' },
        { id: 301, name: '预约人员' }
      ],
      // 省市县列表_搜索
      province_list_search: [],
      city_list_search: [],
      area_list_search: [],
      // 是否可以导出
      isOut: this.$store.getters.isOut,
      // 是否打开自动更新
      isUpdate: '',
      // 信息详情弹框
      dialogVisible: false,
      // 信息详情
      dialogContent: '',
      dialogTableVisible: false,
      // 访客机数据
      visitToJetList: {},
      // 自定义字段模板
      addCustomList: [],
      row: {}
    }
  },
  computed: {},
  created() {
    this.page_copy = JSON.parse(JSON.stringify(this.page))
    this.fetchData()
    this.matchAutoUpdate()
    this.getUserListSearch()
    this.getFaceDeviceList()
    this.getMachineTypeListSearch()
    this.getFaceLogStatusEnumSearch()
    this.getAddressListSearch(1)
    if (checkRole([2, 3])) {
      this.getAddressListSearch(2, this.$store.getters.provinceId)
      this.page.data.provinceId = this.$store.getters.provinceId
    } else if (checkRole([4])) {
      this.getAddressListSearch(2, this.$store.getters.provinceId)
      this.page.data.provinceId = this.$store.getters.provinceId
      this.getAddressListSearch(3, this.$store.getters.cityId)
      this.page.data.cityId = this.$store.getters.cityId
    } else if (checkRole([5])) {
      this.getAddressListSearch(2, this.$store.getters.provinceId)
      this.page.data.provinceId = this.$store.getters.provinceId
      this.getAddressListSearch(3, this.$store.getters.cityId)
      this.page.data.cityId = this.$store.getters.cityId
      this.page.data.areaId = this.$store.getters.areaId
      this.getContextById(this.$store.getters.adminId)
    }
  },
  beforeDestroy() {
    var isUpdate = localStorage.getItem('isUpdate')
    if (isUpdate) {
      clearInterval(isUpdate)
    }
  },
  methods: {
    getReasonName(str) {
      if (!str) {
        return ''
      } else {
        console.log(this.reasonType_list)
        const index = (this.reasonType_list || []).findIndex(v => v.code == str)
        return index > -1 ? this.reasonType_list[index]?.desc || '' : ''
      }
    },
    // 查询权限
    checkRole,
    // 获取列表数据
    fetchData(isUpdate = false) {
      this.listLoading = true
      doGetFaceServerLog(this.page).then((res) => {
        this.list = res.data.list
        this.total = res.data.total
        this.listLoading = false
      })
    },
    // 查询自定义字段详情
    searchDetails(row) {
      this.row = row
      const data = {
        logId: row.logId,
        type: row.rightno
      }
      getUserListFrom(data).then((res) => {
        this.visitToJetList = res.data
        this.dialogTableVisible = true
      })
    },
    // 获取自定义字段模板
    getContextById(adminId) {
      getContextById(adminId).then((res) => {
        this.addCustomList = res.data
        this.page.data.contents = res.data
        // console.log(this.page.data.contents);
      })
    },
    // 获取设备列表-搜索
    getFaceDeviceList() {
      getFaceDeviceList().then((res) => {
        this.machine_list = res.data
      })
    },
    // 设备品牌列表-搜索
    getMachineCompanyListSearch() {
      getMachineCompanyListSearch().then((res) => {
        this.machine_company_list = res.data
      })
    },
    getFaceLogStatusEnumSearch() {
      getFaceLogStatusEnumSearch().then((res) => {
        this.reasonType_list = res.data
      })
    },
    // 获取设备类型列表-搜索
    getMachineTypeListSearch() {
      getMachineTypeListSearch().then((res) => {
        this.machine_type_list = res.data
      })
    },
    // 获取账号列表数据_搜索
    getUserListSearch() {
      getUserListSearch().then((res) => {
        this.user_list = res.data
      })
    },
    // 获得省市县列表_搜索
    getAddressListSearch(type, code) {
      switch (type) {
        case 1:
          getProvince().then((res) => {
            this.province_list_search = res.data
          })
          break
        case 2:
          getCity(code).then((res) => {
            this.city_list_search = res.data
          })
          break
        case 3:
          getArea(code).then((res) => {
            this.area_list_search = res.data
          })
          break
        default:
          break
      }
    },
    // 选择省份_搜索
    chooseProvinceSearch(e) {
      this.city_list_search = []
      this.page.data.cityId = ''
      this.page.data.cityName = ''
      this.area_list_search = []
      this.page.data.areaId = ''
      this.page.data.areaName = ''
      this.getAddressListSearch(2, e)
      // this.getTagList(e);
    },
    // 选择市_搜索
    chooseCitySearch(e) {
      this.area_list = []
      this.page.data.areaId = ''
      this.page.data.areaName = ''
      this.getAddressListSearch(3, e)
    },
    // 导出记录
    download() {
      this.$prompt('请输入导出密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false
      })
        .then(({ value }) => {
          if (value == 'Nqj##361') {
            this.$message({
              type: 'success',
              message: '密码正确,正在下载...'
            })
            this.downloadLoading = true
            downloadFaceLog(this.page.data).then((res) => {
              window.location.href = res.data
              this.downloadLoading = false
            })
          } else {
            this.$message({
              type: 'error',
              message: '您输入的密码不正确'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消导出'
          })
        })
    },
    // 批量导出图片-带参数导出入口-BETA $1 查询参数  $2多少条
    steakPhoto(number) {
      downloadPhotosPassRecords(this.page, number)
    },
    // 打开自动更新
    autoUpdate() {
      this.isUpdate = setInterval(() => {
        this.fetchData(true)
      }, 60000)
      localStorage.setItem('isUpdate', this.isUpdate)
    },
    // 关闭自动更新
    stopUpdate() {
      clearInterval(this.isUpdate)
      localStorage.setItem('isUpdate', '')
      this.isUpdate = ''
    },
    // 检测上次自动更新状态
    matchAutoUpdate() {
      var isUpdate = localStorage.getItem('isUpdate')
      if (isUpdate) {
        clearInterval(isUpdate)
        this.autoUpdate()
      }
    },
    // 返回列表序号
    indexMethod(index) {
      return (this.page.pageNum - 1) * this.page.pageSize + index + 1
    }
  }
}
</script>
<style scoped>
.table {
  margin-top: 15px;
}
.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.margin-left {
  margin: 10px 0 0 10px;
}
.input {
  width: 150px;
}
</style>
