<template>
  <a-form-item v-if="record.type === 'phone'">
    <a-form-item :label="record.label" v-if="record.type === 'phone'">
      <a-input
        :style="`width:${record.options.width}`"
        :disabled="disabled || record.options.disabled"
        :placeholder="record.options.placeholder"
        :type="record.options.type"
        :allowClear="record.options.clearable"
        :maxLength="record.options.maxLength"
        @change="handleChange($event.target.value, record.model)"
        v-decorator="[
          record.model, // input 的 name
          {
            initialValue: record.options.defaultValue, // 默认值
            validateTrigger: 'blur',
            rules: record.rules // 验证规则
          }
        ]"
      />
    </a-form-item>

    <a-form-item v-if="record.type === 'phone' && record.options.smsVerification">
      <div class="verify_box">
        <a-input
          class="verify_input"
          placeholder="请输入验证码"
          :maxLength="4"
          @change="handleChange($event.target.value, record.model.replace('phone', 'verify'))"
          v-decorator="[
            record.model.replace('phone', 'verify'), // input 的 name
            {
              initialValue: '', // 默认值
              validateTrigger: '',
              validateFirst: true,
              rules: [...record.verifyRules, { asyncValidator: this.valiValidate }] // 验证规则
            }
          ]"
        />
        <a-button
          :disabled="countDown.status ? true : false"
          type="primary"
          class="verify_button"
          @click="toGetVerify(record.model)"
          >{{ countDown.status ? `${countDown.min}s` : '获取验证码' }}</a-button
        >
      </div>
    </a-form-item>
  </a-form-item>

  <!-- 地区选择-->
  <a-form-item :label="record.label" v-else-if="(record.type = 'distinct')">
    <a-cascader
      :placeholder="record.options.placeholder"
      :showSearch="record.options.showSearch"
      :options="distinctData"
      :disabled="disabled || record.options.disabled"
      :allowClear="record.options.clearable"
      @change="handleChange($event, record.model)"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue,
          rules: record.rules
        }
      ]"
    />
  </a-form-item>
</template>
<script>
import { verifySms, getVerify } from '@/api/common.js'
import provinceData from './distinction.json'

export default {
  name: 'CustomComponent',
  // eslint-disable-next-line vue/require-prop-types
  props: ['record', 'formConfig', 'disabled', 'dynamicData', 'form'],

  data() {
    return {
      countDown: { status: false, min: 60 }
    }
  },

  computed: {
    distinctData() {
      const provinceList = []
      const keyArr = Object.keys(provinceData)
      const includesCity = ['city', 'distinct'].includes(this.record.options.rangeSetting)
      const includeDistinct = ['distinct'].includes(this.record.options.rangeSetting)
      keyArr.forEach(v => {
        const item = includesCity ? { value: v, label: v, children: [] } : { value: v, label: v }
        if (includesCity) {
          const secondLevel = provinceData[v]
          Object.keys(secondLevel).forEach(v1 => {
            const item2 = includeDistinct ? { value: v1, label: v1, children: [] } : { value: v1, label: v1 }
            if (includeDistinct) {
              secondLevel[v1].forEach(v2 => {
                const item3 = { value: v2, label: v2 }
                item2.children.push(item3)
              })
            }

            item.children.push(item2)
          })
        }

        provinceList.push(item)
      })
      return provinceList
    },
    customComponent() {
      // 计算需要显示的组件
      const customComponentList = {}
      if (window.$customComponentList) {
        // 将数组映射成json
        window.$customComponentList.forEach(item => {
          customComponentList[item.type] = item.component
        })
      }
      return customComponentList[this.record.type]
    }
  },
  methods: {
    handleChange(value, key) {
      this.$emit('change', value, key)
    },

    //点击提交按钮时校验手机号
    valiValidate(rule, value) {
      return new Promise((resolve, reject) => {
        try {
          this.form.validateFields([rule.field.replace('verify', 'phone')], async (error, phoneValue) => {
            if (error) {
              console.log(error)
              resolve()
              return
            }
            const phoneNum = phoneValue[rule.field.replace('verify', 'phone')]
            verifySms({ smsCode: value, phoneNum })
              .then(res => {
                resolve()
                console.log(res)
              })
              .catch(error => {
                if (error.code === '106') {
                  reject('短信验证码错误')
                } else {
                  this.$message.error(error.message)
                }
                console.log(error)
              })
          })
        } catch (error) {
          console.log(error)
        }
      })
    },

    //获取验证码
    toGetVerify(phoneModel) {
      this.form.validateFields([phoneModel], async (error, phoneValue) => {
        console.log(phoneValue)
        if (error) {
          console.log(error)
          return
        }
        const phoneNum = phoneValue[phoneModel]
        getVerify({ phoneNum })
          .then(res => {
            this.$message.success(res.message)
            console.log(res)
            const timer = setInterval(() => {
              if (this.countDown.min > 0) {
                this.countDown = { status: true, min: this.countDown.min - 1 }
              } else {
                clearInterval(timer)
                this.countDown = { status: false, min: 60 }
              }
            }, 1000)
          })
          .catch(error => {
            console.log(error)
            this.$message.error(error.message)
          })
      })
    }
  }
}
</script>
<style scoped lang="less">
.verify_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .verify_input {
    flex: 1;
  }
  .verify_button {
    width: 100px;
    margin-left: 5%;
  }
}
</style>
