<template>
  <div class="register-container">
    <div class="page-header">
      <!-- <span>统计：</span> -->
      <el-input
        size="small"
        class="filter-item"
        style="width: 100px; opacity: 0; pointer-events: none"
        ref="hideInput"
      />
      <span>
        总数：
        <span style="color: #2892f0">{{ sendNum }}</span>
        张
      </span>
      <span>
        未收回：
        <span style="color: #f5a623">{{ receiveNum }}</span>
        张
      </span>
      <el-button size="mini" type="primary" @click="moreVisitors">查看更多</el-button>
      <el-button size="mini" type="warning" @click="readMe">操作指导</el-button>
    </div>
    <div class="page-content">
      <div class="content-item entry">
        <div class="title">
          <span class="title-line"></span>
          <img
            class="title-icon entry-icon"
            :src="require('@/assets/images/visitor/icon_visitor.png')"
          />
          <span>进站发卡</span>
          <!-- <el-button size="mini" type="primary" @click="readIdCard">点击开始读卡</el-button> -->
        </div>
        <div class="content-main">
          <el-steps direction="vertical" :space="400" :active="stepActive">
            <el-step title="刷身份证"></el-step>
            <el-step title="刷卡"></el-step>
            <el-step title="选取人员类型"></el-step>
          </el-steps>
          <div class="form-box">
            <el-form
              ref="formEntry"
              :rules="rules"
              :model="entryData"
              size="small"
              label-width="100px"
            >
              <div class="person-info">
                <div class="info-box">
                  <el-form-item label="姓名" prop="name">
                    <el-input
                      v-model="entryData.name"
                      size="small"
                      class="filter-item"
                      style="width: 280px"
                      disabled
                    />
                  </el-form-item>
                  <el-form-item label="性别" prop="sex">
                    <el-input
                      v-model="entryData.sex"
                      size="small"
                      class="filter-item"
                      style="width: 280px"
                      disabled
                    />
                  </el-form-item>
                  <el-form-item label="年龄" prop="age">
                    <el-input
                      v-model="entryData.age"
                      size="small"
                      class="filter-item"
                      style="width: 280px"
                      disabled
                    />
                  </el-form-item>
                  <el-form-item label="上次来访时间" prop="lastDate">
                    <el-input
                      v-model="entryData.lastDate"
                      size="small"
                      class="filter-item"
                      style="width: 280px"
                      disabled
                    />
                  </el-form-item>
                </div>
                <div class="photo-box">
                  <img :src="entryPhotoPath" alt="" />
                </div>
              </div>
              <div class="card-info">
                <el-form-item label="卡号" prop="labelMAC">
                  <el-input
                    v-model="entryData.labelMAC"
                    size="small"
                    class="filter-item"
                    style="width: 280px"
                    :validate-event="false"
                    disabled
                  />
                </el-form-item>
              </div>
              <div class="type-box">
                <el-form-item label="人员类型" prop="type">
                  <el-select
                    v-model="entryData.type"
                    size="small"
                    class="filter-item"
                    style="width: 280px"
                    :disabled="stepActive != 3"
                    :validate-event="false"
                    clearable
                  >
                    <el-option
                      v-for="item of typeArr"
                      :key="item.id"
                      :label="item.typeName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-form>
            <div class="btn-box">
              <el-button
                type="primary"
                icon="el-icon-thumb"
                id="entrySaveBtn"
                @click="handleSaveEntry"
              >
                提交
              </el-button>
              <el-button
                type="success"
                icon="el-icon-refresh-right"
                id="entryResetBtn"
                @click="handleResetEntry"
              >
                重置
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="content-item out">
        <div class="title">
          <span class="title-line"></span>
          <img
            class="title-icon out-icon"
            :src="require('@/assets/images/visitor/icon_visitor.png')"
          />
          <span>出站收卡</span>
        </div>
        <div class="content-main">
          <el-steps direction="vertical" :space="400" :active="1" finish-status="success">
            <el-step title="身份证信息"></el-step>
            <el-step title="卡片信息"></el-step>
            <el-step title="人员类型"></el-step>
          </el-steps>
          <div class="form-box">
            <el-form ref="formOut" :model="outData" size="small" label-width="100px">
              <div class="person-info">
                <div class="info-box">
                  <el-form-item label="姓名" prop="name">
                    <el-input
                      v-model="outData.name"
                      size="small"
                      class="filter-item"
                      style="width: 280px"
                      disabled
                    />
                  </el-form-item>
                  <el-form-item label="性别" prop="sex">
                    <el-input
                      v-model="outData.sex"
                      size="small"
                      class="filter-item"
                      style="width: 280px"
                      disabled
                    />
                  </el-form-item>
                  <el-form-item label="年龄" prop="age">
                    <el-input
                      v-model="outData.age"
                      size="small"
                      class="filter-item"
                      style="width: 280px"
                      disabled
                    />
                  </el-form-item>
                  <el-form-item label="进站时间" prop="entryTime">
                    <el-input
                      v-model="outData.entryTime"
                      size="small"
                      class="filter-item"
                      style="width: 280px"
                      disabled
                    />
                  </el-form-item>
                </div>
                <div class="photo-box">
                  <img :src="outPhotoPath" alt="" />
                </div>
              </div>
              <div class="card-info">
                <el-form-item label="卡号" prop="labelMAC">
                  <el-input
                    v-model="outData.labelMAC"
                    size="small"
                    class="filter-item"
                    style="width: 280px"
                    disabled
                  />
                </el-form-item>
              </div>
              <div class="type-box">
                <el-form-item label="人员类型" prop="type">
                  <el-input
                    v-model="outData.type"
                    size="small"
                    class="filter-item"
                    style="width: 280px"
                    disabled
                  />
                </el-form-item>
              </div>
            </el-form>
            <div class="btn-box">
              <el-button type="primary" icon="el-icon-thumb" id="outSaveBtn" @click="handleSaveOut"
                >提交</el-button
              >
              <el-button
                type="success"
                icon="el-icon-refresh-right"
                id="outResetBtn"
                @click="handleResetOut"
              >
                重置
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <scanner-or-reader :enable="true" @output="handleReaderOut" />
    <id-card-reader :enable="enable" @output="readIdCard" />
  </div>
