<template>
  <div class="comp-car-card">
    <el-form ref="formRef" :model="form" :rules="formRules" size="small" label-position="top" @submit.native.prevent>
      <el-row>
        <el-col :span="24">
          <el-form-item label="车辆VIN码" prop="vin">
            <div class="el-input-wrapper">
              <el-input
                :value="form.vin"
                clearable
                maxlength="50"
                placeholder="请输入您的VIN码"
                class="ccc-vin-input"
                @input="onVinInput"
                @focus="onVinFocus"
                @blur="onVinBlur"/>
            <!-- <el-button v-if="isInApp" class="ccc-add-vin-btn" type="primary" icon="el-icon-camera" plain size="small" @click.stop="handleTakeScan">扫码添加</el-button> -->
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="add-iccid-btn-wrapper">
            <el-form-item label="ICCID列表" prop="iccidList">
              <el-button :disabled="!enableAddBtn" class="ccc-add-iccid-btn" type="primary" icon="el-icon-plus" plain size="small" @click.stop="clickAddIccid">添加ICCID卡</el-button>
            </el-form-item>
          </div>
          <div class="iccid-table-wrapper">
            <el-table
              v-loading="loading"
              :data="iccidList"
              style="width: 100%">
              <el-table-column
                type="index"
                label="序号"
                width="180"/>
              <el-table-column
                prop="iccid"
                label="ICCID"
                min-width="320"
              >
                <template slot-scope="scope">
                  <template v-if="scope.row.state === 'readonly'">{{ scope.row.iccid }}</template>
                  <template v-else-if="scope.row.state === 'edit'">
                    <el-form :ref="scope.row._formId" :model="scope.row" :rules="iccidRules" size="small" label-width="0" @submit.native.prevent>
                      <el-form-item prop="iccid" class="ccc-el-form-item">
                        <el-input :ref="scope.row._inputId" :value="scope.row.iccid" clearable maxlength="50" class="ccc-iccid-el-input" @input="onIccidInput($event, scope.row)"/>
                      </el-form-item>
                    </el-form>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-link v-if="canDelIccidRecord(scope)" class="ccc-el-link-del" @click.stop="clickIccidItemDel(scope)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <comp-confirm
      :show.sync="showDelConfirm"
      :desc="delConfirmDesc"
      :show-cancel-btn="true"
      @on-sure="onDelSure"
    />
    <comp-confirm
      :show.sync="showTipConfirm"
      :desc="tipConfirmDesc"
    />
  </div>
</template>

<script>
import bridge, { isInApp } from '@/utils/bridge'
import { CancelToken } from 'axios'
import { queryUnBindCardByVin, queryBindCardByVin } from '@/api/iccid'
import CompConfirm from '@/components/CompConfirm'

let gid = 0

