<template>
  <Dialog
    :flag="passengerDialogFlag"
    width="440px"
  >
    <div
      id="dialogPassenger"
      ref="dialog"
      tabindex="0"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      @keyup.self.esc="dialogHide"
    >
      <div class="title">
        <span>查看旅客信息</span>
        <i
          class="el-icon-close"
          @click="dialogHide"
        />
      </div>
      <div class="content">
        <template v-if="!userChecked">
          <el-form
            ref="checkForm"
            :model="checkForm"
            :rules="checkRules"
            class="check-form"
            label-position="left"
            label-width="70px"
          >
            <el-form-item
              label="密码"
              prop="password"
            >
              <el-input
                ref="password"
                v-model="checkForm.password"
                show-password
                placeholder="密码"
                name="password"
                tabindex="1"
                class="password"
              />
            </el-form-item>
            <div class="flex-wrap">
              <el-form-item
                label="验证码"
                prop="verificationCode"
                class="flex1"
              >
                <el-input
                  ref="verificationCode"
                  v-model="checkForm.verificationCode"
                  placeholder="请输入验证码"
                  name="verificationCode"
                  tabindex="2"
                  @keyup.enter.native="submitHandler"
                />
              </el-form-item>
              <Identify
                :identifyCode="checkCode"
                style="margin-left: 24px"
                @changeCode="changeCode"
              />
            </div>
          </el-form>
        </template>
        <template v-else>
          <div class="passenger-info-box">
            <img
              v-show="!loading"
              :src="passengerImg"
              alt="旅客信息"
              title="旅客信息"
              class="passenger-info-img"
            />
          </div>
        </template>
      </div>
      <div
        v-if="!userChecked"
        class="footer"
      >
        <el-button
          type="primary"
          size="small"
          @click="submitHandler"
        >提交</el-button>
        <el-button
          size="small"
          @click="dialogHide"
        >取消</el-button>
      </div>
    </div>
  </Dialog>
</template>

<script>
import Dialog from '@/layout/components/Dialog'
import Identify from '@/views/login/identify'
import { mapGetters } from 'vuex'
import { GetCheckCode, CheckUser } from '@/api/temp'
import { GetPassengerInfo } from '@/api/flight'
// import { getToken } from '@/utils/auth'
import MD5 from 'blueimp-md5'
import '@/config/staticConfig.js'
import '@/config/config.js'

const noDataImage = require('@/assets/logo/nodata.png')

export default {
  name: 'PassengerDialog',
  components: { Dialog, Identify },
  computed: {
    ...mapGetters([
      'passengerDialogFlag',
      'passengerQueryParams',
      'userChecked',
    ]),
  },
  data() {
    return {
      checkForm: {
        password: '',
        verificationCode: '',
      },
      checkCode: null,
      checkRules: {
        password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        verificationCode: [
          { required: true, trigger: 'blur', message: '请输入验证码' },
        ],
      },
      passengerImg: '',
      loading: false,
    }
  },
  watch: {
    passengerDialogFlag(val) {
      this.$nextTick(() => {
        this.$refs['dialog']?.focus()
      })
      this.passengerImg = noDataImage
      if (val) {
        if (this.userChecked) {
          this.getPassengerInfo()
        } else {
          this.getCheckCode()
        }
      }
    },
  },
  methods: {
    dialogHide() {
      this.$refs['checkForm']?.resetFields()
      this.$store.dispatch('app/togglePassengerDialogFlag', false)
    },
    //获取动态验证码
    async getCheckCode() {
      try {
        const { code, data, message } = await GetCheckCode({
          appToken: PLATFROM_CONFIG.tempAppToken,
        })
        if (Number(code) === 0) {
          this.checkCode = data
        } else {
          this.$message.error(message || '失败')
        }
      } catch (error) {
        this.$message.error('失败')
      }
    },
    //验证码重新获取
    changeCode() {
      this.getCheckCode()
    },
    submitHandler() {
      this.$refs['checkForm'].validate(async valid => {
        if (valid) {
          try {
            await this.checkUser()
            this.$refs['checkForm']?.resetFields()
            this.$store.dispatch('user/setUserChecked', true)
            await this.getPassengerInfo()
          } catch (error) {
            this.$message.error(error?.message || '失败')
          }
        }
      })
    },
    async checkUser() {
      this.loading = true
      try {
        const { code, data, message } = await CheckUser({
          userId: PLATFROM_CONFIG.tempUserId,
          password: MD5(this.checkForm.password.replace(/s+/g, '')),
          verificationCode: this.checkForm.verificationCode,
        })
        if (Number(code) !== 0) {
          throw new Error(message || '失败')
        }
      } catch (error) {
        this.loading = false
        this.getCheckCode()
        return Promise.reject(error.message)
      }
      this.loading = false
    },
    async getPassengerInfo() {
      this.loading = true
      try {
        const { passengerName, flightNO, flightDate } =
          this.passengerQueryParams
        const { code, data, message } = await GetPassengerInfo({
          id: '1803430',
          dataContent: [passengerName, flightNO, flightDate],
        })
        if (Number(code) === 0) {
          if (data?.verifyCodeImage) {
            this.passengerImg = `data:image/png;base64,${data.verifyCodeImage}`
          }
        } else {
          throw new Error(message || '失败')
        }
      } catch (error) {
        this.loading = false
        return Promise.reject(error.message)
      }
      this.loading = false
    },
  },
}
</script>

<style lang="scss">
#dialogPassenger {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0;
    .el-icon-close {
      margin-right: 16px;
      cursor: pointer;
    }
  }
  .content {
    margin: 0;
    .el-form {
      padding: 30px 20px 6px;
    }
    .passenger-info-box {
      width: 100%;
      height: 180px;
      padding: 20px;
      text-align: center;
      .passenger-info-img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
        vertical-align: middle;
      }
    }
  }
  .footer {
    padding: 0 22px;
    height: 56px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    background: #f0f5ff;
    .el-button {
      width: 80px;
      border-radius: 4px;
      font-family: 'Microsoft YaHei';
      &:not(:last-child) {
        margin-right: 14px;
      }
    }
  }
}
</style>