</template>

<script>
import ScannerOrReader from '@/components/ScannerOrReader'
import IdCardReader from '@/components/IdCardReader'
import { initData, uploadBase64 } from '@/api/data'
import Dayjs from 'dayjs'
export default {
  name: 'register',
  components: { ScannerOrReader, IdCardReader },
  data() {
    return {
      sendNum: 20,
      receiveNum: 10,
      entryData: {
        id: '',
        name: '',
        age: '',
        sex: '',
        idNumber: '',
        lastDate: '',
        labelMAC: '',
        labelId: '',
        type: '',
        photoPath: '',
        oneKeyAlarm: true,
      },
      outData: {
        id: '',
        name: '',
        age: '',
        sex: '',
        idNumber: '',
        entryTime: '',
        labelMAC: '',
        type: '',
        labelId: '',
        photoPath: '',
        oneKeyAlarm: true,
      },
      rules: {
        labelMAC: [{ required: true, message: '卡号不能为空' }],
        type: [{ required: true, message: '人员类型不能为空' }],
      },
      fullLoading: null,
      stepActive: 1,
      personDisabled: true,
      typeArr: [],
      rfid: '',
      idCardData: {},
      enable: false,
    }
  },
  computed: {
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
    entryPhotoPath() {
      if (this.entryData.photoPath) {
        if (this.entryData.photoPath.startsWith('data:image')) {
          return this.entryData.photoPath
        } else {
          return this.VUE_APP_BASE_API + this.entryData.photoPath
        }
      } else {
        if (this.$route.query?.theme === 'green') {
          return '/static/images/img_head_bg1.png'
        }
        return '/static/images/default_0.png'
      }
    },
    outPhotoPath() {
      if (this.outData.photoPath) {
        if (this.outData.photoPath.startsWith('data:image')) {
          return this.outData.photoPath
        } else {
          return this.VUE_APP_BASE_API + this.outData.photoPath
        }
      } else {
        if (this.$route.query?.theme === 'green') {
          return '/static/images/img_head_bg1.png'
        }
        return '/static/images/default_0.png'
      }
    },
  },
  created() {
    this.getPersonType()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.hideInput.focus() //强制获取焦点
      if (!this.enable) this.enable = true
    })
  },
  beforeDestroy() {
    if (this.enable) this.enable = false
  },
  methods: {
    //操作说明
    readMe() {
      window.open('/static/pdf/收发卡操作说明.pdf')
    },
    //查看更多跳转
    moreVisitors() {
      if (!!this.$route.query?.theme) {
        this.$router.push({
          path: '/visitor/visitors',
          query: { theme: this.$route.query.theme },
        })
      } else {
        this.$router.push({
          path: '/visitor/visitors',
        })
      }
    },
    // 读取身份证
    readIdCard(data) {
      // data = {
      //   code: '0',
      //   name: '冯利鹏',
      //   sex: '男',
      //   born: '19890326',
      //   cardno: '142731198903262434',
      //   photobase64:
      //     ' ',
      // }
      console.log(data)
      this.fullLoading = this.$loading({
        text: '身份证读取中',
        lock: true,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        if (data.code === '0') {
          this.idCardData = data
          this.GetPersonByIdCard()
        } else {
          this.$message.warning('读取身份证失败')
          this.fullLoading.close()
          this.stepActive = 1
        }
      }, 1000)
    },
    // 读取rfid卡
    handleReaderOut(code) {
      this.fullLoading = this.$loading({
        text: '读取中',
        lock: true,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        if (!!code) {
          this.rfid = code
          this.fullLoading.close()
          this.GetPersonByLabelRFID()
        }
      }, 1000)
    },
    // 获取人员类型
    async getPersonType() {
      try {
        const res = await initData('system/personType/getListJson', {})
        this.typeArr = res.data?.content || []
      } catch (err) {
        console.log(err)
      }
    },
    // 重置发卡
    handleResetEntry(evt) {
      for (const key in this.entryData) {
        this.$set(this.entryData, key, '')
      }
      this.$refs.formEntry.resetFields()
      this.stepActive = 1
      this.idCardData = {}
      evt && this.buttonBlur(evt)
    },
    // 重置收卡
    handleResetOut(evt) {
      for (const key in this.outData) {
        this.$set(this.outData, key, '')
      }
      this.$refs.formOut.resetFields()
      evt && this.buttonBlur(evt)
    },
    buttonBlur(evt) {
      let target = evt.target
      if (target.nodeName == 'SPAN' || target.nodeName == 'I') {
        target = evt.target.parentNode
      }
      target.blur()
    },
    // 通过rfid获取标签id
    getIdByRFID() {
      const param = { rfid: this.rfid }
      initData('positioning/label/getIdByRFID', param)
        .then((res) => {
          if (res.data) {
            this.entryData.labelId = res.data
            const param2 = { id: this.entryData.labelId }
            initData('positioning/label/getEntity', param2)
              .then((res2) => {
                this.entryData.labelMAC = res2.data.label
                this.stepActive = 3
              })
              .catch((err2) => {
                this.$message.warning('查询标签信息失败！')
                console.log(err2)
              })
          }
        })
        .catch((err) => {
          this.$message.warning('查询标签ID失败！')
          console.log(err)
        })
    },
    // 通过rfid获取人员信息
    GetPersonByLabelRFID() {
      const param = {
        rfid: this.rfid,
      }
      initData('System/Person/GetPersonByLabelRFID', param)
        .then((res) => {
          if (!!res.data?.labelId) {
            this.outData = {
              id: res.data.id,
              name: res.data.name,
              age: res.data.age,
              sex: res.data.sex,
              entryTime: res.data.entryTime,
              labelMAC: '',
              type: res.data.typeName,
              labelMAC: res.data.labelMAC,
              photoPath: res.data.photoPath,
              oneKeyAlarm: true,
            }
          } else {
            console.log(this.entryData)
            if (!!this.entryData.idNumber) {
              this.getIdByRFID()
            } else {
              this.$message.warning('请先刷身份证！')
            }
          }
          setTimeout(() => {
            this.fullLoading.close()
          }, 1000)
        })
        .catch((err) => {
          this.$message.warning('查询人员信息失败！')
          console.log(err)
        })
    },
    // 通过身份证号获取人员信息
    GetPersonByIdCard() {
      const param = {
        idNumber: this.idCardData.cardno,
      }
      initData('System/Person/GetPersonByIdCard', param)
        .then((res) => {
          console.log(res)
          if (res.data) {
            if (!!res.data.labelId) {
              this.outData = {
                id: res.data.id,
                name: res.data.name,
                age: res.data.age,
                sex: res.data.sex,
                idNumber: res.data.idNumber,
                entryTime: res.data.entryTime,
                labelMAC: '',
                type: res.data.typeName,
                labelMAC: res.data.labelMAC,
                photoPath: res.data.photoPath,
                oneKeyAlarm: true,
                birthday: res.data.birthday,
              }
            } else {
              this.entryData = {
                id: res.data.id,
                name: res.data.name,
                age: res.data.age,
                sex: res.data.sex,
                idType: res.data.idType,
                idNumber: res.data.idNumber,
                lastDate: '',
                labelMAC: '',
                type: res.data.type,
                labelMAC: '',
                photoPath: res.data.photoPath,
                oneKeyAlarm: true,
                birthday: res.data.birthday,
              }
              this.stepActive = 2
            }
          } else {
            this.entryData = {
              name: this.idCardData.name,
              age: this.computeAge(this.idCardData.born),
              sex: this.idCardData.sex,
              idNumber: this.idCardData.cardno,
              lastDate: '',
              labelMAC: '',
              birthday: this.idCardData.born,
              type: '',
              photoPath: `data:image/jpg;base64,${this.idCardData.photobase64}`,
              oneKeyAlarm: true,
            }
            this.stepActive = 2
          }
          this.fullLoading.close()
        })
        .catch((err) => {
          this.$message.warning('查询人员信息失败！')
          console.log(err)
        })
    },
    // 提交发卡信息
    handleSaveEntry(evt) {
      this.$refs.formEntry.validate(async (res) => {
        if (res) {
          this.fullLoading = this.$loading({
            text: '正在提交',
            lock: true,
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          try {
            if (this.entryData?.photoPath.startsWith('data:image/')) {
              let res2 = await uploadBase64(this.entryData.photoPath)
              this.entryData.photoPath = res2.data
            }
            await initData('System/Person/SaveFormJson', this.entryData)
            setTimeout(() => {
              this.handleResetEntry()
              this.fullLoading.close()
              this.stepActive = 1
              this.$message.success('操作成功')
            }, 1000)
          } catch (error) {
            console.log(error)
          }
        }
      })
      this.buttonBlur(evt)
    },
    // 提交收卡信息
    async handleSaveOut(evt) {
      this.buttonBlur(evt)
      this.fullLoading = this.$loading({
        text: '正在提交',
        lock: true,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      try {
        await initData('System/Person/unbind', { id: this.outData.id }).then((res) => {})
        setTimeout(() => {
          this.handleResetOut()
          this.fullLoading.close()
          this.$message.success('操作成功')
        }, 1000)
      } catch (error) {
        console.log(error)
      }
    },
    computeAge(born) {
      const date1 = Dayjs(born)
      const date2 = Dayjs(new Date())
      // console.log(date2.diff(date1, 'year') + 1)
      return date2.diff(date1, 'year')
    },
  },
}
</script>
<style lang="scss">
.withoutTop {
  .register-container {
    height: calc(100vh - 45px) !important;
  }
}
</style>
<style lang="scss" scoped>
.register-container {
  width: 100%;
  background-color: #f2f3f5;
  height: calc(100vh - 140px);
  // height: calc(100vh - 45px);
  .page-header {
    width: 100%;
    height: 50px;
    padding-right: 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    & > span {
      margin-right: 10px;
    }
    span {
      font-size: 16px;
      color: #666666;
      letter-spacing: 0.8px;
      font-weight: 400;
    }
    .el-button {
      margin-left: 20px;
    }
  }
  .page-content {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-around;
    .content-item {
      width: 48%;
      // height: 840px;
      height: calc(100% - 100px);
      background: #ffffff;
      border-radius: 10px;
      .title {
        width: 100%;
        height: 60px;
        font-size: 16px;
        color: #404d54;
        letter-spacing: 0.8px;
        font-weight: 700;
        display: flex;
        align-items: center;
        position: relative;
        .title-line {
          margin-right: 16px;
          width: 3px;
          height: 20px;
          background: #2892f0;
        }
        .title-icon {
          display: none;
          height: 28px;
          margin: 0 10px 0 15px;
          &.entry-icon {
            transform: rotate(45deg);
          }
          &.out-icon {
            transform: rotate(-45deg);
          }
        }
        .el-button {
          position: absolute;
          right: 20px;
        }
      }
      .content-main {
        position: relative;
        height: calc(100% - 60px);
      }
      .el-steps {
        height: 900px;
        position: absolute;
        left: 20px;
        top: 20px;
        ::v-deep .el-step {
          &:nth-child(2) {
            top: -10px;
          }
          &:last-child {
            top: -180px;
          }
        }
        ::v-deep .el-step.is-vertical .el-step__line {
          width: 6px;
          top: 0;
          bottom: 0;
          left: 9px;
          .el-step__line-inner {
            border-width: 3px !important;
          }
        }
      }

      .form-box {
        width: 100%;
        height: 100%;
        border-top: 1px solid #eee;
        padding: 10px 60px 0 60px;
        // position: relative;
        .person-info {
          padding: 20px;
          padding-bottom: 0;
          margin-top: 50px;
          display: flex;
          border: 1px solid #e8e8e8;
          .photo-box {
            width: 125px;
            height: 154px;
            // border: 1px solid #ccc;
            margin-left: 100px;
            img {
              width: 100%;
              height: 100%;
            }
          }
        }
        .card-info {
          padding: 20px;
          padding-bottom: 0;
          border: 1px solid #e8e8e8;
          margin-top: 60px;
        }
        .type-box {
          padding: 20px;
          padding-bottom: 0;
          border: 1px solid #e8e8e8;
          margin-top: 60px;
        }
        .btn-box {
          position: absolute;
          bottom: 50px;
          left: 50%;
          transform: translateX(-50%);
          padding-right: 30px;
          display: flex;
          justify-content: center;
          .el-button {
            margin-right: 20px;
            width: 122px;
            height: 38px;
          }
        }
      }
    }
    .out {
      ::v-deep .el-step__head {
        display: none;
      }
      ::v-deep .el-step__title {
        width: 220px;
        background-image: url('~@/assets/images/visitor/blue_bg.png');
        background-size: contain;
        background-repeat: no-repeat;
        color: #fff;
        padding: 4px 0 0 24px;
        font-weight: 700;
        margin-left: 20px;
      }
    }
    .entry {
      ::v-deep .el-step__title {
        width: 220px;
        background-image: url('~@/assets/images/visitor/grey_bg.png');
        background-size: contain;
        background-repeat: no-repeat;
        color: #666;
        // text-align: left;
        padding: 4px 0 0 24px;
        font-weight: 700;
        &.is-finish {
          background-image: url('~@/assets/images/visitor/blue_bg.png');
          color: #fff;
        }
      }
    }
  }
}
</style>