export default {
  name: 'CompCarCard',
  components: {
    CompConfirm
  },
  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    maxIccidLength: {
      type: Number,
      default: 5
    },
    // 特殊业务卡解绑重新封装依据vin获取iccid等信息 SPECIAL
    soucePage: {
      type: String,
      default: () => ''
    },
    // 是否查询绑定的iccid true：已绑定 false：未绑定
    isBind: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const checkVin = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入您的vin码'))
      } else if (!this.checkVin(value)) {
        callback(new Error('vin码格式不正确'))
      } else {
        callback()
      }
    }
    const checkIccid = (rule, value, callback) => {
      if (value !== '') {
        if (this.checkIccid(value)) {
          callback()
        } else {
          callback(new Error('iccid格式不正确'))
        }
      } else {
        if (this.validIccidList.length) {
          callback()
        } else {
          callback(new Error('请输入iccid'))
        }
      }
    }
    return {
      form: {
        vin: '',
        iccidList: []
      },
      formRules: {
        vin: [
          { required: true, validator: checkVin, trigger: 'blur' }
        ],
        iccidList: [
          { type: 'array', required: true, message: '请添加ICCID数据', trigger: '' }
        ]
      },
      iccidRules: {
        iccid: [
          { required: true, validator: checkIccid, trigger: 'blur' }
        ]
      },
      isInApp,
      iccidList: [],
      loading: false,
      showDelConfirm: false,
      delConfirmDesc: '确认删除当前行吗？',
      showTipConfirm: false,
      tipConfirmDesc: '',
      inputIsFocus: false
    }
  },
  computed: {
    newAddedIccidList() {
      return this.iccidList.filter(item => item.state === 'edit')
    },
    validIccidList() {
      return this.iccidList.filter(item => (item.state === 'edit' ? this.checkIccid(item.iccid) : (item.iccid !== '')))
    },
    enableAddBtn() {
      const ret = (!this.inputIsFocus && !this.loading) || (this.inputIsFocus && !this.form.vin)
      this.$emit('on-canenable', ret)
      return ret
    }
  },
  watch: {
    data() {
      this.updateInternalData()
    },
    iccidList(val) {
      if (this._iccidListInitMount) {
        this._iccidListInitMount = false
        return
      }
      if (val.length) {
        this.$refs.formRef.clearValidate('iccidList')
      } else {
        this.$refs.formRef.validateField('iccidList')
      }
    }
  },
  created() {
    this._iccidListInitMount = true
    this.init()
  },
  methods: {
    /**
     * 扫码功能
     */
    handleTakeScan() {
      bridge.scanCode(true, code => {
        this.form.vin = code
        this.onVinBlur()
      })
    },

    errorTips(errMsg) {
      this.showTipConfirm = true
      this.tipConfirmDesc = errMsg
    },

    init() {
      this.updateInternalData()
    },
    updateInternalData() {
      if (typeof this.data === 'object' && this.data !== null) {
        this.form.vin = this.data.vin || ''
        this.form.iccidList = []
        this.iccidList = Array.isArray(this.data.iccidList) ? [...this.data.iccidList] : this.getDefaultIccidList()
      } else {
        this.form.vin = ''
        this.form.iccidList = []
        this.iccidList = this.getDefaultIccidList()
      }
    },
    getDefaultIccidList() {
      return []
    },

    // 点击添加 ICCID 按钮
    clickAddIccid() {
      if (this.iccidList.length >= this.maxIccidLength) {
        this.errorTips(`最多只能添加${this.maxIccidLength}条ICCID数据`)
        return
      }
      const newIccid = this.makeIccidTemplate()
      newIccid.state = 'edit'
      this.iccidList.push(newIccid)
      this.$nextTick(() => {
        this.$refs[`${newIccid._inputId}`].focus()
      })
    },
    // 点击删除 ICCID 记录按钮
    clickIccidItemDel(scope) {
      this.showDelConfirm = true
      this._curDelIndex = scope.$index
    },
    // 确认删除 ICCID
    onDelSure() {
      this.iccidList.splice(this._curDelIndex, 1)
    },
    onIccidInput($event, cur) {
      if ($event === '' || $event.length <= 20) {
        cur.iccid = $event
      }
    },
    canDelIccidRecord(scope) {
      // 卡解绑查询出来的数据不能删除
      if (this.$route.name === 'CardUnbindingStepOne') {
        if (scope.row.state === 'readonly') {
          return false
        }
      }
      return true
    },

    onVinFocus() {
      this.inputIsFocus = true
    },
    // 光标移开 vin 码输入框时的动作
    onVinBlur() {
      this.inputIsFocus = false
      this.$refs.formRef.validateField('vin', errorMsg => {
        if (!errorMsg) {
          this.onVinBlurHandler()
        } else {
          if (this._req) {
            this._req.cancel()
          }
        }
      })
    },
    // 光标移开 vin 码输入框处理
    async onVinBlurHandler() {
      this.loading = true
      const retData = await this.getIccidListByVin()
      this.loading = false
      if (retData === 'cancel') {
        return
      }
      const pendingAdd = retData.iccidList || []
      this.iccidList = [
        ...this.normalizeIccidList(pendingAdd.slice(0, this.maxIccidLength))
      ]
      this.prevIsBind = this.isBind
      this._preVin = this.form.vin
    },
    // vin 码输入长度限制
    onVinInput($event) {
      if ($event === '' || $event.length <= 17) {
        this.form.vin = $event
      }
    },

    checkVin(vin) {
      return vin.length === 17
    },
    checkIccid(iccid) {
      return typeof iccid === 'string' && iccid !== '' && iccid.length === 20
    },

    async getIccidListByVin() {
      if (this._req) {
        this._req.cancel()
      }
      this._req = CancelToken.source()

      let retData = null
      const searchParams = {
        vin: this.form.vin
      }
      try {
        // 接口请求方法
        const reqFuction = this.isBind ? queryBindCardByVin : queryUnBindCardByVin
        // 开始请求接口
        const respData = await reqFuction({
          data: {
            ...searchParams,
            ...(this.soucePage === 'BIND' ? { filter: true } : {})
          },
          cancelToken: this._req.token,
          hideToast: true
        })
        retData = respData || {}
      } catch (e) {
        if (e.code === '_CANCEL_REQUEST_') {
          retData = 'cancel'
        } else {
          // 其他错误需要提示
          this.errorTips(e.message || '系统异常')
        }
      }
      return retData || {}
    },

    // ICCID 记录数据模板
    makeIccidTemplate() {
      return {
        iccid: '',
        state: 'readonly',
        _formId: gid++,
        _inputId: gid++
      }
    },
    // 标准化远程获取的 ICCID 记录数据
    normalizeIccidList(list = []) {
      return list.map(item => {
        const newIccid = this.makeIccidTemplate()
        newIccid.iccid = item
        newIccid.state = 'readonly'
        return newIccid
      })
    },

    async validateForm1(isErrorAnchor = false) {
      this.form.iccidList = JSON.parse(JSON.stringify(this.iccidList))
      try {
        await this.$refs.formRef.validate()
        return true
      } catch (e) {
        if (isErrorAnchor) {
          this.$refs.formRef.fields.filter(item => item.validateState === 'error')[0].$el.scrollIntoView(true)
        }
        let temp = {
          anchor: () => {
            this.$refs.formRef.fields.filter(item => item.validateState === 'error')[0].$el.scrollIntoView(true)
            temp = null
          }
        }
        throw temp
      }
    },
    async validateIccidListForm2(isErrorAnchor = false) {
      const validateIccidList = this.newAddedIccidList
      for (let i = 0, len = validateIccidList.length; i < len; i++) {
        const item = validateIccidList[i]
        try {
          await this.$refs[item._formId].validate()
        } catch (e) {
          if (isErrorAnchor) {
            this.$refs[item._inputId].$el.scrollIntoView(true)
          }
          let temp = {
            anchor: () => {
              this.$refs[item._inputId].$el.scrollIntoView(true)
              temp = null
            }
          }
          throw temp
        }
      }
      return true
    },

    // 校验
    async validate(isErrorAnchor = false) {
      try {
        await Promise.all([
          this.validateForm1(),
          this.validateIccidListForm2()
        ])
        return true
      } catch (e) {
        throw e
      }
    },
    // 获取数据
    getFormData() {
      return {
        vin: this.form.vin,
        iccidList: this.iccidList.map(item => item.iccid)
      }
    },
    // 获取待缓存数据
    getPendingCacheData() {
      return {
        vin: this.form.vin,
        iccidList: JSON.parse(JSON.stringify(this.iccidList))
      }
    }
  }
}
</script>

<style lang="scss">
.comp-car-card {
  .ccc-vin-input {
    width: 44%;
  }
  .ccc-iccid-el-input {
    width: 60%;
  }
  .ccc-el-form-item {
    .el-form-item__error {
      left: 62%;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .add-iccid-btn-wrapper {
    margin-bottom: 8px;
    .ccc-add-iccid-btn {
      border-color: #B9CFFF;
      color: #2A68FF;
      background: #F5F7FF;
      &:hover {
        border-color: #5489FF;
        background: #F5F7FF;
        color: #5489FF;
      }
    }
  }
  .iccid-table-wrapper {
    .el-form-item {
      margin-bottom: 0 !important;
    }
    .ccc-el-link-del {
      font-size: 14px;
      color: #2A68FF;
      &:hover {
        &:after {
          display: none;
        }
      }
    }
  }
  .el-input-wrapper {
    display: flex;
    .ccc-add-vin-btn {
      margin-left: 12px;
    }
  }
}
</style>
